Object As Interface
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);
}
}
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.
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.