-1

What are the pros and cons of expression-bodied properties vs straight property declarations? For example, is there any advantage to using;

public string Foo => "Bar"

vs simply

public string Foo = "Bar"

My understanding was the => is used when the value comes from a method, like a lambda function. If the value is a primitive like a string or int, why would anyone use an expression-bodied property for that?

TomDane
  • 1,010
  • 10
  • 25
  • 1
    They are different declarations – Pavel Anikhouski Jul 17 '20 at 16:48
  • 1
    Duplicate of “why use properties”... searching for the link – Alexei Levenkov Jul 17 '20 at 16:49
  • This does seem less about expression-bodied properties and more about why use properties over fields: [Why use simple properties instead of fields in C#? [duplicate]](https://stackoverflow.com/questions/2374416/why-use-simple-properties-instead-of-fields-in-c) That is also a dup, but has some good anwsers – Dweeberly Jul 17 '20 at 17:28

1 Answers1

1

There are quite a few differences between those two lines of code:

  1. The first one is a property, the second is a field. For example, you cannot ref the first Foo.
  2. The property gets evaluated and returns a new object every time, even if the object is the same string literal. The variable is evaluated once and when used it's just loaded. (Note that a better way to write #1 is public string Foo { get; } = "Bar"; which would also be initialized once and then return the same value).
  3. The first one is read-only (it's a getter only), while the second one is a mutable variable, you can write into it. A closer equivalent would be public readonly string Foo = "Bar"; or even better public static readonly string Foo = "Bar";
Blindy
  • 65,249
  • 10
  • 91
  • 131