Why declare properties twice in a class?

6

When declaring a property in a class, they usually declare twice, one public and the other private. What is the purpose?

private int _years;
public int Years
{
    get { return _years; }
}
    
asked by anonymous 17.05.2017 / 18:39

3 answers

11

You are not declaring the property twice, you are declaring a field and a property that uses this field. In something simple like this is not necessary to do this, you can do:

public int Years { get; }

The field is automatically declared internally (it is not available for your code, nor is it possible to know the name that is used except with reflection, which does not make sense).

When you need to do some algorithm inside the property, you need to explicitly declare the field as the property is no longer automatic.

If the field, not the property, is needed elsewhere in the class, then you need to declare it out. But this is seldom necessary.

We do not always need properties. There is even a school that is against them since it does not have a defined function. I think academicism.

There are cases that a public field can be useful or even better when you know what you are doing.

    
17.05.2017 / 18:44
8

The first purpose of properties in C # is to allow the class to publicly expose (state) values by keeping private (encapsulated) their implementation and validation.

This is achieved by using a private field ( backing field ) whose value is accessed through the get() and set() methods of the property.

The declaration of backing field can be done implicitly (automatically) or explicitly.

Explicit backing field statement is required if you want / need to take advantage of the purpose of using properties.

    
17.05.2017 / 19:04
5

Currently C # admits that you declare a property like this:

public Foo foo { get; set; }

And beneath the cloths you have the private field to store a value through the property name and be read with the name of the property.

This was not always the case ... In the older versions, you had to declare the field.

Today you only need a private field in this way if the property is read-only or read-only.

In time, the _years member in your question is a field, not a property. There is a difference between the two things, which I leave to your discretion to search (read documentation is annoying but it is didactic).

    
17.05.2017 / 18:45