Proper use of fields encapsulated in properties within a class

Which scenario should I use to change 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 this does not matter in this example, but what if someone adds additional code to the properties, and changing the fields through the properties will change some other things?

Can you say which way is better, or does it really not matter?

I know that with C # 3.0 I can write automatically implemented properties, but this is C # 2.0.

+2
source share
4 answers

I would say that using a property is usually better. If getters and setters are simple, anyway they can get jittery at runtime. And, as you said, perhaps other changes will be made to the property code.

A common change is to add change notifications by implementing INotifyPropertyChanged. Students will not receive notification if you set the fields directly.

I prefer my classes to use their own public interface, rather than internal. The exception for me is that I clearly do not want any side effects. It rarely happens.

+1
source

From my experience, always use properties and don't try to access your var directly. If in the future someone adds code to the property accessor, it’s his ability to check the side effects of his changes.

In this case, you will facilitate the work of testing. The change developer should only check public names, not internal vars.

+1
source

If you do some checking, for example, mark the Example object as invalid when the intVar value exceeds 100, then you should use Properties.

 public int IntVar { get { return this.intvar; } set { if ( value > 100) // handle this corner case else this.intvar = value; } } 

Say your private method does some calculations

 private void SomeMethod() { int result = ...; IntVar = result; } 

When SomeMethod is called, it is better to use a property here, so the property will handle the validation, since the field cannot do this.

+1
source

It does not matter and is a personal preference.
I prefer to use properties.

0
source

Source: https://habr.com/ru/post/951856/


All Articles