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...