#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

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

Leave a comment