Tell me, are there any rules for naming fields and properties in C # ?

For example, VS tells me automatically that fields should be named as _fieldName , and properties as PropertyName .

Shouldn't fields and properties have the same naming rules?

Isn’t it more convenient to name class variables using _ ? Indeed, in this case, it is immediately obvious that work is being done with a field or a class property.

2 answers 2

In OOP, there is such a thing as encapsulation — access to the fields of an object must take place indirectly through its methods (basically, get-set methods are meant). Properties in C # - simplify "heters" and "seters". They (properties) make sense to declare public (otherwise they are useless, except that object Sv {get; private set ;})

The following construction is often used:

 private object _example; //может быть просто example public object Example { get {return _example;} set { _example = value; } //value - зарезервированное слово, которое описывает значение, передаваемое при определении (переопределении/переменной); аналогично public void setExample(object val){ _example = val; } 

Properties in VS are highlighted with separate icons and over time you will understand that such rules for naming and separating variables from properties are much more convenient and practical than using only variables.

    Shouldn't fields and properties have the same naming rules?

    In no case, do not forget that the class field is a variable, and the property is, roughly speaking, a function. As for the VS prompts, it hints to you in such a way that it is better to make the properties public, forming the class interface, and the fields private.