Property or backing store from inside a class?

Josh writes,

If you’ve implemented a public property for a private field and you’re modifying the field from with-in the class, is it best to use the property, or modify the field directly. For example:

class Foo
    private object    _Bar;

    public object Bar
        get { return _bar; }
        set { _bar = value; }

    public void FooTheBar
        Bar = new object();

        // or

        _Bar = new object();



This is an interesting question.

I generally write all my classes using the backing store, since in my mind, the property is the “outside the object” view, and I’m writing code that’s inside the object.

I might relax this if the property has some additional behavior (ie it’s a derived value with no backing store, or there’s additional behavior such as “lazy load”), but in those cases I would prefer to encapsulate that behavior in a private method and then use it in both the property and in my location. If you use the property directly, then the class becomes atypical, and that means you might not remember that use when you go to modify the property later.

Other opinions?

Comments (24)

  1. jaybaz [MS] says:

    When I find myself asking this question, I often end up doing a refactoring that makes the question moot.

    If the value is set in the ctor, and never changes, and the containing class is internal, I’ll make the field into a public readonly field, and dump the property entirely.

    If the value has lazy-load semantics, I can extract that behavior into a new class.

  2. Robert Björn says:

    I’ve been pondering this issue a lot as well and haven’t quite decided what to do. Your suggestion seems like the cleanest to me.

  3. AndrewSeven says:

    I’ve been thinking about using a different naming convention depending on whether or not it is "safe" to use the private variable directly.

    It occurred to me that it would have been nice to have the option of somehow defining the private variable within the property definition so that the private member can’t be used from anywhere else in the class.

    public string MyString


    string _myString;



    _myString =value;




    return _myString;



  4. Eric Wilson says:

    In my mind, it would be better to always use the property itself, instead of the backing store.

    In general, a get accessor will always be inlined by the JIT, so there is no really performance reason to use the backing store.

    The whole reason for the property in the first place is to abstract the underlying store from the clients. If you accept that this is a good thing (and I think at this point most of us accept that it is a good idea), why would you not want to abstract the property away for internal properties/methods as well?

  5. Mike Dimmick says:

    I’d tend to use the property, because then I’ve got only one place I need to put any constraints (for example, the value can’t be null). It’s better to ensure that your invariants can’t be broken even internally.

    I’ll then use the private field directly only if I actually need to break an invariant for a short time.

  6. I’m with you ericgu. Another reason to most of the time use the backing member is because if the property is readonly anyway you can’t set it through the property, but you’re right and i agree that calling the property when there is some underlying functionality in there is good when necessary.

  7. I like using the backing store because there are cases where the property accessor may enforce permissions or other constraints that you wouldn’t want to occurr every time you access the actual backing store from within your code.

  8. Paul Tyng says:

    For Lazy Loading behavior or some other behavior I typically use a protected or private property and expose it publicically with another property. Similar to Mike D’s comments, you can’t do any business logic on direct field access, its arguable that this logic shoudl be taking place in whatever is setting the property but its easier to abstract that logic I find. I find sometimes that the rules or logic that apply are sometimes split between public access and private access (public access typically uses a superset of behavior), so this allows for that. Otherwise there really isn’t any easy way to modify the behavior of a field if you are just accessing it directly if the need arises in the future.

    Something like:

    class Foo

    public Bar { get { return InternalBar; } set { InternalBar = value; } }

    protected InternalBar


    Lazy Load, etc..


  9. Paul Tyng says:

    The 2 properties method is typically used for inheritance reasons in my projects (or if it fis the problem) 1 prop works best obviously. I think your implementation depends on the functionality the class is trying to provide, if subtypes need to access the property or change the behavior, obviously the properties are a necessity and you should be accessing the values through them.

  10. John Morales says:

    using the property breaks encapsulation rules and makes my bad-OO-dar go off. the property functions are the encapsulation barrier, so when you are "inside" the class use the private state variable. the lazy load semantics are easily kept in the property get ore refactored into an initialization function.

  11. Joe White says:

    I don’t think properties are for external consumption only — that argument has a bad smell to it. If they’re not general-purpose enough to use from inside the class itself, then they’re badly designed.

    I prefer to use the property rather than the backing store, whenever I can. That way I don’t have to worry about fixing everything if I change the field’s implementation later. There’s a refactoring in Fowler’s book, "Self Encapsulate Field", to do exactly this. Unfortunately, there’s no compiler support for making sure you’ve removed all unnecessary references to the field.

    I like AndrewSeven’s suggestion (declare the variable inside the property block), except that 90% of the time, you also need to be able to access the field from your constructor. Oh well.

  12. Andy Smith says:

    Most of the classes I write are server controls. And in that arena, there generally is no private variable. Your backing store is the ViewState bag. And there is no way i’m going to access my values direct from viewstate every time. And writing two properties (public and private) for every property seems like a gigantic waste of time.

    So I’m fairly used to just using the public property. So in the rare case that i’m writing a "normal" class, I tend to use the public property over the private implementation, just because I’m used to it.

  13. Ryan H. says:

    Neither way is more technically correct, according to OO principals. The whole point of internal/external access is to maintain proper state within your objects. That said, here are what I see as the possible main advantage and disadvantage to using properties internally:

    Advantage: It’s much easier to maintain consistent state for a private field when the logic is encapsulated in a property. Using the property internally makes it easier to maintain internal consistency, since you do something only once (and, of course, maintenance of the code is also easier – if you suddenly decide to change the behavior of the private field).

    Disadvantage: Performance. But this should be eliminated by inlining in a modern compiler.

    So, I really see only an advantage to using properties – and a sizable one at that.

    Note: Some may consider the internal use of properties as a slight disadvantage for readability, as this adds another level of indirection in the code, but I think this is minor.

  14. I always use the Property, unless doing something like setting the holder from the constructor. The number two reason to use properties is in case you decides you need some extra code in there – say range checking or something – then you don’t have to go and hunt down all references to the field.

    It would be very easy to miss an internal reference given that there would be no compile or even runtime errors if most input is in the proper range. So you get potential hard to catch or even notice bugs, but you gain nothing. The only potential case where this isn’t inlined by the compiler (afaik) is when there is extra code, in which case you want the call anyway.

    Of course there are situations where you treat the private store differently internally, but those are usually suspicious situations I think – not always wrong, but often a shortcut…

    I like the idea of a private var inside the property, though I’ve always thought there should be also a ‘holder’ keyword, akin to the ‘value’, used for the store of internal property. In 90% of situations you could just use that, and if you didn’t it just wouldn’t be created (so no need to change existing code). Maybe even give default get/sets with something like:

    public string Test : get, set;

    I do find properties a bit of a pain to generate, and a bit of a large blob of code for very little functionality. However, if we’ve already accepted that, then we might as well use them to solve all the problems (internal and external!) they are meant to solve : ).

  15. Darren Oakey says:

    This is quite interesting – I’ve run into this lots. I _always_ use the internal value – and if there is any "work" to be done on it, throw in a protected accessor that I use – so instinctively agree with Eric and others…

    However, it’s hard to explain why. Sometimes it’s just a lot more work to do it that way – and sometimes you use other people’s code who’ve actually put some "work" directly into the property getters and setters, and using the internal variables actually causes problems because you skip raising events or validating or something..

    It’s just that, for me, there’s an instinctive need to identify something as either part of the internal or the external interface. I scream at the concept of something that is somewhere in between, that can be used for both purposes, but when I think about it I honestly can’t think of a single good reason why it’s bad… it just "feels" wrong 🙂

  16. "..there’s an instinctive need to identify something as either part of the internal or the external interface."

    The way I see it, properties are part of the external interface (assuming they are public), just like methods. I would see calling the internal store more like manually inlining a method. That all seems fine until there is a change, then at minimum it is a hassle. That leads to pressure to just forget about changing things unless it is something major.

    I really think all that kind of optimization is best left to the compiler.

  17. Me says:

    I agree with AndrewSeven, it would be nice to be able to optionally hide a property’s backing field so only the property accessors can access it.

    It’s another level of information hiding. Not always appropriate, but there are cases where it would be useful, e.g.:

    public string MyString


    string _myString;



    _myString =value;



    get { return _myString; }


    By hiding _myString you are guaranteeing that DoSomethingElse() is executed whenever it is modified, whether the code doing the modifying is inside or outside the class. Or whether it’s written by you or a maintenance programmer in 6 months time.

    Another example is that the compiler would detect typos when you cut and paste code to generate similar properties like the following:

    public string FirstName


    string _firstName;

    get { return _firstName; }

    set { _firstName = value; }


    public string MiddleName


    string _middleName;

    get { return _middleName; }

    set { _firstName = value; } // compile error, _firstName not accessible here


    public string LastName


    string _lastName;

    get { return _lastName; }

    set { _lastName = value; }


  18. Robert Bullen says:

    Coming from a Delphi background, I’ve grown to love properties and C# has a great implementation of this language feature. Over the years I have mulled over this issue many times…and changed my mind many times. For a long while I adopted Eric Gunnerson’s convention.

    Now, however, I always prefer to access properties over their backings stores. There are always exceptions to the rule, but it has many advantages: encapsulating constraints, event triggering, lazy initialization, and more listed by others.

    In addition to those great reasons, I would like to add one more–being able to handle changes well. Encapsulating a property allows the implementation of the property to change over time without having to update an entire class, only the accessor/mutator.

    And speaking of being able to handle changes, I noticed that one thing has been left out of this discussion: polymorphic properties. In situations where a property is introduced as virtual or inherited from an interface, it is mandatory to access the property internally instead of the backing store (in the case of the latter, properly accessing the property in a polymorphic manner must be done via the interface). Not doing so can cause bugs when derived classes override the property or re-implement the property’s interface to use a different backing store.