Search code examples
c#automatic-properties

Why do we need to create class variables to get and set a property?


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?


Solution

  • 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.