Alex Rivera | Logout

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

Asked 2009-12-25T17:20:03.267
27

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

Edit
Report

1 Answer

0

I HATE backing variables when they are not needed it is causes more complexity then necessary.

Obviously if you have the need to do something special in the getter or setter then the full semantic form should be used and not the sugar.

Also I like to use properties as a method of debugging how the property gets set or gets used sometimes this isn't as obvious because of reflection and that is one reason I like to use them.

I find it frustrating trying to debug code when there is a possibility that the backing variable maybe accessed either internally in the class by the property it self or the backing variable and nothing tells the coder the right way to access.

You can access the backing variable internally as well as the property so which is the right way? It is not obvious...

answered 2013-07-09T13:31:13.197

Your Answer