Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does () => mean in C#?

Tags:

c#-3.0

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?

like image 697
mezoid Avatar asked Aug 01 '09 06:08

mezoid


2 Answers

()=> 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 "
like image 50
Jimmy Avatar answered Sep 20 '22 23:09

Jimmy


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();
like image 32
Daniel Earwicker Avatar answered Sep 18 '22 23:09

Daniel Earwicker