I want to go through a switch statement to determine what type to make something that contains a generic with.
Below is a silly, but illustrative bit of code that shows what I am trying to do:
Type tempType;
switch(number)
{
case 0:
tempType = typeof(int);
break;
case 1:
tempType = typeof(bool);
break;
case 2:
tempType = typeof(long);
break;
}
List<tempType> theList = new List<tempType>();
When I try this it gives the error:
The type or namespace name ‘tempType’ could not be found (are you missing a using directive or an assembly reference?)
My assumption on why is because it is looking for types that are globally available there, and is not looking in the local member variables of this method. How can I do something like this?
EDIT:
To give a bit more context, I am trying to use Quartz.NET, and I am trying to create different jobs with it, so each of the types in this example are different Job Classes, each with their specific execute commands. the different cases are when I want to access that specific job class. Then I would create the job via:
tempJob = JobBuilder.Create<tempType>()
.WithIdentity("SomeJob " + i)
.UsingJobData()
.Build();
To use generics the compiler has to know the type at compile-time; you can not determine the type at runtime and create a generic. If you don’t know the type until runtime, you would generally just use a List.
You could use reflection to create a particular type instantiation at runtime, but instantiating to a particular type is primarily useful to the compiler for type inference; if the compiler doesn’t know, there’s not a lot of reason for your program to care at runtime.