C# FAQ: How can I cast a concrete type, such as "int", to a generic type "T"?
Posted: (EET/GMT+2)
C#'s generic types are a blessing, but sometimes, they are a little tricky to use. Today's blog post is a quick solution to the problem of casting a concrete type, such as "int" or "string" back to a generic type "T".
Here's how to do it:
if (typeof(T) == typeof(int))
{
int.TryParse(inputA, out int a);
int.TryParse(inputB, out int b);
result = operation((T)(object)a, (T)(object)b);
}
Thus, you would first cast your variable type to an object (the base class for all types), and then cast it again to type "T".
Problem solved!
Happy July 4th to all US readers!