Object As Interface

25,098

Solution 1

You do not need to cast the object if it's of a type that implements the interface.

IMyBehaviour subject = myObject;

If the type of myObject is just Object then you need to cast. I would do it this way:

IMyBehaviour subject = myObject as IMyBehaviour;

If myObject does not implement the given interface you end up with subject being null. You will probably need to check for it before putting it into a list.

Solution 2

Here's a function that

cast[s] the object into the interface and then place it into a List

public void CastAndAdd(object objThatImplementsMyInterface, IList<IMyInterface> theList) 
{
    theList.Add((IMyInterface)objThatImplementsMyInterface);
}

I mean, if you've already found the object and have the list, this is quite elementary. Just replace IMyInterface with whatever interface you're using.

Or generalize from this as appropriate for your specific code.

Solution 3

public interface IFoo { }
public class Foo : IFoo {}

private SomeMethod(object obj)
{
    var list = new List<IFoo>();
    var foo = obj as IFoo;

    if (foo != null)
    {
        list.Add(foo);
    }
}
Share:
25,098
Lennie
Author by

Lennie

Updated on July 17, 2020

Comments

  • Lennie
    Lennie almost 4 years

    I've got an object that implements an interface, I then find that object using reflection. How can I cast the object into the interface and then place it into a List<IInterface> ?