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
ifin 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>.
List<T>as an example... My real problem is aHistogram<T>, in which the bins may be integers or doubles; I know my life would be much easier if I just cast all values to doubles, but I wouldn't like to do that, as it could mess with the precision of integers... In fact, when I retrieve the Histogram, I won't need to cast to the input type, as I just retrieve the values of the bins in order to write them to a file... if you know what I mean... I use a lib by John Skeet to make operations between generic numerical typesTDoubleandUInt32are not Anonymous types! The question, here, is how to determine the type of some input data and, thus, create a genericList<T>or anySampleClass<T>based on that input data type!