1

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

0

2 Answers 2

3

Simply

List<IMyType> list = new List<IMyType>();

Will do the trick you don't need any fancy stuff

Sign up to request clarification or add additional context in comments.

Comments

1
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

2 Comments

Thank's Peter.Actually I want a list of types, not a list of objects of that type
You must customize your list and catch exceptions on Add method and Index Property. Because you determine every type in C# inherited Type base

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.