'What does `static` mean in c#?
I am really confused with the real meaning of the static keyword in C#. I have gone through different articles on internet but none of them are really helping me to understand it's meaning and other sources are not trusted. I know Stack Overflow has some brilliant minds who can help me understand the real meaning of static like
- When they get initialized.
- static methods, properties, classes and constructors
- Static vs readonly vs constant
Solution 1:[1]
I can recommend this article, it seems pretty descriptive: Static Keyword Demystified
I would also recommend an official c# Programming Guide article which covers the various uses of the static keyword. You can go from there since there are a lot of links to different MSDN articles.: Static Classes and Static Class Members (C# Programming Guide)
Solution 2:[2]
A little about constant (const) and readonly:
- constant or const is variable which cannot be modified,and which value is known at compile time.
- readonly is very similar to constant, this cannot be modified either, the difference is that a readonly field can be modified/initialized once in the constructor. After that readonly is the same as constant.
Using examples:
constant:
const int a=10; // value cannot be modified, value is known at compile time
But what to do when we want constant field whos value is not known at compile time?
e.g const PersonClass a=new PersonClass("name"); // error
The answer is a readonly field:
readonly:
readonly PersonClass a=new PersonClass("name"); // all correct
Solution 3:[3]
From documentation:
The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration
Static members are intializeed on first access to the class and are executed in textual order.
Static methods, properties are parts of the class and not instance.
Static has nothing to do with readonly or constant. Static is a way like a member acessed, readonly and constant is way like a member stored/managed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AminM |
| Solution 2 | CSharpened |
| Solution 3 |
