How to find if a generic type is List<>

I have a generic method define as below

public T MyMethod<T>(extra params)

My method can receive and return either single entity type but also List. How can I find if T passed is a single entity type or a List and in this case how can I get the type of inner type T1?

Thanks

Answers


You can do this using methods of the Type class:

var type = typeof(T);
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) {
    var innerType = type.GetGenericArguments()[0];
}

Need Your Help

When the bots attack!

security captcha spam-prevention bots

What are some popular spam prevention methods besides CAPTCHA?

NHibernate ignores length attribute

nhibernate nhibernate-mapping

After running SQL Profiler, I realized that NHibernate was mapping strings to nvarchar(4000). I fixed it by specifying type=AnsiString and length=... in the hbm file. It is now generating varchar(8...