| ||||||
| ||||||

StaticGoals:
Overview
The keyword Static field
Regular fields are often called "instance fields" because each instance of the class
gets their own copy. Consider the following
By contrast, there is only one copy of each
Client code that needs to use a static field must access it using the class name.
Static fields are used to implement the concept of "shared resource" since the single copy can be shared by multiple clients. In other languages, this role is often filled by global variables. The type designer can choose the access level for a static field: private static fields are shared only by instances of that type while public static fields are shared by all clients. The memory for static fields is allocated by the CLR when the class is initialized. Conceptually, you can think of this as occurring "at program startup"; however, the exact timing is up to the CLR and in many cases this setup will occur later. The key thing to take away is that the memory for a static field will be available for use even if no objects of that type have been created. Static field default valuesStatic fields of a class are set to default values when the class is initialized by the CLR. The default values depend on the type of the field.
Numeric fields such as
Fields of type
Characters fields are set to the null character (often written
References are set to
Static variable initializerStatic fields can be initialized inline, that is, at the point of declaration. The official name for this technique is 'static variable initializer'.
Static constructor
The most powerful initialization technique is to provide a static constructor.
The static constructor is defined using the keyword
Static method
A method can be made static by adding the keyword
A static method must be invoked using the type name.
Static methods are not as powerful as instance methods. In particular, static
methods can only access the static parts of their type and are not allowed to
access any instance fields or methods. This limitation means static methods
are not quite as useful as instance methods; however, static methods do still
have their place. Static methods are typically used for 'utility' methods
that do not need to maintain state across calls. Several good examples of this
application can be seen in the
This material is excerpted from the Programming C# course offered by DevelopMentor. |