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.
Related
This question already has answers here:
C# method group strangeness
(2 answers)
Closed 9 years ago.
I just saw the following answer: Is there a better way to create acronym from upper letters in C#? and it has the following code:
string.Join("", s.Where(char.IsUpper));
How does the char.IsUpper work here? (Instead of x => char.IsUpper(x))
char.IsUpper is a method group, which itself takes a char and returns a bool, so it's a valid predicate for use with Where().
The code is referencing the method by name in much the same way as you would with any other method when specifying a delegate, instead of directly invoking it, so the parentheses aren't necessary.
The parentheses are necessary if you're wrapping it in a lambda expression x => char.IsUpper(x), because you're calling the method and returning the result, within the expression.
char.IsUpper refers to a method group which is passed to the Where function as a typed delegate via an implicit conversion which you can read in the Covariance and Contravariance in C#, Part Three: Method Group Conversion Variance article by Eric Lippert.
I believe char.IsUpper (without parentheses) evaluates to a reference to the method, that can be passed as a predicate. If you added parentheses, that would just immediately invoke the method and attempt to pass the result instead of passing the method itself.
Where<char> takes a Func<char, bool> as a parameter. By using x => char.isUpper(x), you are creating a new Func to be used by Where. However, the toUpper method, takes a char, and returns a bool. Therefore, it can be used directly as the parameter for Where.
What is the difference between Expression and Func? The same task can be attained by both. So what is the difference?
Expression trees are data representations of logic - which means they can be examined at execution time by things like LINQ providers. They can work out what the code means, and possibly convert it into another form, such as SQL.
The Func family of types, however, are just delegates. They end up as normal IL, which can be executed directly, but not (easily) examined. Note that you can compile expression trees (well, Expression<T> and LambdaExpression) into delegates and execute those within managed code as well, if you need to.
You can build up expression trees manually using the factory methods in the Expression class, but usually you just use the fact that C# can convert lambda expressions into both expression trees and normal delegates:
Expression<Func<int, int>> square = x => x * x;
Func<int, int> square = x => x * x;
Note that there are limitations on which lambda expressions can be converted into expression trees. Most importantly, only lambdas consisting of a single expression (rather than a statement body) can be converted:
// Compile-time error
Expression<Func<int, int>> square = x => { return x * x; };
// Works fine
Func<int, int> square = x => { return x * x; };
It is not true that "they do the same thing". Expression describes your intent in a way that can be interpreted at runtime - it is, if you like, the recipe. A function is an opaque delegate, that can't be inspected - it can be used as a black box. Compared to a recipe, it is some kind of auto-chef that doesn't let you see what it does: give it some bread and some chicken, close your eyes and it gives you a sandwich, but you never get to know how.
I discuss this more here: Explaining Expression, but having the recipe is key for LINQ, RPC, etc. And of course, if you have the recipe you can make your own chef, via Expression.Compile().
Expression can be built at runtime, function not (unless you use reflection emit). Once you build the expression tree you can compile it and turn it into a function pointer which can be invoked. Func is a pointer to some already existing function which can no longer be modified while Expression represents the code of some function that doesn't exist until you compile it.
You usually use expressions when you want to preserve the semantics of the code so that you can translate it. That is, expressions allow you to treat the code as data. If the code does not need to be treated as data (i.e. you're not planning on storing it or translating it) then using a Func is appropriate.
This question already has answers here:
What does the '=>' syntax in C# mean?
(7 answers)
Closed 8 years ago.
I was watching a Silverlight tutorial video, and I came across an unfamiliar expression
in the example code.
what is => ?
what is its name? could you please provide me a link?
I couldn't search for it because they are special characters.
code:
var ctx = new EventManagerDomainContext();
ctx.Events.Add(newEvent);
ctx.SubmitChanges((op) =>
{
if (!op.HasError)
{
NavigateToEditEvent(newEvent.EventID);
}
}, null);
It's a lambda expression.
If you're familiar with anonymous methods from C# 2, lambda expressions are mostly similar but more concise. So the code you've got could be written like this with an anonymous method:
var ctx = new EventManagerDomainContext();
ctx.Events.Add(newEvent);
ctx.SubmitChanges(delegate(Operation op)
{
if (!op.HasError)
{
NavigateToEditEvent(newEvent.EventID);
}
}, null);
Aspects of anonymous methods such as the behaviour of captured variables work the same way for lambda expressions. Lambda expressions and anonymous methods are collectively called anonymous functions.
There are a few differences, however:
Lambda expressions can be converted into expression trees as well as delegates.
Lambda expressions have a number of shortcuts to make them more concise:
If the compiler can infer the parameter types, you don't need to specify them
If the body is a single statement, you don't need to put it in braces and you can omit the "return" part of a return statement
If you have a single parameter with an inferred type, you can miss out the brackets
Putting these together, you get things like:
IEnumerable<string> names = people.Select(person => person.Name);
Lambda expressions don't support the "I don't care how many parameters there are" form of anonymous methods, e.g.
EventHandler x = delegate { Console.WriteLine("I was called"); };
Lambda operator:
A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls...
Huzzah!
I couldn't search for it because they are special characters.
Sometimes the old-fashioned ways are the best. This worked for me:
Start Visual Studio 2008 or later
Hit F1
Once the Help Document Explorer has come up, ensure the Index tab is selected in the left hand pane
Enter => in the Look for field
The first item in the list is now the help article you need.
Based on my understanding , i interpret the meaning of Func delegate as follows.Please correct them as and when it is needed.
Declaration : Func<int> dg ;
1. Could i interpret it as "a Delegate
pointing to a method that returns an
integer?".
Declaration : Func<int,int> delg1=r=>2*r;
*2. Could i interpret it as " 'r' is a lambda expression that itself is a parameter of
an integer type being evaluated as '2 * r' and returns an int?
.*
Comparison : Delegate and lambda expression
3. if both Delegates and lambdas are working as function poiinters ,Where do there differ?.
Comparison : Are the following two declarations equal?
decl 1 : Func<int,int> fn=(r)=>45*r;
decl 2 : Expression<Func<int,int>> ex = (r) => r * 10;
4. if both of the above mentioned constructs are serving for the same purpose ,Where do there differ?.
1) Yes, but it would be more precise and accurate to say "a delegate referring to a method that takes no arguments and returns an integer".
2) No. "r" is not a lambda expression. "r" is used twice, first to declare a formal parameter of a lambda expression, and second as part of the body of that lambda expression. But "r" is not the lambda expression. The lambda expression is "r=>2*r"
3) Lambdas and delegates are different things. A lambda is the abstract notion of "a function that does some thing". A delegate type is the abstract notion of the type of things which are methods that take and return certain types. A particular delegate is a reference to such a method. A lambda is convertible to a compatible delegate type, and if you do so, at runtime, you get a delegate instance. But a lambda is convertible to other things as well, like an expression tree.
4) They do not serve the same purpose. The expression tree is an object which represents the computation mentioned in the lambda. The delegate is an object which actually performs the computation mentioned in the lambda.
Delegates and expressions are not the same thing. Delegates are strongly-typed references to methods while expressions are in-memory representations of code that can be treated as data. An expression can be compiled into IL (the Expression.Compile method) and this will give you a delegate to that newly compiled method.
Just remember that an expression can be turned into a delegate, but a delegate is just a delegate.
Here the context for my question:
A common technique is to declare the parameter of a method as a Lambda expression rather than a delegate. This is so that the method can examine the expression to do interesting things like find out the names of method calls in the body of the delegate instance.
Problem is that you lose some of the intelli-sense features of Resharper. If the parameter of the method was declared as a delegate, Resharper would help out when writing the call to this method, prompting you with the x => x syntax to supply as the argument value to this method.
So... back to my question I would like to do the follow:
MethodThatTakesDelegate(s => s.Length);
}
private void MethodThatTakesDelegate(Func<string, object> func)
{
//convert func into expression
//Expression<Func<string, object>> expr = "code I need to write"
MethodThatTakesExpression(expr);
}
private void MethodThatTakesExpression(Expression<Func<string, object>> expr)
{
//code here to determine the name of the property called against string (ie the Length)
}
Everywhere that you're using the term "lambda expression" you actually mean "expression tree".
A lambda expression is the bit in source code which is
parameters => code
e.g.
x => x * 2
Expression trees are instances of the System.Linq.Expressions.Expression class (or rather, one of the derived classes) which represent code as data.
Lambda expressions are converted by the compiler into either expression trees (or rather, code which generates an expression tree at execution time) or delegate instances.
You can compile an instance of LambdaExpression (which is one of the subclasses of Expression) into a delegate, but you can't go the other way round.
In theory it might be possible to write such a "decompiler" based on the IL returned by MethodBase.GetMethodBody in some situations, but currently there are various delegates which can't be represented by expression trees. An expression tree represents an expression rather than a statement or statement block - so there's no looping, branching (except conditionals), assignment etc. I believe this may change in .NET 4.0, though I wouldn't expect a decompilation step from Microsoft unless there's a really good reason for one.
I don't believe it's possible to achieve what you'd like here. From the comments in your code it looks like you are attempting to capture the name of the property which did the assignment in MethodThatTakesExpression. This requires an expression tree lambda expression which captures the contexnt of the property access.
At the point you pass a delegate into MethodThatTakesDelegate this context is lost. Delegates only store a method address not any context about the method information. Once this conversion is made it's not possible to get it back.
An example of why this is not possible is that there might not even be a named method backing a delegate. It's possible to use ReflectionEmit to generate a method which has no name whatsoever and only exists in memory. It is possible though to assign this out to a Func object.
No, it is not possible.