C# FAQ: testing if a generic type parameter is of particular type
Posted: (EET/GMT+2)
Today's blog post is a quick C# frequently asked question and a tip for better code. The question is: if you have a generic method that uses a type definition "T" for a return type of the method, how can you successfully test whether "T" is of particular type?
The correct and easiest way to do this is to say:
private T MyGenericMethod(string valueA, string valueB) { if (typeof(T) == typeof(int)) { // T is an "int" ... } else { throw new InvalidOperationException("The generic type T is not of a known type"); } ... }
Here, the type "T" is tested whether it is an integer type (System.Int32).
Note that while the C#'s handy is operator can be used to test for type matches, it does not work with generic type parameters.
Happy coding!