Object as an interface

I have an object that implements an interface, and then I discover this object with reflection ... How can I pass an object to an interface and then put it in a list?

+6
c #
source share
3 answers

You do not need to throw an object if it has a type that implements an interface.

IMyBehaviour subject = myObject; 

If myObject is just an Object , then you need to throw. I would do it like this:

 IMyBehaviour subject = myObject as IMyBehaviour; 

If myObject does not implement this interface, you will get subject null . You will probably need to check it before listing it.

+14
source share

Here is the function that

enter [s] the object in the interface and then put it in the list

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

I mean, if you have already found an object and have a list, this is pretty basic. Just replace "IMyInterface" with any interface you use. Or generalize this if appropriate for your specific code.

+1
source share
 public interface IFoo { } public class Foo : IFoo {} SomeMethod(object obj) { var list = new List<IFoo>(); var foo = obj as IFoo; if(foo != null) { list.Add(foo); } } 
+1
source share

All Articles