Orca
Orca

Reputation: 2025

Meaning of () => Operator in C#, if it exists

I read this interesting line here, in an answer by Jon Skeet.

The interesting line is this, where he advocated using a delegate:

Log.Info("I did something: {0}", () => action.GenerateDescription());

Question is, what is this ()=> operator, I wonder? I tried Googling it but since it's made of symbols Google couldn't be of much help, really. Did I embarrassingly miss something here?

Upvotes: 46

Views: 43439

Answers (5)

htr
htr

Reputation: 101

=> this is lambda operator. When we don't have any input parameters we just use round brackets () before lambda operator.

syntax: (input parameters) => expression

Upvotes: 10

PiRX
PiRX

Reputation: 3565

It's way to pass anonymous delegate without parameters as lambda expression.

Similar to this from .NET 2.0

Log.Info("I did something: {0}", delegate()
            {
                return action.GenerateDescription();
            });

Upvotes: 3

Simon Steele
Simon Steele

Reputation: 11608

This introduces a lambda function (anonymous delegate) with no parameters, it's equivalent to and basically short-hand for:

delegate void () { return action.GenerateDescription(); }

You can also add parameters, so:

(a, b) => a + b

This is roughly equivalent to:

delegate int (int a, int b) { return a + b; }

Upvotes: 68

Jake Pearson
Jake Pearson

Reputation: 27717

This is an example of a lambda expression you can learn more here.

Upvotes: 3

abatishchev
abatishchev

Reputation: 100258

Creating an anonymous delegate to specified method.

Probably, in your case it will be a Func<string>

Upvotes: 3

Related Questions