Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeof(T) vs <T>

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

Such as:

var list = new List<MyClass>();

The other way is to explicity use the typeof operator such as:

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

My question is regarding the discrepancy in a uniform interface to methods that require a type parameter. Why can't the above statement be done as follows?:

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

Is it because there are two semantic differences required in how the compiler behaves? When a generic parameter is processed by the compiler does it simply perform substitution ala lambda calculus? Whereas the typeof style methods require an actual instance of the Type class to infer attributes and properties from?

Thank you.

like image 780
Nicholas Mancuso Avatar asked Apr 01 '11 17:04

Nicholas Mancuso


Video Answer


2 Answers

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

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

Personally I wouldn't mind seeing an overload which would definitely make code with a type defined at compile time much cleaner.

like image 175
ChaosPandion Avatar answered Sep 21 '22 11:09

ChaosPandion


Consider this method signature.

public object MyGetInstanceOfType(Type theType)

While an instance of the appropriate type might be returned, the compiler has no way to verify it... theType isn't known until runtime (well after the compiler is involved).

Contrast with this:

public T MyGetInstanceOfType<T>()

Here the compiler knows the type every time a caller uses this method. It can guarantee the method's return, because it knows the type on all of the calls.

like image 33
Amy B Avatar answered Sep 18 '22 11:09

Amy B