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.
Remember Me
Powered by: newtelligence dasBlog 1.7.5016.2
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2009, John Ritsema
E-mail