Type Parameters against generics

Is there a reason to use Type parameters for generics, i.e.

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

It seems to me that generics are much more useful in that they provide common limitations and C # 4.0, contrast and coincidence, and also, perhaps, some other functions that I do not know about. It seems to me that the general form has all the pluses and no negatives that the first does not share. So, are there any cases where you would use the first instead?

+6
generics c #
source share
3 answers

Absolutely: when you don't know the type before runtime. For example:

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

Doing this when Foo is common is a pain in the butt. It is doable, but painful.

It also allows the parameter to be null , which may be useful in some situations.

+8
source share
 Foo(someVariable.GetType()); // allowed Foo<someVariable.GetType()>(); // illegal 
+1
source share

Well, they are not at all the same.

In the second case, you really have a class such as compilation time (regardless of who was passed by anyone). Thus, you can call certain functions on it (say, if it's all some kind of specific interface).

In the first example, you have an object of class Type. Therefore, you will still need to determine what it is and make an acting cast to do something useful with it.

0
source share

All Articles