Alex Rivera | Logout

Should you access a variable within the same class via a Property?

Asked 2008-11-07T05:36:40.993
29

If you have a Property that gets and sets to an instance variable then normally you always use the Property from outside that class to access it.

My question is should you also always do so within the class? I've always used the Property if there is one, even within the class, but would like to hear some arguments for and against as to which is the most correct and why.

Or is it just a matter of coding standards being used on the project?

Edit
Report

3 Answers

10

It depends on whether you want to apply any logic implemented within the property setter, and so you really have to decide on a case by case basis.

When you go directly to the private field, you know that the field is being set to exactly what you say.

When you go through the Property, the value gets set according to the setter logic, so you get any business rules or validation you want over values assigned to that field.

Pretty hard to come up with a rule about when doing either is 'correct', about the only one I'd say I follow is that in constructor initialisation I'd pretty much never use the Property.

answered 2008-11-07T05:42:10.313
1

Yes I think you should use properties internally in your classes whenever possible. Properties are more flexible and allows you to add logic for validating it's value at a central place.

You can also delay the initialization of the the field to whenever the property is used instead of being forced to do it in the constructor (or everywhere the field is used). Example:

class Test {
   private int _checksum = -1;
   private int Checksum {
      get {
         if (_checksum == -1)
            _checksum = calculateChecksum();
         return checksum;
      }
   }
}
answered 2008-11-07T05:49:30.080
0

Always Use Properties, Here are some of the reasons

  1. Easy to Use. In visual Studio you can use "Prop Tab Tab". You will get the property snippet
  2. Properties are language elements that are accessed as though they are data members
  3. .Net framework classes uses it, the data binding code classes in the .NET Framework support properties,
  4. Properties have all the language features of methods. Properties can be virtual
answered 2008-11-07T05:51:23.210

Your Answer