Lennie
Lennie

Reputation: 3297

Object As Interface

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> ?

Upvotes: 13

Views: 34421

Answers (3)

quentin-starin
quentin-starin

Reputation: 26638

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.

Upvotes: 1

davehauser
davehauser

Reputation: 5944

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);
    }
}

Upvotes: 3

jdehaan
jdehaan

Reputation: 19928

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.

Upvotes: 24

Related Questions