-1

I am writing to ask about what is the difference between lambda expression and equal sign in this example:

public string Id => ConfigurationManager.AppSettings["Id"];   

And:

public string Id = ConfigurationManager.AppSettings["Id"];   

Or there is no difference?

Drax
  • 63
  • 1
  • 1
  • 7

2 Answers2

3

The first statement isn't a lambda, it's an expression-body definition (valid starting from C# 6)

public string Id => ConfigurationManager.AppSettings["Id"]; 

Yo can apply it to methods, properties, indexers, per specs

It's just a more readable form (without get and return) of readonly property

public string Id
{
    get
    {
         return ConfigurationManager.AppSettings["Id"];
    }
}   

The second one is usual assignment, initializes the Id field

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
2
public string Id => ConfigurationManager.AppSettings["Id"]; 

This is not a lambda expression, but an expression bodied property. The AppSetting will be read whenever the getter of the property is invoked.

public string Id = ConfigurationManager.AppSettings["Id"]; 

This simply declares a public field and initializes it once when the instance is constructed. The AppSetting value will only be read at this time.

Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46