mezoid
mezoid

Reputation: 28690

What does () => mean in C#?

I've been reading through the source code for Moq and I came across the following unit test:

Assert.Throws<ArgumentOutOfRangeException>(() => Times.AtLeast(0));

And for the life of me, I can't remember what () => actually does. I'm think it has something to do with anonymous methods or lambdas. And I'm sure I know what it does, I just can't remember at the moment....

And to make matters worse....google isn't being much help and neither is stackoverflow

Can someone give me a quick answer to a pretty noobish question?

Upvotes: 10

Views: 881

Answers (6)

Guffa
Guffa

Reputation: 700152

It's a lambda expression. The most common syntax is using a parameter, so there are no parentheses needed around it:

n => Times.AtLeast(n)

If the number of parameters is something other than one, parentheses are needed:

(n, m) => Times.AtLeast(n + m)

When there are zero parameters, you get the somewhat awkward syntax with the parentheses around the empty parameter list:

() => Times.AtLeast(0)

Upvotes: 9

Joe Chung
Joe Chung

Reputation: 12123

() => Times.AtLeast(0)

() indicates that the lambda function has no parameters or return value.

=> indicates that a block of code is to follow.

Times.AtLeast(0) calls the Times class's static method AtLeast with a parameter of 0.

Upvotes: 4

Amber
Amber

Reputation: 526473

That's the definition of a lambda (anonymous) function. Essentially, it's a way to define a function inline, since Assert.Throws takes a function as an argument and attempts to run it (and then verify that it throws a certain exception).

Essentially, the snippet you have there is a unit test that makes sure Times.AtLeast(0) throws a ArgumentOutOfRangeException. The lambda function is necessary (instead of just trying to call the Times.AtLeast function directly from Assert.Throws) in order to pass the proper argument for the test - in this case 0.

MSDN KB article on the topic here: http://msdn.microsoft.com/en-us/library/bb882516.aspx

Upvotes: 2

Jimmy
Jimmy

Reputation: 91432

()=> is a nullary lambda expression. it represents an anonymous function that's passed to assert.Throws, and is called somewhere inside of that function.

void DoThisTwice(Action a) { 
    a();
    a();
}
Action printHello = () => Console.Write("Hello ");
DoThisTwice(printHello);

// prints "Hello Hello "

Upvotes: 12

micmoo
micmoo

Reputation: 6081

I don't program in C#, but Googling "C# Lambda" provided this link that answers your question!!!

Upvotes: 0

Daniel Earwicker
Daniel Earwicker

Reputation: 116654

Search StackOverflow for "lambda".

Specifically:

() => Console.WriteLine("Hi!");

That means "a method that takes no arguments and returns void, and when you call it, it writes the message to the console."

You can store it in an Action variable:

Action a = () => Console.WriteLine("Hi!");

And then you can call it:

a();

Upvotes: 13

Related Questions