Why declare property twice in one class?

Asked

Viewed 119 times

5

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

private int _years;
public int Years
{
    get { return _years; }
}

3 answers

10


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

public int Years { get; }

The field is automatically declared internally (it is not available for your code, nor can you know the name that used save with reflection, which makes no sense to do).

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

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

We don’t always need properties. There’s even a school that’s against them since it doesn’t have a definite function. I think academicism.

Has cases that a public field can be useful or even better, when you know what you’re doing.

7

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

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

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

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

4

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

public Foo foo { get; set; }

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

This wasn’t always so... In the old versions, you needed to declare the field.

Today you only need a private field that way if the property is for writing or read-only.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.