Maybe it is pretty simple, but I'm not in use with the type Type
and it's uses.
Say I want to create a List<T>
either with T
=Double
or T
=UInt32
, depending on the result of some function, say public static Type CheckType(String input);
In code:
Type t = Program.CheckType(someInput); // it returns typeof(Double) or typeof(UInt32)
if (t == typeof(Double))
List<Double> l = new List<Double>();
else
List<UInt32> l = new List<UInt32>();
I know the above code won't compile because I'm letting l
to have two different meanings (a list of double and a list of unsigned int)... So it leads to my question:
- Is there a way to avoid the
if
in the above code?
Something similar to this:
Type t = Program.CheckType(someInput);
List<t> l = new List<t>(); // I know this won't compile either...
I mean, that would generically instantiate a generic List...
Thank you in advance!
EDIT:
This is NOT a duplicate of the marked question for only one reason: Double
and UInt32
are not Anonymous types! The question, here, is how to determine the type of some input data (which will be Type T
=typeof(Double)
or Type T
=typeof(UInt32)
, for example) and, thus, create a generic SampleClass<T>
based on that input data type, T
!
In other words: determine some Type T
in the runtime and, then, instantiate a generic type with the determined type T
. Sorry if I didn't make that clear before...
PS: I used List<T>
as an example for SampleClass<T>
.