Why should I use a private variable in a property accessor? Why should I use a private variable in a property accessor? asp.net asp.net

Why should I use a private variable in a property accessor?


Your examples are semantically the same. The concise property declaration syntax (just having { get; set; }) is a shortcut available in C# 3.0. The compiler actually creates a private backing variable and a simple getter and setter as in your first example.

If all you're doing is creating a getter and setter (and nothing actually happens when either occurs), then the concise syntax is a good option. If you have to perform any other actions (redraw a control, for example) when you set the value, then the full syntax is required.


Why redundant private variable? are these two strategies different ? can anyone please throw some light on this.

If all your doing is reading/writing a variable, then no. Otherwise, there's two reasons why you'd want a private variable:

Data validation

// Data validationpublic class IntWrapper{    private int _value;    public int Value    {        get { return _value; }        set        {            if (value < 0) { throw new Exception("Value must be >= 0"); }            _value = value;        }    }}

Getter/setter wraps up an underlying data store

public class StringBuffer{    List<char> chars = new List<char>();    // Wraps up an underlying data store    public string Value    {        get { return new String(chars.ToArray()); }        set { chars = new List<char>(value.ToCharArray()); }    }    public void Write(string s) { Write(chars.Count, s); }    public void Write(int index, string s)    {        if (index > chars.Count) { throw new Exception("Out of Range"); }        foreach(char c in s)        {            if (index < chars.Count) { chars[index] = c; }            else { chars.Add(c); }            index++;        }    }}


The second example that you give:

public string MyProperty { get; set; }

Is only available in later versions of the .Net framework (v3.0 onwards I believe)

The first example allows you to set breakpoints on the return and assignment statements, causing your debugger to break when the property is assigned / read.