Static Classes and Static Class Members
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated.
In other words, you cannot use the new keyword to create a variable of the class type.
Because there is no instance variable, you access the members of a static class by using the class name itself.
For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example:
UtilityClass.MethodA();
A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields.
For example, in the .NET Framework Class Library, the static System.Math class contains methods that perform mathematical operations, without any requirement to store or retrieve data that is unique to a particular instance of the Math class.
That is, you apply the members of the class by specifying the class name and the method name, as shown in the following example.
double dub = -3.14;
Console.WriteLine(Math.Abs(dub));
Console.WriteLine(Math.Floor(dub));
Console.WriteLine(Math.Round(Math.Abs(dub)));
// Output:
// 3.14
// -4
// 3
As is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded.
The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program.
A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.
To create a non-static class that allows only one instance of itself to be created, see Implementing Singleton in C#.
The following list provides the main features of a static class:
Contains only static members.
Cannot be instantiated.
Is sealed.
Cannot contain Instance Constructors.
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor.
A private constructor prevents the class from being instantiated.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added.
The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object.
Static classes cannot contain an instance constructor; however, they can contain a static constructor.
Non-static classes should also define a static constructor if the class contains static members that require non-trivial initialization.
For more information, see Static Constructors (C# Programming Guide).