Convert to unknown generic type: ChangeType<T>
Problem
When you create a generic method (Foo) or generic class (Bar), it often happens that you need to change (or convert) a type to T. In these situations you need a ChangeType function that changes "any" type to T. Unfortunately this is not a standard method. The Cast() method of Linq looks like a solution but it is very limited. This wil not work for a lot of types:
Examples
Obvious examples where you need a ChangeType method are:
- Returns T but the parameter of the method is an object, string, XML or data from a DataReader.
- Method returns T1 but the parameters of the method is T2: T1 Foo(T2 value))
An obvious example is:
A less obvious example is:
How to use ChangeType in your project?
The code of the GenericRandom class can be found on
Github. If you use .Net 6, you can also use the
Q11.Tools Nuget package..