mshwf
mshwf

Reputation: 7449

empty get in expression bodied syntax?

Is it possible to write this property:

string Error { get; }

in expression bodied syntax (=>),

for example:

 string Title
  { 
    get
      {
        return title;
      }
  }

becomes:

string Title => title;

Upvotes: 1

Views: 148

Answers (2)

marsze
marsze

Reputation: 17035

Yes, you can in C# 6.0. But you would still need to declare the backing field yourself:

string error;
string Error => error;

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500165

No, because this:

string Error { get; }

... is an automatically-implemented property. The compiler is generating a field for you behind the scenes, but you can't refer to that field within the code. If you need to use the backing field, you need to declare it yourself:

private readonly string error;
string Error => error;

That's basically what the compiler is generating for you - so if you want that, just write it yourself. It's pretty rare that that's useful though, IMO.

If you already have that field, you could either just write the property as above, or you could convert the field into the property, so use the property where you were previously using the field.

(It's more feasible if you want a property which is read-only, but backed by a mutable field - at which point it can't be auto-implemented if you want a genuinely read-only property. It could be a publicly-readable and privately-writable automatically-implemented property though.)

Upvotes: 12

Related Questions