3

In C# you could declare a property in two ways that seem very similar:

public string SomeProperty => "SomeValue";

vs

public string SomeProperty { get; } = "SomeValue";

Is there a difference between these two? (Ignoring the fact that "SomeValue" is not a very interesting value, it could be the result of a method call or whatever else would express a difference between the two forms).

Yishai
  • 90,445
  • 31
  • 189
  • 263

1 Answers1

9

In your example there is no functional difference because you're always returning a constant value. However if the value could change, e.g.

public string SomeProperty => DateTime.Now.ToString();

vs

public string SomeProperty { get; } = DateTime.Now.ToString();

The first would execute the expression each time the property was called. The second would return the same value every time the property was accessed since the value is set at initialization.

In pre-C#6 syntax the equivalent code for each would be

public string SomeProperty
{
    get { return DateTime.Now.ToString();}
}

vs

private string _SomeProperty = DateTime.Now.ToString();
public string SomeProperty 
{ 
    get {return _SomeProperty;} 
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • 2
    It's vice versa: the first will execute the expression each time; the second will return the same value. – Dennis_E Aug 31 '16 at 22:53
  • @Dennis_E Thanks, fixed. I realized I had it backwards when I started adding the pre-C#6 equivalent. – D Stanley Aug 31 '16 at 22:55