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>
?
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With