Nick Parker
My ramblings on .NET...

Nice use of generics

Saturday, 25 September 2004 17:43 by nickp

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;
else
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.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   .NET
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

August 20. 2008 03:17