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

Mahesh Velaga picture Mahesh Velaga · Dec 25, 2009 · Viewed 16k times · Source

Sorry If I am being noob, I have this doubt, why do we use private variables and set them using properties ?

Why can't we just use properites alone ?

I am talking about situations like this

private string _testVariable;

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

I am thinking of simply using

public string MyProperty { get; set; } 

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

Thanks

Answer

Adam Robinson picture Adam Robinson · Dec 25, 2009

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.