C# Static Modifier

Static illustration

Static things are unmoving. They do not change locations. The C# language introduces the static modifier to capture this: it denotes fields, methods, and types that are not part of any instance. More than one static member cannot be created in memory at once.

A static field identifies exactly one storage location to be shared by all instances of a given closed class type. Hejlsberg et al., p. 434

Example

Note

As an introduction, this program shows a static class, a static field, and also a static method. The Main method is a special case of a static method because it is invoked as the entry point when the program begins execution. You can see that the static field is incremented and displayed.

Program that uses static keyword [C#]

using System;

static class Perls
{
    public static int _value = 5;
}

class Program
{
    static void Main()
    {
	Console.WriteLine(++Perls._value);
    }
}

Output

6
Square abstract illustration

More on static classes. One feature available in the C# language is the static class: this denotes a class that can never be instantiated. All members in this type must also be static.

Static Class

Static constructors. Static constructors enable you to initialize data at some point before it is required. They usually run right before the type is accessed. We describe the usage of static constructors.

Static Constructor

Static modifier. You can make many different members and types static. This is often a useful technique for sharing the member among many uses.

Static Method Static Field Static Property Static Regex Static String

Singleton

1

The singleton design pattern is one of the most popular ones. This gives you an object that can only be instantiated ones; the implementation uses a private constructor. Singletons can still be used as object instances, unlike static classes.

Singleton Singleton Pattern Versus Static Class

Const

Const keyword

The const modifier in the C# language gives you the ability to specify that a variable will never change. When you use const, you cannot reassign the variable, and it is substituted directly as needed by the compiler.

Const Example

Instructions

.NET Framework information

Continuing on, we understand static fields in great detail if we look at the intermediate language. This also gives us a good idea of how static modifiers can affect performance.

stsfld ldsfld ldc

Summary

The C# programming language

Static members introduce extra complexities into certain programs. It is possible for the values of static fields to become invalid and hard to track. In these situations, class instances provide a superior approach.

Class
.NET