Urban Potato

Fun with Generics

Generics are a new feature in the .NET Framework that are at first glance similar to C++ templates. But, they run much deeper.


Generics are a new feature in the .NET Framework that are at first glance similar to C++ templates. But, they run much deeper.

Generics are a new feature in the .NET Framework that are at first glance similar to C++ templates. But, they run much deeper. Anyone who has been toying with the upcoming release of the .NET Framework may have seen generics in action in the new generic collection namespace:

List<int> intList = new List<int>();
list.Add(1);
list.Add(1);
int result = list[0] + list[1];

This creates a list of integers. Unlike a normal ArrayList, integers added to the list do not get boxed into objects. This can be done with C++ templating easily.

Here's a little deeper use of Generics that C++ can't touch. There is an interface called IServiceProvider that is essentially a hashtable of type->instance. We abuse this interface all over the place inside the Windows Forms designer, and typical usage looks something like this:

IServiceProvider provider = // get this from somewhere
IDesignerHost host; // interface you want an instance of
host = provider.GetService(typeof(IDesignerHost)) as IDesignerHost;

When you're through, you've got an instance to an object that implements IDesignerHost. Simple, right? True, but that last line is anything but pretty. There is a typeof and essentially a cast. I prefer the "as" syntax because it looks a little cleaner, but it is still a cast. This looks even worse in Visual Basic:

host = CType(provider.GetService(GetType(IDesignerHost)), IDesignerHost)

Yuck!

But Generics can make this better. In fact, almost Smoov. Here's a little generic method that wraps a member variable called _provider:

private T GetService<T>() {
    return (T)_provider.GetService(typeof(T));
}

Simple enough. Here's how you would use this:

host = GetService<IDesignerHost>();

It's a little ugly because I still need the open/close parens, but all of the typeof and casting junk is gone. Cool!

Brian • 11/20/2003 9:35:34 AM