-1

Is there a difference between the two syntax below? Is there any reason that one of them is preferred over the other?

public string PropertyA { get => throw new NotSupportedException(); }

public string PropertyB { get { throw new NotSupportedException(); } }
Zigzagoon
  • 787
  • 6
  • 16
  • 5
    That second one isn't valid C# FYI – BradleyDotNET May 16 '19 at 17:22
  • Does [any](https://stackoverflow.com/questions/27910985/what-is-the-difference-between-getter-only-auto-properties-and-expression-body-p) [of](https://stackoverflow.com/questions/46522877/what-is-the-difference-between-expression-bodied-syntax-vs-getter-syntax-on-il-l) [these](https://stackoverflow.com/questions/31764532/what-is-the-assignment-in-c-sharp-in-a-property-signature/31764663#31764663) questions help you? – René Vogt May 16 '19 at 17:24
  • Your first one was actually OK (though it still is) those two lines are the same. – BradleyDotNET May 16 '19 at 17:26

1 Answers1

1

It's only syntactic sugar.

public string PropertyA => throw new NotSupportedException();

and

public string PropertyB { get { throw new NotSupportedException(); } }

compile to the same byte-code.

The expression body is just a shorter way of making a read-only property.

I think it looks nicer in certain cases, but it's a style preference.

cj.vaughter
  • 248
  • 2
  • 6