locked
Private variable or property with private setter RRS feed

  • Question

  • Hi there,

    I'm still a little confussed over this property business.

    If I have a class, and I want to use a global variables that wont be used outside the class, am I better to just use private variable, or should I use a property with a private setter?

    Thanks

    Stu

     

    Wednesday, November 3, 2010 2:18 PM

Answers

  • Hi Stu - welcome to the forums.

    The private variable vs. the property with the private getter/setter is a bit of a 'religious' war, from my experience.  OO Purists will argue for the getter/setter approach, while others will argue the other way.

    Personally, I think that automatic properties make this almost a moot point, since you can declare the property and it declares the variable for you automatically.  Plus, if you have to change the implementation (to guard against multi-threaded access, for example, or add validation), the code that uses the property won't have to change.  So I would go for the private getter/setter.

    Phil

    • Marked as answer by hoakey Wednesday, November 3, 2010 3:29 PM
    Wednesday, November 3, 2010 2:37 PM

All replies

  • Hi Stu - welcome to the forums.

    The private variable vs. the property with the private getter/setter is a bit of a 'religious' war, from my experience.  OO Purists will argue for the getter/setter approach, while others will argue the other way.

    Personally, I think that automatic properties make this almost a moot point, since you can declare the property and it declares the variable for you automatically.  Plus, if you have to change the implementation (to guard against multi-threaded access, for example, or add validation), the code that uses the property won't have to change.  So I would go for the private getter/setter.

    Phil

    • Marked as answer by hoakey Wednesday, November 3, 2010 3:29 PM
    Wednesday, November 3, 2010 2:37 PM
  • Hi Phil,

    That's great. Just needed some clarrification. Insidentally - and I realise this is off topic slightly, how would validation be added to automatic properties?

    Regrds

    Stu

    Wednesday, November 3, 2010 3:59 PM
  • how would validation be added to automatic properties?

    Again?
    Wednesday, November 3, 2010 5:02 PM
  • Apologies if this is in appropriate. I felt like I had conficting advise in the previous thread, but had already clicked answer. Unless it's possible to continue a thread once it's been answered?

    Wednesday, November 3, 2010 5:09 PM
  • It is possible to continue a thread. Or you can unmark an answer if you're not satisfied.

    If you want validation in properties, you don't use automatic properties.

    Wednesday, November 3, 2010 5:21 PM
  • Appreciated, thanks.

    Stu

    Wednesday, November 3, 2010 5:31 PM