46

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?

Community
  • 1
  • 1
Orca
  • 2,035
  • 4
  • 24
  • 39
  • 3
    Note that grammatically it is the => that is the operator and the () and the expression which are its operands. It's a strange operator; most binary operators take two expressions, not an argument list and an expression-or-block. – Eric Lippert Sep 02 '10 at 16:51

5 Answers5

64

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; }
Simon Steele
  • 11,558
  • 4
  • 45
  • 67
  • 2
    Roughly, indeed. For my series on some of the subtle differences between the lambda syntax and the anonymous method syntax start here: http://blogs.msdn.com/b/ericlippert/archive/2007/01/10/lambda-expressions-vs-anonymous-methods-part-one.aspx – Eric Lippert Sep 02 '10 at 16:53
10

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

syntax: (input parameters) => expression

Lews Therin
  • 3,707
  • 2
  • 27
  • 53
htr
  • 101
  • 3
3

Creating an anonymous delegate to specified method.

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

abatishchev
  • 98,240
  • 88
  • 296
  • 433
3

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

Community
  • 1
  • 1
Jake Pearson
  • 27,069
  • 12
  • 75
  • 95
  • 1
    Even better than sifting through SO is to go straight to the source: http://msdn.microsoft.com/en-us/library/bb397687.aspx – John K Sep 02 '10 at 16:38
  • Thank you. How about `public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup();});` ? I don't understand `webBuilder =>{webBuilder.UseStartup();});` – Avv Apr 28 '22 at 17:26
3

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();
            });
PiRX
  • 3,515
  • 1
  • 19
  • 18