Nice use of generics

posted @ Saturday, September 25, 2004 5:43 PM


Eric Gunnerson recently talked about a nice use of generics that I thought I would share. To create a COM object in .NET you can do the following:

Type t = Type.GetTypeFromCLSID(guid);
IGraphBuilder graphBuilder = (IGraphBuilder) Activator.CreateInstance(t);

so a nice helper function using generics looks like this:

private T CreateComObject(Guid guid) where T: class|
Type comType = Type.GetTypeFromCLSID(guid);
object o = Activator.CreateInstance(comType);
if(o == null)
return null;
return (T) o;

and now you can do something like this:

IGraphBuilder graphBuilder = CreateComObject<IGraphBuilder>(CLSID_FilterGraph);

Just wanted to document this for future use.