D
D
Denis Bredun2020-07-06 23:31:03
C++ / C#
Denis Bredun, 2020-07-06 23:31:03

Why do we need static (emphasis on the word "static") fields/automatic static properties in a class?

Good day! It just dawned on me that I know what static fields are, what is the difference between static and dynamic fields, but I don’t understand why static fields are needed. What are they needed for? What if we want, for example, to change the value of a field of type int from 5 to 9 in all classes? Or if we, for example, want that if the value changes in one class, then in all the others, like we don’t need to write a lot of code and process each class? Are they comfortable in that sense?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Victor Bomberow, 2020-07-07
@Luffy1

The static memory area is initialized before the main entry point is executed.
A static class guarantees the existence of a single instance of the class.
A static field allows you to implement the storage of data that will exist until the exit from the main function.
A static constructor allows you to pre-initialize a class before even creating at least one instance of the class.
Static data can thus be considered the property of the main thread, the original process.
In general, everything static is used for initialization, which should happen before runtime. But this is true only for the scope of each class / class hierarchy, and not the entire set of classes in the source code, because it is bad manners to control the order in which static constructors are evaluated.
If the use of the code does not involve the use of the class in several threads, then the use of "shared" data in static fields is allowed, but as a rule, this is only rational for readonly and const.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question