You're allowing the compiler to infer the type parameters. This works fine for case 1:
class SomeClass<T> where T : class {
void SomeMethod<TProperty>( Expression<Func<T,TProperty>> expression ){ ... }
}
because you first declare an instance:
var sc = new SomeClass<MyDateClass>();
which tells the compiler that T is MyDateClass
. Then, when you call the method:
sc.SomeMethod( dt => dt.Year );
the compiler knows that T is MyDateClass
, so T.Year
must be an int. That's enough info to resolve SomeMethod
as SomeMethod<MyDateClass, int>
.
Your second example, however, is explicitly stating the type parameter(s) - telling the compiler to not infer it:
sc.SomeMethod<MyDateClass>( dt => dt.Year );
Unfortunately, it is trying to call SomeMethod
with only a single type parameter (the <MyDateClass>
bit). Since that doesn't exist, it'll complain and say you need 2 type parameters.
If, instead, you were to call it like you did the first example:
sc.SomeMethod( dt => dt.Year );
The compiler will complain, telling you that it cannot infer the type parameters - there's simply not enough info to determine what dt
is. So, you could explicitly state both type parameters:
sc.SomeMethod<MyDateClass, int>( dt => dt.Year );
Or, tell the compiler what dt
is (which is what you did in the first example by newing SomeClass<MyDateClass>
):
sc.SomeMethod((MyDateClass dt) => dt.Year );
Edits and Updates:
So effectively the compiler is performing magic in the first example? Making an assumption that TProperty should be an int because .Year is an int? That would answer my question, can't say it's satisfying though.
Not really magic, but a series of small steps. To illustate:
sc
is of type SomeClass<MyDateClass>
, making T = MyDateClass
SomeMethod
is called with a parameter of dt => dt.Year
.
dt
must be a T (that's how SomeMethod
is defined), which must be a MyDateClass
for the instance sc
.
dt.Year
must be an int, as MyDateClass.Year
is declared an int.
- Since
dt => dt.Year
will always return an int, the return of expression
must be int. Therefore TProperty = int
.
- That makes the parameter
expression
to SomeMethod
, Expression<Func<MyDateClass,int>>
. Recall that T = MyDateClass
(step 1), and TProperty = int
(step 5).
- Now we've figured out all of the type parameters, making
SomeMethod<T, TProperty>
= SomeMethod<MyDateClass, int>
.
[B]ut what's the difference between specifying T at the class level and specifying at the method level? SomeClass<SomeType>
vs. SomeMethod<SomeType>
... in both cases T is known is it not?
Yes, T
is known in both cases. The problem is that SomeMethod<SomeType>
calls a method with only a single type parameter. In example 2, there are 2 type parameters. You can either have the compiler infer all type parameters for the method, or none of them. You can't just pass 1 and have it infer the other (TProperty
). So, if you're going to explicitly state T
, then you must also explicitly state TProperty
.