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
...
}
}
Yes:
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:
That will behave differently to the first code block if
tis 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.