3

I saw code like below. My questions are:

1> ()=>Name what does this mean?

2> Is Expression<Func<>> the same as Expression<TDelegate>? How is ()=>Name cast to Expression<Func<>> and which constructor is used? Most Expression classes don't have public constructors. How does C# compiler convert from Lambda to Expression?

3> What is the performance cost of the Parse function?

public class Test
{
    public string Name {get;set;}

    public void Start()
    {
        Parse(()=>Name);
    }

    public string Parse<T>(Expression<Func<T>> exp)
    {
        var mexp = (System.Linq.Expressions.MemberExpression)expression.Body;
        return mexp == null ? "" : mexp.Member.Name;
    }
}
1
  • 1
    you should measure to answer #3. Commented Jul 3, 2015 at 22:47

2 Answers 2

5
  1. That is a lambda that takes no arguments, but results in a String.
  2. No. TDelegate is a template argument. Func<T> is a concrete type that satisfies the TDelegate's constraints. The C# compiler will convert the lambda into the appropriate type at compile time.
  3. You should measure in order to answer this question.
Sign up to request clarification or add additional context in comments.

3 Comments

Why it recognize Name property in my class? And in this case, what type the C# complier converts this Lambda to?
@Helic that's because it is closed upon.
so does it mean I can use Parse(()=>{return name;}), but it gives me another exception "A lambda expression with a statement body cannot be converted to an expression tree". Also, please see my edit to the original question. Thanks.
3

So ()=>Name is a lambda function. It is basically a function that returns the Name property. In your case this thing is a Func<string> by type.

All that changes a little because you hand it over to a field that is defined as Expression<Func<T>>. In your case you give a Expression<Func<string>>. Basically that makes the lambda function to a expression of a lambda function that gives you not the result of the function but the structure.

Usually a structure like this is used to get the name of a property in a safe way. For example to prevent a obfuscator or a accidental renaming to mess with your code.

2 Comments

" hand it over " do you mean cast?
I have no idea what the C# compiler does at this point. ()=>Name is a Func<string> and it turns to a Expression<Func<string>>. Sadly I can only tell you that it works. I can't tell you why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.