A
A
Artem2022-04-05 09:27:14
C++ / C#
Artem, 2022-04-05 09:27:14

What is the difference between get/set and regular variable?

I often see something like this in my code:

public int trade_id { get; set; }
public string type { get; set; }
public string quantity { get; set; }
public string price { get; set; }
public string amount { get; set; }
public int date { get; set; }


And I don't understand why people do this. It would be nice if they indicated some kind of checks or something else in these properties. But you can declare an ordinary variable.
In general, if it's not difficult, please explain, only without links.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Stanislav Makarov, 2022-04-06
@Timon1221

There is only one main architectural reason - to expose a stable interface as a property, leaving behind the possibility to change its implementation. This will allow in the future to make some of the properties computable, or, as Hemul GM already noted , to add checks for some conditions / invariants. There is no need to rebuild client code.
True, only the authors of libraries / nuget-packages (public or private, within the company) do this consciously, the rest are more likely because they said so.

V
V Sh., 2022-04-05
@JuniorNoobie

What is the advantage of autoproperties, if in essence they just refer to an automatically created variable, why not directly refer to a variable without autoproperties? The fact is that at any time, if necessary, we can expand the auto-property into a regular property, add some specific logic to it.

H
HemulGM, 2022-04-05
@HemulGM

What will happen if you decide to add a check in the future? And I will say what will happen, you will rewrite the code wherever you use this variable) And smart people will add a setter or getter method and everything will work right away.

V
Vasily Bannikov, 2022-04-05
@vabka

If we omit the philosophical reflections on encapsulation and extension, then there is not so much left.
Many libraries, for example all sorts of serializers, work only with properties, but not with fields.
If you work with EF, you also need to do everything through properties.
In general, there are no problems when using properties, except for an additional 9 characters.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question