#1,145 – Using Reflection on Generic Type Parameters

You can use the typeof operator to get information about one or more type parameters within a generic type.  In the example below, we get information about the type argument used when the generic type is constructed.

    public class Pile<T>
        List<T> pile = new List<T>();

        public Pile()
            Type t = typeof(T);
            Console.WriteLine("Constructing Pile<T> type, with T as [{0}]", t.Name);

        public void Add(T item)
            if (!pile.Contains(item))

Here’s the output when we construct Pile<Dog> and Pile<int>:

            Pile<Dog> pack = new Pile<Dog>();
            Pile<int> justNumbers = new Pile<int>();