0

Just want to know when to practice normal property declaration and auto-implemented properties

private instance variable and property:

private string apple;
public string Apple
{
    get{return apple;}
    set{apple=value;}
}

The auto-implemented properties:

public string Apple {get; set;}

Want to know when to use which.

Samson Yap
  • 33
  • 7
  • 1
    Basically, if you want to do something additional (either before setting `value` or afterwards, such as update another variable), you can use the normal declaration. Otherwise, you can use the one liner auto-implemented property. – Keyur PATEL Jun 16 '17 at 04:42
  • It's not just logic that requires explicit getters/setters. I often find myself dropping to an explicit backing field if I want a `readonly` backing field. There have been proposals for possible ways to do this with auto properties in both C#6 (primary constructors) and C#7 (Immutable types) but looks like they've both been delayed. – matt_t_gregg Jun 16 '17 at 05:16
  • @KeyurPATEL in what situation it is the best to use auto-implemented property? Can u give some scenario or examples ? – Samson Yap Jun 16 '17 at 08:10
  • @SamsonYap I can give scenarios for the other way round, always use auto-implemented properties UNLESS e.g. if you want B to become null when A is set to null, you would put this in A's `set` line: `set{ a=value; if (a == null) B = null; }`. This is the most basic example I could give, but the possibilities are endless. – Keyur PATEL Jun 16 '17 at 08:18
  • @KeyurPATEL , ok thx for your explanation. – Samson Yap Jun 16 '17 at 08:22

0 Answers0