I have:
- an interface : IMyType
- some classes implementing it : MyType1 , MyType2 , MyType3
How can I define a list of type IMyType?
var myList = new List<Type> {typeof (MyType1), typeof (MyType2)};
The above list does not force types to be IMyType type, and I can add any type to the list
class Program
{
static void Main(string[] args)
{
IList<IMyType> lst = new List<IMyType>();
lst.Add(new MyType1());
lst.Add(new MyType2());
lst.Add(new MyType3());
foreach (var lstItem in lst)
{
Console.WriteLine(lstItem.GetType());
}
}
}
public interface IMyType { }
public class MyType1 : IMyType { }
public class MyType2 : IMyType { }
public class MyType3 : IMyType { }
If you want determine what's implementation class, you can use obj.GetType() or operator obj is MyType1
Simply
List<IMyType> list = new List<IMyType>();
Will do the trick you don't need any fancy stuff