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:
In short, static effectively means "associated with a type instead of any one instance of the type". So there's one set of static variables for a type (within an AppDomain) whether you have 0 instances or a million; you don't need an instance to access a static member, etc.
The exact point of initialization of static variables depends on whether there's also a static constructor or not, but very broadly speaking it's "once, usually before anything significant happens in the class". (See this blog post for a more detailed description.)
While readonly
fields can be either static or instance (i.e. related to the type or related to an instance of the type), const
values are always implicitly static (they're compile-time constants, so it wouldn't make sense to have one copy per instance).
You may sometimes see static
being described as "shared between all instances of a type" - I personally dislike that description, as it suggests that there has to be at least one instance... whereas actually, you don't need any instances in order to use a static member. I prefer to think of them as entirely separate, rather than being "shared" between instances.
Solution 2:
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 3:
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