Possible Duplicate:
Should you access a variable within the same class via a Property?
I ran into this recently and was curious if there was some sort of standard for which one you should reference while inside a class.
I mean really it shouldn't make a difference whether you access the member variable directly or go through the property (unless you need to dodge some custom setter code), but I wanted to be sure there wasn't a best practice for it.
partial class MyClass {
private string foo;
internal string Foo {
get {
return foo;
}
private set {
foo=value;
// I do other stuff
}
}
public void DoSomething() {
//Option 1;
Foo="some string";
//Option 2;
foo="some string";
}
}
This shouldn't be a choice you really make. Either the code in the setter is supposed to run, in which case use the property, or it's not, in which case you use the member variable. In most all situations one is right and one is wrong. Neither is always right/wrong in the general case, and it's unusual for it to "not matter".
For example, if the setter code is firing a "changed" event, do you want external objects to be notified that it changed, or not? If you're changing it in response to a previous change, probably not (infinite recursion anyone?) if no, you probably want to make sure it's fired (so that you're not changing a value and not notifying anyone of changes).
If it's just validating that the value being set is valid, then either you know that, in this context, the value is already validated and must be valid, in which case there is no need to validate again; set the property. If you haven't yet validated what you're about to set then you want the validation logic to run, so use the property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With