Search code examples
c#propertiesautomatic-properties

Use of properties vs backing-field inside owner class


I love auto-implemented properties in C# but lately there's been this elephant standing in my cubicle and I don't know what to do with him.

If I use auto-implemented properties (hereafter "aip") then I no longer have a private backing field to use internally. This is fine because the aip has no side-effects. But what if later on I need to add some extra processing in the get or set?

Now I need to create a backing-field so I can expand my getters and setters. This is fine for external code using the class, because they won't notice the difference. But now all of the internal references to the aip are going to invoke these side-effects when they access the property. Now all internal access to the once aip must be refactored to use the backing-field.

So my question is, what do most of you do? Do you use auto-implemented properties or do you prefer to always use a backing-field? What do you think about properties with side-effects?


Solution

  • Eric Lippert has an excellent blog post that answers this question:

    If the reason that motivated the change from automatically implemented property to explicitly implemented property was to change the semantics of the property then you should evaluate whether the desired semantics when accessing the property from within the class are identical to or different from the desired semantics when accessing the property from outside the class.

    If the result of that investigation is “from within the class, the desired semantics of accessing this property are different from the desired semantics of accessing the property from the outside”, then your edit has introduced a bug. You should fix the bug. If they are the same, then your edit has not introduced a bug; keep the implementation the same.