Re: class fields vs class properties

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Koda wrote:

What is the difference between class fields and class properties?

I think it's a little difficult to explain. Generally, a field is a declared variable:


  class Foo {
    int bar;
  }

This field is a private field, and good OO practice dictates that fields should always be private, so they can't be accessed from outside the class Foo. Now, if the field must be accessed from the outside, one used to use getter/setter methods to accomplish this, for example in languages like C++. So you'd have public methods that would allow for getting/setting the value of the bar variable, probably including some code for validity checking, especially on the setter. Like this:

  class Foo {
    int bar;
    public int GetBar() {
      return bar;
    }
    public void SetBar(int newbar) {
      // check newbar for validity
      bar = newbar;
    }
  }

Properties are a syntactically nicer way of putting this same code. In C#, the same class might look like this, using a property:

  class Foo {
    int bar;
    public int Bar {
      get { return bar; }
      set {
        // check the new value
        bar = value;
      }
    }
  }

Looking at the class Foo from the outside, it's also easier to work with properties, because you can use normal syntax to get the value of a property or assign a value to it:

  ...
  Foo foo = new Foo();
  foo.Bar = 5;
  Console.WriteLine(foo.Bar);
  ...

This advantage is seen by some as a disadvantage, I should mention - because the user of the property can't see the implementation of the getter code, it's possible that the property getter does a lot of computations every time the setter is called. In these cases it might still be a better idea to code a "traditional" getter in the form of a method, to suggest to the caller that getting the value is not a trivial operation.

Now, one final thing I should note: you were asking about *class* fields and *class* properties. In some languages, this is a way of referring to what's called (in C#) a "static" field or property. I'm not sure if that's what you meant, but just in case it is... a static field or property is one that only exists once per class type, not once per instance. To declare it, you'd use the keyword "static" with the declaration of the variable and/or the property. I'm not going into any more depth with this for now, please ask if you need more information on this.


Oliver Sturm -- omnibus ex nihilo ducendis sufficit unum Spaces inserted to prevent google email destruction: MSN oliver @ sturmnet.org Jabber sturm @ amessage.de ICQ 27142619 http://www.sturmnet.org/blog .



Relevant Pages