Variable accessing best practices

mwightman

Member
Joined
Aug 18, 2007
Messages
9
Programming Experience
10+
When accessing a variable from within a class should you use the public property or the private member.
 
I don't know if there is a best practice for this, but there are some considerations. If you use the property this will in turn use the private field, so this affects performance (though usually insignificant), but there could be time consuming lookups that has to be in place for external class usage that is redundant when you operate the class from within. Your property getter/setter may include other code that you want done when the value is set/get. If you then use the private field that code isn't done. That kind of code could be validation etc for external usage and not relevant to proper internal usage, so it could be skipped without harm, or you could benefit from that implementation also internally. It could also raise events like "PropChanged" that you want or don't want raised in some cases of internal usage, so you can choose to use the private field or the property.
 
Back
Top