Stats

166 Contributors: 8
2016-11-20
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

Properties

Download c# eBook

Remarks

Properties combine the class data storage of fields with the accessibility of methods. Sometimes it may be hard to decide whether to use a property, a property referencing a field, or a method referencing a field. As a rule of thumb:

  • Properties should be used without an internal field if they only get and/or set values; with no other logic occurring. In such cases, adding an internal field would be adding code for no benefit.

  • Properties should be used with internal fields when you need to manipulate or validate the data. An example may be removing leading and trailing spaces from strings or ensuring that a date is not in the past.

With regards to Methods vs Properties, where you can both retrieve (get) and update (set) a value, a property is the better choice. Also, .Net provides a lot of functionality that makes use of a class's structure; e.g. adding a grid to a form, .Net will by default list all properties of the class on that form; thus to make best use of such conventions plan to use properties when this behaviour would be typically desirable, and methods where you'd prefer for the types to not be automatically added.

Related Examples