Reputation:
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
Upvotes: 1
Views: 237
Reputation: 660128
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
Upvotes: 1
Reputation: 13730
Often the property contains simple logic, which you may miss out on accessing the variable directly.
public class MyClass
{
private List<string> _someList;
public List<string> SomeString
{
get
{
if(_someList == null)
_someList = new List<string>();
return _someList;
}
}
}
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.
Upvotes: 0
Reputation: 23789
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 to get
for something that only yesterday was a 'plain' property probably isn't a good idea.
Upvotes: 1
Reputation: 62037
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.
Upvotes: 1
Reputation: 14213
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.
Upvotes: 3
Reputation: 32639
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.
Upvotes: 7