Yishai Yishai - 3 months ago 13
C# Question

Difference between SomeValue {get;} = true; vs SomeValue => true; in Properties

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).

Answer

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