Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch based on generic argument type

In C# 7.1 the below is valid code:

object o = new object();
switch (o)
{
    case CustomerRequestBase c:
        //do something
        break;
}

However, I want to use the pattern switch statement in the following scenario:

public T Process<T>(object message, IMessageFormatter messageFormatter) 
    where T : class, IStandardMessageModel, new()
{
    switch (T)
    {
        case CustomerRequestBase c:
            //do something
            break;
    }
}

The IDE gives me the error "'T' is a type, which is not valid in the given context" Is there an elegant way to switch on the type of a generic parameter? I get that in my first example you are switching on the object and the second I'd want to switch on the type T. What would be the best approach to do this?

like image 909
David Christopher Reynolds Avatar asked Dec 03 '18 16:12

David Christopher Reynolds


People also ask

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.

How do you know if a type is generic?

To examine a generic type and its type parametersGet an instance of Type that represents the generic type. In the following code, the type is obtained using the C# typeof operator ( GetType in Visual Basic, typeid in Visual C++). See the Type class topic for other ways to get a Type object.

What is generic type constraint?

A type constraint on a generic type parameter indicates a requirement that a type must fulfill in order to be accepted as a type argument for that type parameter. (For example, it might have to be a given class type or a subtype of that class type, or it might have to implement a given interface.)

What is generic MVC?

Generic is a class which allows the user to define classes and methods with the placeholder.


1 Answers

I agree that there are situation when this approach is faster and not so ugly, and also agree that in any case a better solution should be found, but sometimes the trade-off doesn't pay... so here is a solution (C# 9.0)

return typeof(T) switch
{
    Type t when t == typeof(CustomerRequestBase) => /*do something*/ ,
    _ => throw new Exception("Nothing to do")
};
like image 108
Mosè Bottacini Avatar answered Oct 02 '22 14:10

Mosè Bottacini