2

Very simple question but I find it very important to understand why we do it.

I can create a property in the class as follows:

1st Approach:

public class MyClass
{
   public string MyProperty {get;set;}
}

2nd Approach:

public class MyClass
{
    private string _myProperty;

    public string MyProperty
    {
        get
        {
            return _myProperty;
        }
        set
        {
            _myProperty = value;
        }
    }
}

Almost all of the articles use the later approach. Why do we need to create a temporary variable in the class to hold the string value. Why can't we just use the first approach? Does the second approach provide any benefits? Isn't it bad memory and performance wise to create extra variable to store a value?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
InfoLearner
  • 14,952
  • 20
  • 76
  • 124

4 Answers4

9

Automatic properties were not added to C# until C# 3.0, so many examples or articles which use the later form were written before C# 3.0 came out. Unless you need to do extra work in your property setters and getters, there is no reason to choose one over the other.

Alex McBride
  • 6,881
  • 3
  • 29
  • 30
  • 2
    Right answer. As the link explains, the first approach just gets the compiler to do the second one for you. They are not actually any different except saving keystrokes. – Rex M Dec 12 '10 at 18:37
1

Auto-setters, automatic properties or auto-implemented properties (the first approach) are only available for .NET Framework >= 3.0. So articles written prior to the Framework 3.0 release use the second approach.

The two approaches are equivalent. Internally they work in the same way, so I prefer writing less code and using the first approach whenever possible.

Daniel Peñalba
  • 30,507
  • 32
  • 137
  • 219
1

Automatic properties were not always available. Also, if you had some kind of special action in a property, but didn't want it to be executed internal to the class, the declared variable would be helpful also.

zsalzbank
  • 9,685
  • 1
  • 26
  • 39
1

Of course if you want to be able to access the backing field you'll still need to write the full syntax. For example if you're going to raise change events:

private string _name;
public string Name
{
    get
    {
        return _name;
    }
    set
    {
        if (_name != value)
        {
            _name = value;
            RaisePropertyChanged("Name");  // assuming this method handles raising the event
        }
    }
}