Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type parameters vs. generics

Tags:

c#

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?

like image 704
Matthew Scharley Avatar asked Aug 18 '09 23:08

Matthew Scharley


People also ask

What is type parameters in generics?

In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type.

Can generics take multiple type parameters?

A Generic class can have muliple type parameters.

Are generics type differ based on their type arguments?

In generics, it is possible to create a single class. A class interface or a method that operates on a parameterized type is called generic, like generic class or generic method, and generics only work with objects. And their type differs based on their type arguments.

How many type parameters can be used in a generic class?

Multiple parameters You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.


2 Answers

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.

like image 117
Jon Skeet Avatar answered Oct 21 '22 04:10

Jon Skeet


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.

like image 40
Noon Silk Avatar answered Oct 21 '22 04:10

Noon Silk