When referencing class properties from a function within the class do you use the value from the actual property or the private variable value?
Which way is best? Why?
public class
private m_Foo as double
public property Foo() as double
get
return m_Foo
end get
set(byval value as double)
m_Foo = value
end set
end property
public function bar() as double
Dim x as double = 5 * m_Foo
Dim y as double = 3 * Foo
end function
end class
The property code may contain -- now or in the future -- logic that returns a different value or sets a different value depending on the state of the object. It makes sense to use the property.
Two things.
First, this is a duplicate of
When should a class use its own getters/setters vs accessing the members directly?
Second, here's my article from earlier this year on a closely related subject:
http://blogs.msdn.com/ericlippert/archive/2009/01/14/automatic-vs-explicit-properties.aspx
Often the property contains simple logic, which you may miss out on accessing the variable directly.
if you then access
_someList
directly, you may run into a null reference. Accessing the property directly ensures it's been initialized.Some may argue the private variable should have simply been declared as new in the first place, or initialized in the constructor rather than the property - but this should at least highlight a possible issue as this is a common approach.
It's probably safer (but not better) to use the property just in case you add additional
get
logic later on. Of course, adding logic toget
for something that only yesterday was a 'plain' property probably isn't a good idea.I prefer the latter. If your property simply returns the field, the compiler will optimize your calls to it away. And you need to protect yourself against your own changes just like everyone else. What if the property later does something to the field before returning it, you'd have to update all your internal code to accommodate.
Personally, I try to use the get/set accessor whenever possible, to avoid surprising myself when I change their logic and suddenly places where I access the private field don't work as expected.