(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?
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With