#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

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,145 – Using Reflection on Generic Type Parameters

  1. Pingback: Dew Drop – July 24, 2014 (#1821) | 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: