Is it possible to do something like this in C#:
public void DoSomething<T>(T t) { if (T is MyClass) { MyClass mc = (MyClass)t ... } else if (T is List<MyClass>) { List<MyClass> lmc = (List<MyClass>)t ... } }
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.
A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
Yes:
if (typeof(T) == typeof(MyClass)) { MyClass mc = (MyClass)(object) t; } else if (typeof(T) == typeof(List<MyClass>)) { List<MyClass> lmc = (List<MyClass>)(object) t; }
It's slightly odd that you need to go via a cast to object, but that's just the way that generics work - there aren't as many conversions from a generic type as you might expect.
Of course another alternative is to use the normal execution time check:
MyClass mc = t as MyClass; if (mc != null) { // ... } else { List<MyClass> lmc = t as List<MyClass>; if (lmc != null) { // ... } }
That will behave differently to the first code block if t
is null, of course.
I would try to avoid this kind of code where possible, however - it can be necessary sometimes, but the idea of generic methods is to be able to write generic code which works the same way for any type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With