#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))
                pile.Add(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>();

1145-001

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

One Response to #1,145 – Using Reflection on Generic Type Parameters

  1. Pingback: Dew Drop – July 24, 2014 (#1821) | Morning Dew

Leave a comment