Which scenario should I use for changing private fields inside class methods/properties:
public class Example
{
private int intVar = 0;
private string stringVar = string.Empty;
public int IntVar
{
get { return this.intvar; }
set { this.intvar = value; }
}
public string StringVar
{
get { return this.stringVar ; }
set { this.stringVar = value; }
}
private void SomeMethod()
{
//change fields in this way:
this.intVar = 50;
this.stringVar = "changed";
//or that way(through properties):
this.IntVar = 50;
this.StringVar = "changed";
}
}
Maybe in this example it makes no difference, but what if someone add extra code to properties, and changing fields through properties will change some other things?
Can you say which way is better, or it really makes no difference?
I know that since C# 3.0 I can write auto-implemented properties, but this is C# 2.0.
I’d say using a property is usually better. If the getters and setters are simple, they might get inlined by the jitter at runtime anyway. And as you said, maybe other changes will be made to the property code.
A common change is adding change notifications by implementing INotifyPropertyChanged. Listeners would not get notified if you set the fields directly, then.
I prefer my classes to use their own public interface rather than internals. An exception for me is when i explicitly do not want any of the side effects. That is rarely the case though.