Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does SomeMethod(() => x.Something) mean in C#

Tags:

c#

lambda

(Note the code is an example)

I have the following syntax:

SomeMethod(() => x.Something) 

What do the first brackets mean in the expression?

I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?

like image 333
Arec Barrwin Avatar asked Sep 02 '09 21:09

Arec Barrwin


2 Answers

What do the first brackets mean in the expression?

It's the lambda syntax for a method that takes no parameters. If it took 1 parameter, it'd be:

SomeMethod(x => x.Something);

If it took n + 1 arguments, then it'd be:

SomeMethod((x, y, ...) => x.Something);

I'm also curious how you can get the property name from argument that is being passed in. Is this possible?

If your SomeMethod takes an Expression<Func<T>>, then yes:

void SomeMethod<T>(Expression<Func<T>> e) {
    MemberExpression op = (MemberExpression)e.Body;
    Console.WriteLine(op.Member.Name);
}
like image 151
Mark Brackett Avatar answered Nov 18 '22 22:11

Mark Brackett


The () is an empty argument list. You're defining an anonymous function that takes no arguments and returns x.Something.

Edit: It differs from x => x.Something in that the latter requires an argument and Something is called on that argument. With the former version x has to exist somewhere outside the function and Something is called on that outside x. With the latter version there does not have to be an outside x and even if there is, Something is still called on the argument to the function and nothing else.

like image 8
sepp2k Avatar answered Nov 18 '22 21:11

sepp2k