Home  |  Photos  |  Blog

 Tuesday, October 04, 2005

Today at work I came across some new APIs in Whidbey that I found to be quite useful when dealing with generic types.  System.Type.IsGenericType and System.Type.GetGenericTypeDefinition().  Have you ever wondered how to reflect if an object's type is a specific generic type definition (wait...is that any oxymoron :))?

Suppose we have some generic code:

class Foo {}

static void Main(string[] args) {
  System.Collections.Generic.List<Foo> fooList = new System.Collections.Generic.List<Foo>();
 
}

and now we want a method of determining at runtime if the object, fooList is a generic list:

static void Main(string[] args) {
  System.Collections.Generic.List<Foo> fooList = new System.Collections.Generic.List<Foo>();
  Console.WriteLine(IsObjectGenericList(fooList));
}

static bool IsObjectGenericList(object o) {
  Type t = o.GetType();
  return (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(System.Collections.Generic.List<>)));
}

I found these APIs useful when working with various generic types in my system.  For more information on this subject, look here.

10/4/2005 6:58 PM Eastern Standard Time  #    Disclaimer  |   |  Trackback