Nicholas Hill
Nicholas Hill

Reputation: 316

How can I determine the parameterless-type of a C# generic type for checking purposes?

Is it possible to check the type of a generic type, without using any generic parameters?

For example, I would like to be able to do something similar to the following (actual types' names have been changed to protect the innocent):

var list = new List<SomeType>();

...

if (list is List)
    {
    Console.WriteLine("That is a generic list!");
    }

The above code currently generates the following error:

Using the generic type 'System.Collections.Generic.List<T>' requires 1 type arguments

Is there a way around this? Preferably, something concise and something that will work with types that DON'T have generic parameters (ie: "if myString is List").

Upvotes: 5

Views: 117

Answers (1)

Eren Ers&#246;nmez
Eren Ers&#246;nmez

Reputation: 39085

You can check like this:

var type = list.GetType();
if(type.IsGenericType && 
   type.GetGenericTypeDefinition().Equals(typeof(List<>)))
{
    // do work
}

Upvotes: 9

Related Questions