views:

373

answers:

4

Can someone explain why the first of the two following examples is valid and the other is not? More specifically, how is a relationship created between T and TProperty in the first example?

//Example 1  
class SomeClass<T> where T : class
{
    void SomeMethod<TProperty>( Expression<Func<T,TProperty>> expression ){ ... }
}

//Example 2  
class SomeClass
{
    void SomeMethod<T,TProperty>( Expression<Func<T,TProperty>> expression ) 
         where T : class{ ... }
}

Given the two examples I would expect that the following implementations would work, but the second one does not.

//Implementation w/ Example 1  
var sc = new SomeClass<MyDateClass>();
sc.SomeMethod( dt => dt.Year );

//Implementation w/ Example 2
var sc = new SomeClass();
sc.SomeMethod<MyDateClass>( dt => dt.Year );

What I'm having difficulty wrapping my mind around is how the first example/implementation can ignore the TProperty generic type when executing SomeMethod, yet the second example/implementation can't and how an implicit relationship seems to be established between T and TProperty in example/implementation 1.

Solution Change signature of method in example 2 as follows:

void SomeMethod<T>( Expression<Func<T,Object>> expression ){ ... }

While this will allow arbitrary objects to be used in the expression as a result it does allow for property articulation as described in implementation 2.

A: 

The problem, as far as I can see, is simply that DateTime isn't a class... you're passing in T as DateTime (whether it is implicit or explicit).

It is probably also slightly confusing that in the first example you have two type parameters called T - one on the type, and one on the method. They are actually completely separate... to be the same, rewrite the first example as:

//Example 1  
class SomeClass<T> where T : class
{
    void SomeMethod<TProperty>( Expression<Func<T,TProperty>> expression ){ ... }
}

This is now the same T : class

Marc Gravell
Sorry bad example... obviously DateTime is a struct. Made edits to my example to hopefully more clearly articulate the problem. Assuming the object is actually a class with properties and not a struct.
Ikarii Warrior
While this is true, and it can certainly be written this way - I am interested in where the connection is made that TProperty is actually related to T, thus allowing p => p.Property in the expression without ever defining the generic type of TProperty. More importantly how I accomplish the same thing with a method that is not in a generic class. Am I making sense? :)
Ikarii Warrior
+1  A: 

First of all, your first example is incorrect, and won't compile as given. Aside from the missing public on the method, you define T twice - once on class, and once on method. This isn't an error in and of itself (though you'll get a warning), but when compiling the method call, you'll get the same error as you describe getting for example #2. So, I assume the actual code is like this:

//Example 1  
class SomeClass<T> where T : class
{
  public void SomeMethod<TProperty>(Expression<Func<T,TProperty>> expression) {}
}

Furthermore, both your examples "ignore" (that is, infer) the actual type of TProperty in your call to SomeMethod. Your second example explicitly specifies the type of T, yes, but not TProperty.

There's no implicit relationship established in the first example, either. When you instantiate SomeClass<> with T=MyDateClass, the signature of SomeMethod for that instantiation effectively becomes:

void SomeMethod<TProperty>(Expression<Func<MyDateClass, TProperty>> expression)

So the argument type of the lambda is known at this point, so you don't have to specify it. The return type of expression lambda is inferred as the type of expression on the right of =>, and that will be the inferred type of TProperty.

In the second example, since T was not explicitly specified when instantiating the class, and since there's no way to infer it from method arguments, it has to be specified explicitly. Once you specify it, TProperty is inferred in exact same way as for example #1.

Pavel Minaev
I don't understand what you are implying with your infer comment. Are you saying that neither example shouldn't work because the type of TProperty is unknown in the examples? Regarding the syntax errors, yes, guilty as charged - I did not attempt to compile these examples before posting.
Ikarii Warrior
"Infer" means "automatically figure out the type". In this case it goes like this: type of `T` is known -> `T1` in `Func<T1,TResult>` is known -> type of `dt` is known -> return type of lambda is inferred as type of expression `dt.Year` (once we know the type of `dt`, we obviously know the type of `dt.Year` -> `TResult` in `Func<T1,TResult>` is known -> `TProperty` is known.
Pavel Minaev
The confusion is not with an understanding of what infer means, but how defining MyDateClass at the class level vs. at the method level makes a difference. ie; SomeClass<MyDateClass>, SomeMethod<MyDateClass>... in both these cases T1 is known so why is the type of TProperty inferred int he first example but not the second?
Ikarii Warrior
Oh, I see now. If your example #2 is taken exactly as given, the compiler error there is simply because you do not specify `TProperty`. This isn't because it cannot be inferred, but because, unlike C++, C# doesn't let you explicitly specify some type parameters in a method call, but omit others. You either omit all of them (and let them be inferred), or you specify all.
Pavel Minaev
Exactly. :) Sorry if I wasn't clear. I tried to dumb down the example but I may have obfuscated the problem by adding compiler errors with adhoc code. Apologies.
Ikarii Warrior
+1  A: 

Rather than typing out the specifics, please take a look at this post by Eric Lippert. I think it will answer what you're attempting to ask.

I realize it's long and contrived, but I think it's the best bang for the buck for answering you.

Marc
+6  A: 

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:

  1. sc is of type SomeClass<MyDateClass>, making T = MyDateClass
  2. SomeMethod is called with a parameter of dt => dt.Year.
  3. dt must be a T (that's how SomeMethod is defined), which must be a MyDateClass for the instance sc.
  4. dt.Year must be an int, as MyDateClass.Year is declared an int.
  5. Since dt => dt.Year will always return an int, the return of expression must be int. Therefore TProperty = int.
  6. That makes the parameter expression to SomeMethod, Expression<Func<MyDateClass,int>>. Recall that T = MyDateClass (step 1), and TProperty = int (step 5).
  7. 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.

Mark Brackett
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. :)
Ikarii Warrior
... I think the light just went off. The diff between class<T> and method<T> is that class<T> implies that an instance of T exists in context while method<T> does not? Hence the assumptions by the compiler?
Ikarii Warrior
Not sure why you aren't satisfied, but static type inferencing is no magic, and has explicit rules and is a new feature in C#.
Charles Prakash Dasari
@Ikarii - I'm not sure what you're implying. It isn't context, T is known in the first example because you had to specify it at class creation. You're expecting it to be inferred in the second.
Marc
Right... but 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?
Ikarii Warrior
Thanks Mark, I think you understood the problem exactly and were able to articulate an answer to bring my brain out of a tailspin! :)
Ikarii Warrior