I've used typeof(T), typeof(T) t when t == typeof(X), typeof(T).Name, and typeof(T).FullName variations (suggested in other answers), but I've never been happy with any of them. They're either too complex, or too slow.
typeof(T) when t == typeof(X) is probably the best, however, it's performance is questionable as the compiler seems to treat the when clauses as a series of if ... else if ... statements. Run the debugger and trace it to see what I mean. String variations have similar concerns - getting type names and comparing strings seems like unnecessary overhead.
What we really want is a solution that uses native switch hash lookup behavior for optimal performance.
So here's another solution that reduces complexity:
- Create a dummy variable T
- Assign an new value
- Use the dummy variable of type T in the switch statement
Result:
public T Process<T>(object message, IMessageFormatter messageFormatter)
where T : class, IStandardMessageModel, new()
{
T dummy = Activator.CreateInstance(typeof(T));
switch (dummy)
{
case CustomerRequestBase _:
//do something
break;
}
}
T requires a constructor, which in this case is perfect as the method is qualified with where T: class, new() - being a class and having a default constructor. So we can instantiate the dummy variable, and use that dummy variable to execute standard switch variable case Type functionality.
Warning: T dummy = default won't work as default is usually Null, and we can't use Null in the switch statement. This is why Activator.CreateInstance() was used.
Discard (_) in the case statement is used to discourage use of the dummy variable. Presumably the case statement will have other logic for handling 'message'.
typeof(...)
. – Grazswitch
on a type almost certainly means that you should be refactoring the code so that isn't needed. – Kinglet