C
C
cehka2018-05-26 21:42:25
OOP
cehka, 2018-05-26 21:42:25

How do automatic get;set properties work in c#?

I read the book and reached automatic properties. For example:
public int Age {get; set}
Properties are needed to encapsulate private variables so that they can be changed, but I did not understand the syntax, we write public. I re-read the chapter in the book, and did not understand why public is written and the compiler thinks that it is private.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Matvey Pravosudov, 2018-05-26
@cehka

public int Age { get; set; }
There is no private property in this code, and the compiler creates it itself. The default getters and setters are used here, that is, a value is simply assigned and retrieved.
And here we encapsulate the property _age:

private int _age;
public int Age
{
    get => _age;
    set => _age = value;
}

You can read more on some Metanit .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question