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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With