This post originated from an RSS feed registered with .NET Buzz
by Eric Gunnerson.
Original Post: Property or backing store from inside a class?
Feed Title: Eric Gunnerson's C# Compendium
Feed URL: /msdnerror.htm?aspxerrorpath=/ericgu/Rss.aspx
Feed Description: Eric comments on C#, programming and dotnet in general, and the aerodynamic characteristics of the red-nosed flying squirrel of the Lesser Antilles
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.