Tales from the Evil Empire

Bertrand Le Roy's blog

News


Bertrand Le Roy


Add to Technorati Favorites Tales from the Evil Empire - Blogged

Blogs I read

My other stuff

Archives

What's the difference between generic type parameters and parameters of type Type?

In other words, what's the difference between:

public T GetService<T>()

and:

public object GetService(Type service)

The generic type parameter enables strongly-typed scenarios that would otherwise be impossible. But don't forget that the generic type must be resolvable at compile-time (which is the whole point of generics). So you can't do this:

Type t = Type.GetType("SomeTypeName");
object serviceInstance = GetService<t>();

The type parameter is just that, a type parameter, it's not some parameter of type Type. So for these cases (those where the type you want to instantiate is defined in config, for example), you need the weakly-typed factory.

In this precise scenario of a factory, I prefer to keep both versions so that I can use the strongly-typed generic version wherever possible, and the other one otherwise.

Comments

Jerry Pisk said:

So in Whidbey one has to template the method signatures in addition to the type definition? instead of C++:

class <T> MyClass {
T GetService();
}

we have to do:

class <T> MyClass {
T GetService<T>();
}

isn't that a little too much?
# March 28, 2005 3:16 AM