Reputation: 87047
I'm trying to pass in a list of System.Type
into a method. Not instances but Type
's.
Now there's a catch: I wish to restrict the Type
by an interface.
For example, imagine i have this...
public interface IFoo
public class Cat : IFoo
public class Dog : IFoo
then this..
public void MyMethod(IEnumerable<Type> foos)
but only allow Cat
's and Dog
's and not anything else.
Usually, I do this:
public void MyMethod(IEnumerable<IFoo> foos)
but that is asking for some foo instances, which is not what I'm trying to do.
Upvotes: 2
Views: 86
Reputation: 62
public static void MyMethod<T>(Type theType) where T : ICat {}
ICat icat = new Class2();
//This will not work because its the wrong type
IDog idog = new Class2();
MyMethod<ICat>(icat.GetType());
Upvotes: 0
Reputation: 11514
public void MyMethod<T>(T theType) where T : List<Cat>, List<Dog>
Upvotes: -1
Reputation: 35464
I assume that your method only wants a list of instances (objects) that implement IFoo
. If so then use IEnumerable<IFoo>
; as in:
public void MyMethod(IEnumerable<IFoo> foos) { ... }
Update
There is no way to declare that the method only accepts a list of Type
s that implement an interface
. You need to do the validation in your own code.
if (!foos.Any(t => t.GetInterfaces().Contains(typeof(IFoo)))
throw new ArgumentException(...);
Upvotes: 3