Home > Development > Generics and Reflection .NET with C#

Generics and Reflection .NET with C#

Generics in .NET work a little differently depending that normal reflection over types. The difference appears in whether the type is an open type, no type arguments supplied or a closed type all type arguments supplied.

static void Main()
            Type opentype = typeof (List<>);
            Console.WriteLine("Name: " + opentype.FullName);
            Console.WriteLine("Is Generic Type: " + opentype.IsGenericType);
            Console.WriteLine("Contains Generic Parameters: " + opentype.ContainsGenericParameters);


            Type closedtype = typeof(List<Person>);

            Console.WriteLine("Name: " + closedtype.FullName);
            Console.WriteLine("Is Generic Type: " + closedtype.IsGenericType);
            Console.WriteLine("Contains Generic Parameters: " + closedtype.ContainsGenericParameters);
            Console.WriteLine("Type Arguments are as follows...");
            Array.ForEach(closedtype.GetGenericArguments(), Console.WriteLine);


The output is as follows..
Name: System.Collections.Generic.List`1
Is Generic Type: True
Contains Generic Parameters: True
Name: System.Collections.Generic.List`1[[CSharpSamples.Person, CSharpSamples, Version=, Culture=neutral, PublicKeyToken=null]]
Is Generic Type: True
Contains Generic Parameters: False
Type Arguments are as follows…

The first line shows System.Collections.Generic.List`1, which means there is 1 type parameters. This is also an open type as Person has not been supplied as a type argument as opposed to System.Collections.Generic.List`1[[CSharpSamples.Person, CSharpSamples, Version=, Culture=neutral, PublicKeyToken=null]].

Also the type is generics as show by the second line and contain un supplied type arguments as shown on the third line.

The final line GetGenericArguments() allows you to get all supplied type arguments.

Hope this helps…


  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: