How to instantiate a list of System.Types from a literal?

118 Views Asked by At

I have a few types:

public ClassA
{
}

public ClassB
{
}

public ClassC
{
}

Now I would like to store some of them in a list?

Some of the failed approaches I've tried:

List<System.Type> allowedTypes = new List<System.Type>{ ClassA, ClassC };

List<System.Type> allowedTypes = new List<System.Type>{ System.Type.GetType(ClassA), Systme.Type.GetType(ClassC) };

List<System.Type> allowedTypes = new List<System.Type>{ ClassA.GetType(), ClassC.GetType() };

The working approaches I am aware of seem pretty cumbersome:

List<System.Type> allowedTypes = new List<System.Type>{ new ClassA().GetType(), new ClassB().GetType() };

This approach is cumbersome because it requires ClassA and ClassC to be specifically prepared for such a use.

List<System.Type> allowedTypes = new List<System.Type>{ System.Type.GetType("ClassA"), System.Type.GetType("ClassC") };

If there's no way to get rid of these magic strings then well, I guess I should embrace them...

1

There are 1 best solutions below

0
On

The correct approach would be the typeof expression:

List<System.Type> allowedTypes = 
        new List<System.Type>(){ typeof(ClassA), typeof(ClassC) };