Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 821
Lennie Avatar asked Aug 25 '10 22:08

Lennie


2 Answers

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.

like image 69
jdehaan Avatar answered Sep 21 '22 13:09

jdehaan


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);
    }
}
like image 32
davehauser Avatar answered Sep 19 '22 13:09

davehauser