Tales from the Evil Empire

Bertrand Le Roy's blog

News

Ads Via DevMavens

ASP.NET AJAX UpdatePanel Control: Add Ajax interactivity to your ASP.NET 2.0 web pages

Add to Technorati Favorites

Blogs I read

My other stuff

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

Bertrand Le Roy said:

No Jerry, you never write that second thing, which would probably not compile because that would create a conflict between the class type parameter and the method type parameter. You write something close to the first one:

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

I should maybe have written the code for the entire class. What you have in my example is a generic method in a non-generic class:

class MyClass {
T GetService<T>();
}
# March 28, 2005 2:02 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)