I just started working on a project with an existing code base. While looking over the project, I found an odd lambda that I'm trying to understand.
Here's the code:
SomeFunction(x => () => new Y());
I don't understand...
why there are two => operators in the callback.
what is the purpose of the ().
For reference, here is the method signature of SomeFunction:
ISomeInterface<T> SomeFunction(Func<IXInterface, T> method);
The first lambda is returning a second lambda (a function) that returns a new object, in this case of type T. Recall that functions (i.e. delegates) are first-class objects in their own right.
In an ordinary lambda function, there is a lambda parameter that "encloses" the outer scope, as in this predicate:
x => x.SomeMember == true;
The () is simply a placeholder that says "I don't require a lambda parameter here, since I don't need to refer to the outer scope." (x) and (x, y) are also valid forms, so the () just means "no lambda parameters specified."
Related
I'm defining a lambda and calling it, by appending "()", immediately.
Try:
int i = (() => 0) ();
Error:
Error CS0119: Expression denotes a anonymous method', where amethod group' was expected
Why is that?
You're not "defining a lambda".. you're wrapping parenthesis around what you think is one.
The compiler doesn't infer this type of thing. It needs context. You give it context by assigning or casting the representation of the lambda to a delegate type:
Func<int> f = () => 0;
int i = f();
Thats clear context. If you want an unclear one.. this sort of thing also works:
int i = ((Func<int>)(() => 0))();
A lambda just does not support being executed. A delegate supports being executed. A lambda expression can be implicitly converted to a delegate type. In case no such conversion is requested there is no "default" delegate type. Since .NET 2 we normally use Action and Func for everything but we could use different delegate types.
First convert to a delegate, then execute:
((Func<int>)(() => 0))()
One could argue that C# should default to using Action and Func if nothing else was requested. The language does not do that as of C# 5.
This question already has answers here:
C# Lambda ( => ) [duplicate]
(4 answers)
Closed 9 years ago.
I have seen => used in sample code, but I don't know what this operand is called. Because the term is just symbols, Google search is not very helpful.
Here is an example of its use:
var rolesAllowed = rolePermission.Where(permission => permission.Permissions.Any(p => Demand.HasFlag(p.Type))).ToList();
This question is different from the ones so brazenly marked as "duplicate". I was looking for the name of the expression so I could research how to use it. The so-called duplicate item was for someone who already knew that => was called a lambda expression.
I want to thank the people who took the time to read and understand the question, and post a quality response.
It is called Lambda operator
To create a lambda expression, you specify input parameters (if any)
on the left side of the lambda operator =>, and you put the expression
or statement block on the other side. For example, the lambda
expression x => x * x specifies a parameter that’s named x and returns
the value of x squared.
Lambda expressions use special syntax. They allow functions to be used as data such as variables or fields. The lambda expression syntax uses the => operator. This separates the parameters and statement body of the anonymous function.
The => operator can be read as "goes to" and it is always used when declaring a lambda expression.
That is used to for lambda expressions. Essentially what that the Where function takes in is another function that iterates through the collection. The left side of the => defines the parameters and the right side is the actual function that gets run.
It is called lambda operator and it's the part of the lambda expression syntax.
Lambda expressions are very concise way to create anonymous methods.
Anonymous method example:
button1.Click += delegate(System.Object o, System.EventArgs e)
{ MessageBox.Show("Click!"); };
The same code, but this time using lambda expression:
button1.Click += (o,e) => MessageBox.Show("Click!");
As shown, this syntax is a
great shorthand notation for authoring anonymous methods, where a stack of arguments can be passed
into a group of statements for processing. Any method in the .NET platform that takes a delegate object
as an argument can be substituted with a related lambda expression, which will typically simplify your
code base quite a bit.
This is the lambda operator, it creates a lambda expression, which is like an anonymous method.
=> is a lambda operator, check the link to read more.
Also check this answer for more details.
This is an example out of a book using northwind database. What is the => mean ?
Northwind db = new Northwind(#"Data Source=.\SQLEXPRESS;InitialCatalog=Northwind");
var orders = db.Customers
.Where(c => c.Country == "USA" && c.Region == "WA")
.SelectMany(c => c.Orders);
Console.WriteLine(orders.GetType());
why don't they just write
Where(c.Country == "USA" && c.Regian == "WA")
The part inside the parentheses of the Where() needs to be a function that takes a Customer and returns a boolean value (that's Func<Customer, bool> in C#'s type system).
It's most common to write that function using C#'s Lambda Expressions.
The c => part means "take the Customer that's passed in to you and call it c. Then with that value of c, compute this conditional. Without the c on the left side of the =>, the compiler would have no way of knowing what c refers to.
If they wrote this:
Where(c.Country == "USA" && c.Regian == "WA")
Where would you define what the variable c referred to? What if somewhere earlier in my code I had written:
var c = "this is a string";
This notation defines a lambda construct, where c => is bound to the delegate input expected by the Where function - in this case, c is bound to each row, and the function you run with c needs to return a boolean.
Note that you could have written a function like this:
public bool OnlyWA(Row c)
{
return c.Country == "USA" && c.Regian == "WA";
}
And then used it like this:
var orders = db.Customers
.Where(OnlyWA)
.SelectMany(c => c.Orders);
Here you don't need the c any longer because you're using a named function not a lambda variable. The only parameter to the function acts in place of the c. This is usually overkill for small functions, and further makes it harder to read as the small predicate function is moved away from its usage (and therefore contextual) location.
It's a lambda expression. It describes a function; the variables to the left of the arrow are parameters to the function. In this case, the function has one parameter, so there is a single variable to the left of the arrow.
Consider the "why don't they..." example you gave. Where is c declared? How does the compiler know what it represents?
You may wonder how the compiler knows the type of the c parameter, which it obviously does, because it allows you to call the Country and Region properties. This is accomplished with type inference. The Where method requires a delegate argument with a parameter whose type depends on the type of the sequence (Customers, in this case).
Since Customers is an IEnumerable<Customer>, the compiler expects a delegate with a single Customer parameter, and it therefore treats the single parameter of the lambda expression as a Customer variable.
=> is the lambda operator
See here: msdn
It is used in lambda expressions to separate the input variables on the left side from the lambda body on the right side. Lambda expressions are inline expressions similar to anonymous methods but more flexible; they are used extensively in LINQ queries that are expressed in method syntax.
(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.
It's a lambda expression. That is, it's a way to create an anonymous function or delegate.
The general form is:
(input parameters) => expression
If you have
() => expression
then you have created a function that takes no arguments, and returns the result of the expression.
C# uses type inference to figure out what the types of the values are, and it captures local variables (like your "x" variable) by means of a lexical closure.
I assume x is declared in somewhere inside your method, if yes, you can compare this lambda expression with a delegate that has no paramaters and return the type of x.someproperty
delegate{
return x.someproperty;
}
that is the same as:
() => x.someproperty
the () mean that this method doesn't take any parameters.
for example, if you assign a normal event handler using a lambda expression, it would look like this:
someButton.Click += (s, e) => DoSomething();
See also the following two blog posts that discuss exactly your second question and provide alternative approaches:
How to Find Out Variable or Parameter Name in C#?
How to Get Parameter Name and Argument Value From C# Lambda via IL? (Or "How NOT to Use .NET Linq Expressions in Order to Get Parameter Name and Argument Value From C# Lambda?")
To get the name of the property you need SomeMethod to have an argument of the type of System.Linq.Expressions.Expression<System.Func<object>>. You can then go through the expression to determine the property name.
I am curious why C# allows me to ignore delegate parameters in some cases but not others.
For instance this is permitted:
Action<int> action = delegate { Console.WriteLine("delegate"); };
but this is not:
Action<int> action = () => Console.WriteLine("lambda");
Is there a way to initialize a delegate and ignore the parameters using a lambda? I know that I can add a single parameter to the lambda and fix the previous line but this is more of an academic question pertaining to the compiler and why or how this works.
I believe that your first sample actually creates an anonymous function that is able to take on many different signatures whose body is the single statement Console.WriteLine.... Because it can match different signatures, it does not cause a problem. In the second sample, the lambda syntax itself defines a function that takes no parameters with the same body. Obviously the latter is not consistent with the defined Action so you get the error.
C# Anonymous Method Reference
There is one case in which an
anonymous method provides
functionality not found in lambda
expressions. Anonymous methods enable
you to omit the parameter list, and
this means that an anonymous method
can be converted to delegates with a
variety of signatures. This is not
possible with lambda expressions.
To elaborate on tvanfosson's answer; this behavior is described in the C# 3.0 language specification (§7.14):
The behavior of lambda-expressions and
anonymous-method-expressions is the
same except for the following points:
• anonymous-method-expressions permit
the parameter list to be omitted
entirely, yielding convertibility to
delegate types of any list of value
parameters.
• lambda-expressions permit parameter
types to be omitted and inferred
whereas anonymous-method-expressions
require parameter types to be
explicitly stated.
• The body of a lambda-expression can
be an expression or a statement block
whereas the body of an
anonymous-method-expression must be a
statement block.
• Since only lambda-expressions can
have an expression body, no
anonymous-method-expression can be
successfully converted to an
expression tree type (§4.6).
I think:
Action<int> action = () => Console.WriteLine("lambda");
is the equivalent of:
Action<int> action = delegate() { Console.WriteLine("delegate"); };
which wouldn't compile either. As Daniel Plaisted says () is explicitly saying there aren't any parameters.
If there were an equivalent of delegate{} it might be:
Action<int> action = => Console.WriteLine("lambda")
Which isn't very pretty and I suspect it suspect isn't in the spirit of lambda expressions.
As others said, no, you can't skip declaring the parameters to a lambda. But, for cleanliness, I suggest giving them a name such as _. For example
foo.Click += (_,__) => { ... }
You aren't ignoring them per-se, but you're indicating you don't care what they are and will not use them.
The () => ... syntax explicitly specifies that the lambda takes no parameters. Perhaps the language could be modified so that () => really meant "Infer the parameters of this lambda for me" in the same way the delegate syntax does, but that would make the language more complicated. When designing new language features, you start at minus 100, and I don't think this one passes the test.
There may also be more technical reasons why this would be difficult to implement (which is probably more in line with what you were asking for, but I doubt the technical reasons drove this decision if it ever came up).
I'd say it's to have a forced use of the parameters of the lambda expression.
Take your first example, how would you interact with the passed in value, there's no local representation of it.
What about this?
Func<int> lamdapointer = () => TwoArgMethodThatReturnsInt(10,20); // the same method cannot be called with the delegate "NoArgmethodThatReturnsInt"
lamdapointer();
Delegate int NoArgmethodThatReturnsInt();
NoArgmethodThatReturnsInt del = NoArgmethodThatReturnsInt; // only this is possible with delegates
public int TwoArgMethodThatReturnsInt(int x,int y)
{
return x + y;
}
public int NoArgmethodThatReturnsInt()
{
return 20;
}
Actually, delegate {} does not specify any parameters and fits any delegate method signature - therefore it is permitted in your first construcion.
The Lambda expression () => ...; specifically states parameterless delegate, which contradicts the signature required by Action - a delegate with single parameter.
You may want to use one of the following options.
If you need the action to have a parameter, you can do it the next way ("_" is a legal character for identifier name).
Action<int> action = _ => Console.WriteLine("lambda");
Or you may want to use parameterless Action as follows:
Action action = () => Console.WriteLine("lambda");