tags:

views:

1232

answers:

3

Ok, I'm lost. Why is the 1st function WRONG (squiglies in the lamda expression), but the 2nd one is RIGHT (meaning it compiles)?

    public static Expression<Func<IProduct, string, bool>> IsValidExpression(string val)
    {
        return (h => h.product_name == val);

    }

    public static Expression<Func<IProduct, bool>> IsValidExpression2()
    {
        return (m => m.product_name == "ACE");

    }
+2  A: 

What is the middle string intended to do? You can make it compile by:

public static Expression<Func<IProduct, string, bool>> IsValidExpression(string val)
{
    return (h,something) => h.product_name == val;
}

Or maybe you mean:

public static Expression<Func<IProduct, string, bool>> IsValidExpression()
{
    return (h,val) => h.product_name == val;
}

?

Marc Gravell
My guess is that OP is unaware that val is hoisted and hence not part of the signature for the resulting method of the lambda expression
Rune FS
+1  A: 

Your first function is going to need two arguments. Func<x,y,z> defines two parameters and the return value. Since you have both an IProduct and a string as parameters, you'll need two arguments in your lambda.

  public static Expression<Func<IProduct, string, bool>> IsValidExpression(string val)
  {
        return ((h, i) => h.product_name == val);
  }

Your second function is only Func<x,y>, so that means that the function signature has but one parameter, and thus your lambda statement compiles.

womp
Well the function is not using the second argument so I'd say it's not _needed_ but that the signature for the method is wrong
Rune FS
Agreed. A succinct way of stating it.
womp
This won't compile, btw... needs `(h,i) =>`
Marc Gravell
gah. thanks Marc :)
womp
A: 

Func<IProduct, string, bool> is a delegate to a method with the following signature:

bool methodName(IProduct product, string arg2)
{
  //method body
  return true || false;
}

so

public static Expression<Func<IProduct, string, bool>> IsValidExpression(string val)
{
    return (h => h.product_name == val);
}

has a differance between the return type and the returned value. you are trying to return an object of the type Expression<Func<IProduct, bool>>.

the val argument is not an argument to the method you're delegating to but will be hoisted (made part of a class implementing the resulting function) and since it's not an argument to the resulting method it should not be part of the Func type delclaration

Rune FS
Since this is an `Expression` (not a delegate) it isn't quite as you describe - there **is** no "resulting function"; it is an expression tree...
Marc Gravell
@marc You're right on the Expression<> being an Expression tree and not a method I strungled for a term for "The method that the Expression tree can be compiled into" which I tryed to formulate as "resulting function" however the statment that well Func<> is a delegate type is correct :)
Rune FS