Which of the following two is better? Why?
Ex. 1:
public class TestClass
{
public TestClass(CoolClass cool)
{
this.Cool = cool;
}
CoolClass _cool
public CoolClass Cool
{
get
{
return _cool;
}
set
{
_cool = value;
}
}
}
Ex. 2:
public class TestClass
{
public TestClass(CoolClass cool)
{
_cool = cool;
}
CoolClass _cool
public CoolClass Cool
{
get
{
return _cool;
}
set
{
_cool = value;
}
}
}
(I know that one can simply do public CoolClass { get; set; }, but let’s ignore that for a sec.) I guess it just boils down to: From within a class, should one use its properties or its corresponding fields for getting/setting values?
EDIT: Thank you all very much for your responses. It seems that there are a lot of conflicting opinions out there. So here is what I decided on, let me know what you think:
I will use properties whenever possible; only when there are side effects I will use another way of access.
Why?
– I like the idea of only accessing a variable from one place.
– I can easily integrate logic into variable access.
– I often use public CoolClass { get; set; }, so using properties whenever possible is more consistent.
And I noticed, that unfortunately it is not possible to declare a property with several getters/setters that have different visibility modifiers – it would have been nice to have a private setter as well as a public one…
The answer is, it depends. Style-wise, I find it nicer to set properties. That way, your private variable is only touched in one place, and if the logic changes in the future and you need to call the property, you’ve already prepared for that. But that’s really just my personal preference. One place where you’ll need to consider whether to set the property is if you have some kind of side-effect – when some other variable or property changes or an event fires based on the value you just set in the other property.
On the flip side, you often will have member variables that you will not expose to the outside world. It’s probably not worth setting up private getters/setters for those, unless you’re managing setter side-effects or getter calculations. Pick whichever is easier to read. Performance is negligible. Style and anticipating future change is everything when you’re considering that this is code you’ll have to maintain.