19

Is it good practice to use the private field, or the property, when writing code in the class that contains them?

For example, if I have this field/property pair, classes outside this class must use the property. What about code inside the class? Should it use the private field, or should it also go through the property?

private string _foo;

protected string Foo
{
    get { return this._foo; }
}

private void SomeMethod()
{
  string dummyVariable = "snuh" + this._foo;  // So, this...
  string dummyVariable = "snuh" + this.Foo;  // ... or this?
}

One advantage of using the property here, is if there is any logic in the getter, it will still get executed. I'm curious to know if there is a best-practice policy to follow here.

Bob Horn
  • 33,387
  • 34
  • 113
  • 219
  • 1
    My **opinion** is that it does not matter (given that your property does not do anything special) as long as you are consistent, but I'm curious what others have to say. – Tung Apr 28 '12 at 19:43
  • possible duplicate of [Best Practice on local use of Private Field x Property](http://stackoverflow.com/questions/833047/best-practice-on-local-use-of-private-field-x-property) – Matt Apr 28 '12 at 19:44
  • A nomenclature note: You're using the term "variable" incorrectly. In this case, you mean "field". – Daniel Mann Apr 28 '12 at 20:22
  • Good point. I'll change it. Thanks! – Bob Horn Apr 28 '12 at 20:31

1 Answers1

10

When using Auto-Implemented properties, you don't have a choice - you must use the property, as you don't have any access to the generated field.

If you property is not simple and does some extra work (validation, firing events etc...), you should call the property in order to centralize access and logic.

If you have any other properties (meaning a simple property with no logic and a backing field) I would ask why are they not one of the above...

With the example you have give, it makes little difference - it is more important to be consistent with how you use these and really boils down to personal aesthetics and coding style.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 1
    Two use cases for simple, non-automatic properties come to my mind: properties with non-default initial values (C#) or properties with a private setter (VB.NET). – Heinzi Apr 28 '12 at 20:38
  • @Heinzi - True, and the part of my answer regarding the example would apply to those as well... – Oded Apr 28 '12 at 21:28