#1,144 – Getting Type Information about a Generic Type

You can use the typeof operator to get information about a particular type.  The operator returns an instance of the Type class, which you can then query to get info about the type.

You can get type information about generic types in two different ways.  You can use the name of the type with empty angle brackets to get information about the generic type.  Or you can supply type arguments to get information about a particular constructed type.

        private static void DumpInfoForType(Type t)
        {
            Console.WriteLine("Type {0}:", t.Name);
            Console.WriteLine("  IsGenericType: {0}", t.IsGenericType);
            Console.WriteLine("  IsGenericTypeDefinition: {0}", t.IsGenericTypeDefinition);
            Console.WriteLine("  IsConstructedGenericType: {0}", t.IsConstructedGenericType);
            Console.WriteLine("  ContainsGenericParameters: {0}", t.ContainsGenericParameters);

            if (t.IsConstructedGenericType)
            {
                foreach (Type targ in t.GenericTypeArguments)
                    Console.WriteLine("Arg: {0}", targ.Name);
            }
        }

        static void Main(string[] args)
        {
            DumpInfoForType(typeof(Pile<>));
            DumpInfoForType(typeof(Pile<Dog>));
        }

The first type is a generic type definition with generic parameters. The second is a constructed generic type with a Dog argument.

1144-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #1,144 – Getting Type Information about a Generic Type

  1. Pingback: Dew Drop – July 23, 2014 (#1820) | Morning Dew

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: