BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 2.0+

C# Static Classes

C# version 2.0 provides a new facility that permits the creation of static classes. These classes cannot be instantiated and so may only contain static members. These members can then be used without the requirement to create an object beforehand.

What is a Static Class?

Sometimes you will want to create a class that contains only static members and that cannot be instantiated. This is often the case when creating utility classes, or as an alternative to using the singleton design pattern. When using the .NET framework version 1.1, this is achieved by decorating every member declaration in the class with the "static" modifier and by including only private constructors.

In C# version 2.0, Microsoft introduced static classes to provide this behaviour using simpler code. A static class is simply a class whose definition is decorated with the "static" modifier. Once declared in this manner, the class may only contain static members. If any of the class's members is not declared as static, the compiler will report an error.

Static classes provide some benefits over standard classes. Firstly, the compiler ensures that no instance members are added accidentally. Secondly, the program can have improved performance because the overhead of creating objects is removed. However, static classes should be used with care, as they can be more difficult to mock for automated testing purposes.

A good example of the use of static classes is the Math class in the System namespace. In .NET 1.1, this was a sealed class with no public constructor. In .NET 2.0, this has been modified and is now a static class.

Creating a Static Class

To create a static class, the definition is prefixed with the "static" keyword. In the following example, the class holds a single system setting for an application. This setting holds the maximum number of files that can be used by the program and is controlled by a static property. The property is initialised in the static constructor.

public static class SystemSettings
{
    static int _maximumFiles;

    public static int MaximumFiles
    {
        get { return _maximumFiles; }
        set { _maximumFiles = value; }
    }

    static SystemSettings()
    {
        _maximumFiles = 20;
    }
}

The members of the static class can be called without first creating an object. Instead, the name of the member is prefixed with the class name and a full stop (period), as can be demonstrated using the following code:

int maxFiles = SystemSettings.MaximumFiles;
Console.WriteLine("File limit = {0}", maxFiles);    // Outputs "File limit = 20"
22 November 2008