C# Static Class
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.
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.
Example
To start, 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.Constructor
And:
Inside the Perl class, we 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 Bool
Discussion
Conceptually, a static class is a form of information hiding.
You can use regular classes and static classes in the same way,
but the static modifier imposes an extra restriction.
The constructor is eliminated.
So:
You can think of a static class as a regular class with its constructor eliminated.
Summary
With static classes, we can enforce coding standards and expectations with a minimum
of effort.
By eliminating the constructor or the ability
to create variables of a type, we introduce global variables and single-instance fields.