Static Classes and Static Class Members (C# Programming Guide) 

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.

Static Classes

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

The main features of a static class are:

Creating a static class is therefore much 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. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state. For more information, see Static Constructors (C# Programming Guide).

When to Use Static Classes

Suppose you have a class CompanyInfo that contains the following methods to get information about the company name and address.

class CompanyInfo
{
    public string GetCompanyName() { return "CompanyName"; }
    public string GetCompanyAddress() { return "CompanyAddress"; }
    //...
}

These methods do not need to be attached to a specific instance of the class. Therefore, instead of creating unnecessary instances of this class, you can declare it as a static class, like this:

static class CompanyInfo
{
    public static string GetCompanyName() { return "CompanyName"; }
    public static string GetCompanyAddress() { return "CompanyAddress"; }
    //...
}

Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace.

Static Members

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine.

Static class members are declared using the static keyword before the return type of the member, for example:

public class Automobile
{
    public static int NumberOfWheels = 4;
    public static int SizeOfGasTank
    {
        get
        {
            return 15;
        }
    }
    public static void Drive() { }
    public static event EventType RunOutOfGas;

    //other non-static fields and properties...
}

Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member. For example:

Automobile.Drive();
int i = Automobile.NumberOfWheels;

Example

Here is an example of a static class that contains two methods that convert temperature from Celsius to Fahrenheit and vice versa:

public static class TemperatureConverter
{
    public static double CelsiusToFahrenheit(string temperatureCelsius)
    {
        // Convert argument to double for calculations.
        double celsius = System.Double.Parse(temperatureCelsius);

        // Convert Celsius to Fahrenheit.
        double fahrenheit = (celsius * 9 / 5) + 32;

        return fahrenheit;
    }

    public static double FahrenheitToCelsius(string temperatureFahrenheit)
    {
        // Convert argument to double for calculations.
        double fahrenheit = System.Double.Parse(temperatureFahrenheit);

        // Convert Fahrenheit to Celsius.
        double celsius = (fahrenheit - 32) * 5 / 9;

        return celsius;
    }
}

class TestTemperatureConverter
{
    static void Main()
    {
        System.Console.WriteLine("Please select the convertor direction");
        System.Console.WriteLine("1. From Celsius to Fahrenheit.");
        System.Console.WriteLine("2. From Fahrenheit to Celsius.");
        System.Console.Write(":");

        string selection = System.Console.ReadLine();
        double F, C = 0;

        switch (selection)
        {
            case "1":
                System.Console.Write("Please enter the Celsius temperature: ");
                F = TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());
                System.Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
                break;

            case "2":
                System.Console.Write("Please enter the Fahrenheit temperature: ");
                C = TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine());
                System.Console.WriteLine("Temperature in Celsius: {0:F2}", C);
                break;

            default:
                System.Console.WriteLine("Please select a convertor.");
                break;
        }
    }
}

Input

2

98.6

Sample Output:

Please select the convertor

1. From Celsius to Fahrenheit.

2. From Fahrenheit to Celsius.

:2

Please enter the Fahrenheit temperature: 98.6

Temperature in Celsius: 37.00

Additional sample output might look as follows:

Please select the convertor

1. From Celsius to Fahrenheit.

2. From Fahrenheit to Celsius.

:1

Please enter the Celsius temperature: 37.00

Temperature in Fahrenheit: 98.60

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 25.2 Static Classes

See Also

Reference

class (C# Reference)
Instance Constructors (C# Programming Guide)

Concepts

C# Programming Guide
Classes (C# Programming Guide)