C# Static Class

Static illustration

A static class is never instantiated. The static keyword on a class enforces that a type not be created with a constructor. In the static class, we access members directly on the type. Thus eliminates misuse of the class—and improves code quality.

This C# program uses a static class. This kind of class cannot be instantiated.

Example

Note

To start, we should notice that there are two classes in this program: the Program class, which is not static, and the Perl class, which is static. You cannot create a new instance of Perl using a constructor; trying to do so results in an error. Inside the Perl class, you must use the static modifier on all fields and methods: instance members cannot be contained in a static class.

Program that demonstrates static class [C#]

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

Public static members. The bool _ok and the method Blend() are the public static members on the Perl type. Often, public static members are used in helper classes or utility classes throughout a project.

Public Static Readonly Field Public Method Bool Type

Information hiding

This section provides information

Conceptually, a static class is an example of information hiding. You can use regular classes and static classes in the exact same way, but the static modifier imposes a restriction on how the type can be used. The constructor is eliminated. You can think of a static class as a regular class with its constructor eliminated.

Summary

The C# programming language

With static classes, we can enforce coding standards and expectations with a minimum of effort, as shown in this example. By eliminating the constructor or the ability to create variables of a type, we easily introduce global variables and single-instance fields.

Global Variable Static Modifier
.NET