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>()


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.

1 Comment

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

    class &lt;T&gt; MyClass {

    T GetService();


    we have to do:

    class &lt;T&gt; MyClass {

    T GetService&lt;T&gt;();


    isn't that a little too much?

Comments have been disabled for this content.