What does "static" mean in C?

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.


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

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)


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.

Tags:

C#

C

Syntax

Static