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

34,678

Solution 1

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; }

Solution 2

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

syntax: (input parameters) => expression

Solution 3

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

Solution 4

Creating an anonymous delegate to specified method.

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

Solution 5

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();
            });
Share:
34,678
Orca
Author by

Orca

Updated on July 09, 2022

Comments

  • Orca
    Orca almost 2 years

    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?

  • abatishchev
    abatishchev over 13 years
    Probably return action.GenerateDescription();, no? Otherwise error "Can't cast void to string", something like that
  • PiRX
    PiRX over 13 years
    @abatishchev, probably yes. Wrote it from top of my head, so I'm not sure it even compiles.
  • John K
    John K over 13 years
    Even better than sifting through SO is to go straight to the source: msdn.microsoft.com/en-us/library/bb397687.aspx
  • Eric Lippert
    Eric Lippert over 13 years
    Roughly, indeed. For my series on some of the subtle differences between the lambda syntax and the anonymous method syntax start here: blogs.msdn.com/b/ericlippert/archive/2007/01/10/…
  • abatishchev
    abatishchev over 13 years
    Could you please try and if it will fail - edit your post please?)
  • Avv
    Avv almost 2 years
    Thank you. How about public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup<Startup>();}); ? I don't understand webBuilder =>{webBuilder.UseStartup<Startup>();});