Referencing property vs underlying variable

jrvbdeveloper

Member
Joined
Jul 15, 2007
Messages
17
Programming Experience
Beginner
Hi,

With regards to best practice, I was just wondeirng whether it is better within a class to refer to the property name or its underlying variable?

For example, lets say I have a public property called ItemCount. This property returns a private variable called iNumItems. Outside of the class, if I needed the number of items I would use ItemCount. Within the same class, should I be using "ItemCount" or "iNumItems"?

Thanks.
 
Depends whether your property getter does more than just return a private field - and if you want that to happen also when getting the property from within the class.
 
As JohnH says, if you are just doing
VB.NET:
Get
   Return iNumItems
End Get

Then it makes little difference.

However, if you wish to do some more processing, or fire an event etc when the property gets read, then you should go through the property.

Personally, unless there is a specific reason to directly access the underlying variable, I would go through the property, as it makes the behaviour of the program more predictable.

FYI, the usual notation for encapsulated ( accessible via property) fields is to prefix them with an underscore.

Usually, 'I' is the prefix for Interfaces.

oh, and also in the case of troubleshooting, having all access through the property means that if you need to check what value is beng returned form the variable, then there is only one place you need to put a breakpoint, rather than having to find all the references to the variable
 
I usually prefer to use properties wherever possible. You can always put in checks to ensure that only valid data can go in and other useful stuff later. Also, if you decide that you need to add any code to it later then you won't break anything that references it in another assembly, even if you don't rebuild the other one if you start off with a property, whereas you might (not tested) if you use a field.
 
Back
Top