Typeof (T) vs <T>

In .NET, there are two ways to pass a type to a method or class. The first is through generics, in which we pass the type as a special parameter.

For instance:

var list = new List<MyClass>(); 

Another way is to explicate with the typeof operator, for example:

 var pe = Expression.ParameterExpression(typeof(MyClass), "myinstance"); 

My question is about mismatch in a single interface to methods that require a type parameter. Why can't this be done as follows ?:

 var pe = Expression.ParameterExpression<MyClass>("myinstance"); 

Is it because there are two semantic differences in the way the compiler works? When the general parameter is processed by the compiler, does it just do the substitution ala lambda calculus? While typeof style methods require an actual instance of the Type class to output attributes and properties from?

Thanks.

+6
generics typeof
source share
4 answers

The first method allows you to calculate the required type at runtime.

 Expression.ParameterExpression(CalculateType(), "myinstance"); 

Personally, I would not mind seeing an overload that will certainly make code with a type defined at compile time much cleaner.

+6
source share

Consider this method signature.

 public object MyGetInstanceOfType(Type theType) 

While an instance of the appropriate type can be returned, the compiler is not able to check it ... theType is unknown until runtime (well, as soon as the compiler is involved).

Contrast with this:

 public T MyGetInstanceOfType<T>() 

Here, the compiler knows the type every time the caller uses this method. It can guarantee the return of the method, since it knows the type in all calls.

+3
source share

With var list = new List<MyClass>(); The List class is informed at compile time that it is bound to a specific type. The compiler can then perform type checking so that only MyClass elements are added to the list.

With var pe = Expression.ParameterExpression(typeof(MyClass), "myinstance"); an expression at run time indicates what type of parameter it is working with. This approach cannot perform strong type checking. This is best for dynamic code, where things cannot be determined at compile time, but these cases are rare (although expression trees are one of them).

+2
source share

Technically, a generic version can be easily created, as it can cause an overload that takes a type of type:

 public static ParameterExpression Parameter<T>(string name) { return Parameter(typeof(T), name); } 

In this case, however, using generic does not buy you much. If one of the parameters is of type T or the return value is of type T, then you will get strong typing based on the specified type parameter.

Adding a generic version of the Parameter method does not make it more or less strongly typed.

0
source share

All Articles