Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Within the Containing Class, Use Property or Field?

Tags:

c#

properties

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.

like image 893
Bob Horn Avatar asked Apr 28 '12 19:04

Bob Horn


People also ask

What is the difference between field and property?

Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.

What gives a class property a field?

A field is a variable of any type that is declared directly in a class. A property is a member that provides a flexible mechanism to read, write or compute the value of a private field. A field can be used to explain the characteristics of an object or a class.

What is the properties of a class?

Properties are attributes or features that characterize classes. While classes are groups of objects, an instance is a specific object that actually belongs to a class.

What are fields and properties in C#?

Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax.


1 Answers

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.

like image 173
Oded Avatar answered Sep 22 '22 19:09

Oded