Newer versions of C# haven't added any features specifically around switching on Type values. If you're truly attempting to switch based on a generic type, you'll probably want to follow the patterns recommended in those other SO posts.
However, there may be better approaches than using generic types. The fact that you're trying to switch on that type implies that there are limited types you'd expect code to use when calling your method. In that case, you may be better off explicitly using different methods for each of those types.
Instead of:
var axis = GetAxis<Axis>(axisObject); var somethingElse = GetAxis<SomethingElse>(axisObject);
Use:
var axis = GetAxis(axisObject); var somethingElse = GetSomethingElse(axisObject);
Your example doesn't appear to be doing this, but if what you're really trying to switch off of is the type of the passed-in object, then newer versions of C# do provide some better options through pattern matching. For example:
public T GetAxis<T>(object axisObject) { switch (axisObject) { case Axis axis: //...do something with `axis` break; case SomethingElse somethingElse: //...do something with `somethingElse` break; } return default; }
In this last case, it's unclear to me what value the T generic type has: you may be able to replace that with a non-generic return type.
if (typeof(T) == typeof(Axis)) {...}maybe? Or create a dictionary that mapsTypeto some enum of the expected types, and switch on that?T, or are you trying to switch on the type ofaxisObject?do somethingshould be defined by that type, so you can just constrainTto implement a methodvoid DoSomething()