I have a method that takes a generic parameter T. Internally, to decide what other methods to call, I need to know (without constraining it) if that parameter is a List or just something.
How do I do that?
I’ve been using
var isList = typeof(T).Name.ToLower().Contains("list`1");
but that feels like a dirty approach. What’s cleaner?
If you don’t need an exact match for List, you might also just check if
typeof(IList).IsAssignableFrom(typeof(T)), which many list-like collections implement.If you want to support T being equal to
IList<T2>directly (so the type parameter T is an interface), then you need to check for that separately (GetGenericTypeDefinition()could also returntypeof(IList<>)).If you want to support any type T that inherits from any
IList<>, then you have to get a bit more creative. You have to enumerate all interfaces, check if they are generic (as above) and then check if the generic type of the interface isIList<>. Also, because the GetInterfaces() call on Type only returns the top-level interfaces, you need to navigate through all of the interfaces implemented by each interface (recursively), to check those as well. Ugly, I know.