Tech Tip: Determining object type of a Generic Type using the Switch Statement

Updated on: 09 Jun 2020

Recently, I had to create a generic function. This generic function should be able to take in a generic type and execute code based on the generic type passed into the function and then return the same type as the result.

Consider the function below as an example for the above:

public static class ValueConverter
{
    public static T ConvertValue<T>(string value)
    {
        //code here
    }
}
example.cs

So if string is passed into the function as T, the function should execute some code which will consequently return a string like shown in a sample use below:

public string Test()
{
    string result = ValueConverter.ConvertValue<string>("Hello world");
}
example.cs

And if a user-defined type is passed as T into the function, it should execute a different set of code and return an object of the same user-defined type as shown below:

public string Test()
{
    Person result = ValueConverter.ConvertValue<Person>("Hello world");
}
example.cs

After much research & deliberation, I ended up with the following code to solve the problem:

public static T ConvertValue<T>(string value)
{
    switch (typeof(T))
    {
        case Type type when type == typeof(Person):
            //execute code
        case Type type when type == typeof(IEnumerable<Person>):
            //execute code
        case Type type when type == typeof(string):
            //execute code
        case Type type when type == typeof(decimal):
            //execute code
        case Type type when type == typeof(double):
            //execute code
        default:
            //execute code
    }
}
sample-solution.cs

Bear in mind that this solution leverages on pattern matching; which is only available in C# version 7 and onwards. It will not work on older versions of C#.

It may not be the best approach but it is what I could come up with for now. I am open to suggestions for improvements.

Here are some more posts