-3

approach 1

private string mynameField;
        public string myname
        {
            get
            {
                return this.mynameField;
            }
            set
            {
                this.mynameField = value;
            }
        }

approach 2

 public string mynameField { get; set; }

Need a specific difference between these above two?

JeffC
  • 22,180
  • 5
  • 32
  • 55
Neo
  • 15,491
  • 59
  • 215
  • 405
  • 2
    No difference, approach 2 is new feature reducing lines of code. This is called `Auto Implemented Property` https://msdn.microsoft.com/en-us/library/bb384054.aspx – Arghya C Nov 08 '15 at 16:16
  • 1
    The same in the current state. The above option allows for extra behavoir in the getter and setter – William Nov 08 '15 at 16:17
  • 1
    that backing field needs to be string not bool to compile – Ňɏssa Pøngjǣrdenlarp Nov 08 '15 at 16:19
  • 1
    Possible duplicate of [C# 3.0 auto-properties - useful or not?](http://stackoverflow.com/questions/9304/c-sharp-3-0-auto-properties-useful-or-not) – Metro Smurf Nov 08 '15 at 16:33
  • How do you have that much rep on this site and not be able to google simple stuff like this? This is dup'd on this site I don't know how many times and has got to have been covered by 500 blog posts... – JeffC Nov 09 '15 at 02:43

1 Answers1

0

The method with the private field makes it possible to execute some extra code. E.g.:

private double _torsion;
public double Torsion
{
    get { return _torsion; }
    set
    {
        if (value.Equals(_torsion)) return;
        _torsion = value;
        OnPropertyChanged();
    }
}

Alternatively you could also add some extra logic to the get function. Be careful though, to much logic and side affects are commonly seen as a anti-pattern.

If no extra logic is needed, the auto implemented property has some benefits in code-readability. Under the hood, if no extra logic is added, they will be the same.

(ps: this is an example from a WPF application where the XAML is informed when this property is changed.)

Stefan
  • 17,448
  • 11
  • 60
  • 79