views:

77

answers:

2
Public Class FooBar
{
    private int _foo;

    public int Foo { 
        get { return _foo; }
        set { _foo = value; }
    }

    public void DoStuff()
    {
        _foo++; // Do this?
        Foo++; // Or this?
    }
}

Is there a more accepted practice to either access fields or properties (if one exists) in a class? I've always been in the habit of accessing the field, but since I've been doing WPF which has a lot of INotifyPropertyChanged, I've found myself needing to access the Property to get the notification changed. So now I have a mix of both field and property accesses throughout my classes and while from a compiler point-of-view it doesn't matter, stylistically and readability, it feels...awkward.

+2  A: 

There are certainly cases that accessing the property doesn't make sense (for example, if you were implementing the property itself). Putting those cases aside, I'd go with property style by default (unless I have a specific reason not to). Accessing the field through the property will direct all the changes into a single code path making changing the implementation and debugging easier and can be less error-prone.

Mehrdad Afshari
the single code path is a big reason why I started feeling uncomfortable with all my previous field accessing too. If I start out with fields, then add a bunch of property accesses, then later add some extra functionality in my property setter, the property accesses will hit that, but all the field accesses won't.
qntmfred
+2  A: 

A lot of this comes down to personal style. There is no 100% right or wrong answer here.

My preference is to go through the property every time for a couple of reasons

  • Makes debugging easier as you can break on property access and see all get / set of the value. Not possible with a field
  • Consistency: In some cases, such as auto properties, it's not possible to go directly to the backing field. Going through the property every time shows the same code accessing the same value.
  • Performance: Simple properties are likely inlined by the JIT so the performance issue is usually a mute point.
JaredPar