C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
A static thing stands alone. It occupies just one location. The static modifier is used on methods, classes, constructors.
A keyword. Static denotes things that are singular. They are part of no instance. Static often improves performance, but makes programs less flexible.
An intro. This program shows a static class, field and method. It shows the syntax. Main() is a special case of a static method. It is invoked as the entry point: control flow starts here.
Field: In this program, we see that the static field (an int) is increment and displayed.
Class: In a static class, all fields and methods must also be static. This is a useful restriction.
Based on: .NET 4.5 C# program that uses static keyword using System; static class Perls { public static int _value = 5; } class Program { static void Main() { Console.WriteLine(++Perls._value); } } Output 6
Static methods. These are called with the type name. No instance is required—this makes them slightly faster. Static methods can be public or private.
Info: Static methods use the static keyword, usually as the first keyword or the second keyword after public.
Warning: A static method cannot access non-static class level members. It has no "this" pointer.
Instance: An instance method can access those members, but must be called through an instantiated object. This adds indirection.
C# program that uses instance and static methods using System; class Program { static void MethodA() { Console.WriteLine("Static method"); } void MethodB() { Console.WriteLine("Instance method"); } static char MethodC() { Console.WriteLine("Static method"); return 'C'; } char MethodD() { Console.WriteLine("Instance method"); return 'D'; } static void Main() { // // Call the two static methods on the Program type. // Program.MethodA(); Console.WriteLine(Program.MethodC()); // // Create a new Program instance and call the two instance methods. // Program programInstance = new Program(); programInstance.MethodB(); Console.WriteLine(programInstance.MethodD()); } } Output Static method Static method C Instance method Instance method D
Public, private. Utility (helper) classes often contain public static methods. This results in no performance loss. These methods are available throughout a program.
Internal: We use the internal keyword to describe a method that must only be called in the same assembly as the method implementation.
Private: Static methods are by default private. These are useful as internal logic repositories for the class state.
Performance, static methods. Static methods have a performance advantage. They are normally faster to invoke on the call stack than instance methods.
Important: Instance methods actually use the "this" instance pointer as the first parameter. They will always have that overhead.
Callvirt: Instance methods are also implemented with the callvirt instruction, which imposes a slight overhead.
Note: Changing methods to static ones is unlikely to make a huge difference, but it often helps.
Static properties. These are similar to static methods. In the metadata, properties have the word "get_" or "set_" prefixed to their identifiers.
Tip: We use static properties in the same way as static methods. Properties show the same performance levels of methods.
Static fields. Let us describe static fields. Static methods have no way of accessing fields that are instance fields, as instance fields only exist on instances of the type.
However: Instance methods can access static fields. Using the static keyword restricts the available members of the type.
Static class. A static class is never instantiated. The static keyword on a class enforces that a type not be created with a constructor. This eliminates misuse of the class.
Note: A static class cannot have non-static members. All methods, fields and properties in it must also be static.
Program: To start, there are two classes in this program: the Program class, which is not static, and the Perl class, which is static.
And: You cannot create a new instance of Perl using a constructor. Trying to do so results in an error.
Finally: Inside the Perl class, we use static on all fields and methods. Instance members cannot be contained in a static class.
C# program that demonstrates static class using System; class Program { static void Main() { // Cannot declare a variable of type Perl. // This won't blend. // Perl perl = new Perl(); // Program is a regular class so you can create it. Program program = new Program(); // You can call static methods inside a static class. Perl._ok = true; Perl.Blend(); } } static class Perl { // Cannot declare instance members in a static class! // int _test; // This is ok. public static bool _ok; // Can only have static methods in static classes. public static void Blend() { Console.WriteLine("Blended"); } } Output Blended
Notes, static class. Conceptually, a static class is a form of information hiding. The static modifier imposes an extra restriction. The constructor is eliminated.
Static constructor. A static constructor initializes static fields. It runs at an indeterminate time before those fields are used. Static constructors on a type impose some overhead.
Note: A static constructor is sometimes called a type initializer. It initializes fields before accesses.
Note 2: Instances are not the same as types. An instance is a specific object of the type.
Example: Let us consider two classes. The first one has a static constructor: it initializes its field to 1.
And: The second class has no static constructor. In testing, the one with a static constructor has slower field accesses.
C# program that demonstrates static constructor /// <summary> /// This type has a static constructor. /// </summary> static class HasStaticConstructor { /// <summary> /// Public field. /// </summary> public static int _test; /// <summary> /// Static constructor initializes public field. /// </summary> static HasStaticConstructor() { _test = 1; } } /// <summary> /// This type has no static constructor. /// </summary> static class NoStaticConstructor { /// <summary> /// Public field initialized inline. /// </summary> public static int _test = 1; } class Program { static void Main() { System.Console.WriteLine(HasStaticConstructor._test); System.Console.WriteLine(NoStaticConstructor._test); } } Output 1 1
Benchmark, static constructor. We consider next the performance of the two classes. I wrote a test program (not shown) that uses each class.
Note: In the program, the value 2 is stored in the _test field in each iteration.
Result: Static constructors cause a slowdown of all accesses to the type. This is small in absolute terms, but can add up in a program.
Benchmark results HasStaticConstructor: 2.89 ns NoStaticConstructor: 0.32 ns
Benchmark, continued. Static constructors are sometimes not slower. It is possible to have code that accesses a field in a class with a static constructor, with no performance penalty.
And: This seems to depend on how early in the program the field is first accessed.
Thus: It is best to avoid static constructors for maximum performance. Bogdan Potor wrote in with a benchmark.
Lazy. It is sometimes appropriate to use a lazy instantiation pattern. Check a field for null when needed, and initialize it lazily. The Lazy type is useful.
Examples. We can make many members and types static. This is often a useful technique for sharing the member among many uses. We consider arrays, Regex and strings.
Static ArrayStatic RegexStatic String
Readonly: The C# specification recommends using "public static readonly" variables for constants that must initialized at runtime.
Const. This specifies that a variable will never change. When we use const, we cannot reassign the variable. It is substituted directly as needed by the compiler.
Singleton. This design pattern gives us an object that can only be instantiated once. The implementation uses a private constructor. Singletons are object instances, unlike static classes.
Instructions. We understand static fields if we look at the IL instructions. This also gives us a good idea of how static modifiers affect performance. Often "static" enhances performance.
IL: The C# language (and VB.NET) are compiled into an intermediate form called (fittingly) intermediate language.
Research. The concept of "statics" is core to many languages. In C# we cannot use static to describe local variables. Static modifies a field's storage location.
A static field identifies exactly one storage location to be shared by all instances of a given closed class type.
Local variables. Static locals are a kind of storage-permanent local variable in the C and C++ languages. This concept does not exist in the C# language.
Note: The static keyword is not valid in the method body. But const can specify a method-local constant definition.
Access routines. The book Code Complete by Steve McConnell outlines strategies to employ global variables in programs without creating maintainability problems over time.
Mainly: The author emphasizes the usage of access routines. In the C# language, you can use static properties as access routines.
A review. We use static methods to access type-based data. With static classes, we handle global variables and single-instance fields. Static constructors initialize data, but may be slow.
Statics introduce complications. It is possible for the values of static fields to become invalid. In these situations, class instances are a better approach.