Answer the question
In order to leave comments, you need to log in
How do static fields work in C#?
Hello!
I've been learning C# for a long time, but I came across a question at an interview, the answer to which I can't find anywhere on the Internet at all
How do static variables work in C# and in .NET in general
What is the difference between const and readonly fields
How does it look at the compilation stage?
PS I only know that it has something to do with meta tables, but I have no idea at all.
Please give a clear answer
. Thank you very much in advance!
Answer the question
In order to leave comments, you need to log in
The constant is calculated statically at compile time. Constants are substituted as literals in places where these constants are used. If you create a separate assembly only for constants, refer to this assembly from the main project, build the project, then this assembly can be deleted and everything will work, since there will be no references to the classes of this assembly in the main project, all constants will be substituted as literals . Also, a change in an assembly with constants will require you to rebuild the assembly that uses the constants.
Here is a good example .
A readonly field is a read-only field that can be set in the constructor of the type in which it is defined or at the site of the field declaration. If a field is marked with the static modifier, then its value can only be set in the static constructor of the type in which it is defined or at the place of the field declaration.
Do you have dial-up internet or pathological laziness? :))
1. Values of constants are applicable only at the assembly compilation stage.
2. Any static class fields are always available (of course, if visibility allows)
3. Any non-static class fields are available after creating an instance of the class https
://ru.stackoverflow.com/questions/651231/c-%D...
use of readonly fields in C#?
https://metanit.com/sharp/tutorial/3.3.php
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question