tags:

views:

1333

answers:

6

I just came over this syntax in some of the questions in this forum, but Google and any other searchengine tends to block out anything but letters and number in the search so it is impossible to search out "=>".

So can anyone tell me what it is and how it is used?

+17  A: 

It's the lambda operator, used for lambda expressions. These are basically a shorter form of the anonymous methods introduced in C# 2, but can also be converted into expression trees.

As an example:

Func<Person, string> nameProjection = p => p.Name;

is equivalent to:

Func<Person, string> nameProjection = delegate (Person p) { return p.Name; };

In both cases you're creating a delegate with a Person parameter, returning that person's name (as a string).

See also:

(And indeed many similar questions - try the lambda and lambda-expressions tags.)

Jon Skeet
+1  A: 

Instead of using anonymous method like this:

somevar.Find(delegate(int n)
{
   if(n < 10)
      return n;
});

you simply write it like this:

somevar.Find(n => n < 10);

It will take the data type based on the return value.

milot
A: 

It basically means "goes into", like a parameter

MyObjectReference => MyObjectReference.DoSomething()

Usually you use them to pass functions into methods as parameters, or in LINQ statements

MyCollection.Where(myobj => myobj.Age>10)

For example.

qui
+5  A: 

It means awesomeness. For e.g.

x => x + 1

represents a method which takes x as a parameter and returns the successor of it.

button.Click += new EventHandler((sender, e) => methodInfo.Invoke(null, new object[] { sender, e }));

assigns an event handler to a button by invoking a method that a MethodInfo holds.

Serhat Özgel
I voted you up for the statmeent "It means awesomeness". It really is
qui
+1  A: 

here's a simple example from msdn

delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25

Anything before the => are the input parameters, and anything after is the expression. You can have multiple input parameters. Lambdas are mainly used with Linq.

Steve
A: 

It is part of the syntax of a lambda expression. A lambda expression is essentially a shortened form of a delegate or of an anonymous method. To illustrate, assume that I have an array of strings matching the letters of the alphabet. I could pick out the members of that array that contained values greater than "E" with the following LINQ expression:

var someLetters = alphabet.Where(l => l > "E");

The part of the lambda expression to the left of the "=>" identifies the variable name for the test (which is set to the individual members of alphabet) and the part of the lambda expression to the right of the "=>" identifies the processing. In this case the processing produces a boolean value that the Where logic uses to determine if each member of the alphabet is passed through to the someLetters array.

JonStonecash