Tuesday, August 10, 2010

Why we should use property instead of making variable directly public or using two separate methods to get and set values of private variable?

First advantage of using property is, code looks cleaner than having 2 separate methods. You can simply call a property as if it was a field in the class.

Well, then you may ask why make it 2 methods, we can make it a public field, so that we can access it by creating an instance of the class.

The main advantage over using a Property instead of a public field is, with the property, you will get a chance to write few lines of code (if you want) in the get and set accessors. So, you can perform some validation or any other logic before returning any values or assigning to the private field.