Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you reference the Property or the Member Variable inside a class? [duplicate]

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";
    }
}
like image 515
Wrightboy Avatar asked Jan 23 '13 17:01

Wrightboy


1 Answers

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.

like image 69
Servy Avatar answered Sep 19 '22 16:09

Servy