Matthew Scharley
Matthew Scharley

Reputation: 132254

Type parameters vs. generics

Is there ever a reason to use Type parameters over generics, ie:

// this...
void Foo(Type T);
// ...over this.
void Foo<T>();

It seems to me that generics are far more useful in that they provide generic constraints and with C# 4.0, contravarience and covarience, as well as probably some other features I don't know about. It would seem to me that the generic form has all the pluses, and no negatives that the first doesn't also share. So, are there any cases where you'd use the first instead?

Upvotes: 8

Views: 1966

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500065

Absolutely: when you don't know the type until execution time. For example:

foreach (Type t in someAssembly.GetTypes())
{
    Foo(t);
}

Doing that when Foo is generic is painful. It's doable but painful.

It also allows the parameter to be null, which can be helpful in some situations.

Upvotes: 10

LukeH
LukeH

Reputation: 269318

Foo(someVariable.GetType());      // allowed

Foo<someVariable.GetType()>();    // illegal

Upvotes: 2

Noon Silk
Noon Silk

Reputation: 55072

Well they really aren't the same at all.

With the second one, you've actually got a class of the compile-time type there (whatever has been passed in by whoever). So you can call specific functions on it (say if it's all of some given interface).

In your first example, you've got an object of class 'Type'. So you'll need to still determine what it is and do a cast to do anything useful with it.

Upvotes: 1

Related Questions