Static Classes and Static Class Members in C#

Static classes – what are they?

In C#, static classes have one important difference to that of non-static classes: they cannot be instantiated. That is, the new operator cannot be used to create an instance of the class type. Since no instance of a static class can exist, its members can only be accessed using the class name itself.

An example is the static System.Math class contained in the .NET Framework Class Library, which does not need to store or retrieve data for particular particular instances of the Math class.

The following console application example is taken from the Microsoft MSDN site, illustrates how the static class is used:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    public static class TemperatureConverter
    {
        public static double CelsiusToFahrenheit(string temperatureCelsius)
        {
            // Convert argument to double for calculations.  
            double celsius = 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 = Double.Parse(temperatureFahrenheit);

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

            return celsius;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            double F = TemperatureConverter.CelsiusToFahrenheit("100.0");
            string valueString = "100 degrees celcius = ";
            // convert double to string
            string txtFaren = Convert.ToString(F);           
            Console.WriteLine(valueString + txtFaren + " degrees Fahrenheit");
            Console.ReadKey(true);
        }
    }
} 

Static Members

A non-static C# class can contain static methods, fields, properties, or events. The static member would be callable on a class even when no instance of the class has been created. The static member is always accessed by using the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.

Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

It is more typical to declare a non-static class with some static members, than to declare an entire class as static. Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.

Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.

Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object instance is required.

C# does not support static local variables (variables that are declared in method scope).

You declare static class members by using the static keyword before the return type of the member, as shown in the following Microsoft MSDN 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...
}

Example usage given here:

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

Non-static classes

The following example shows the example usage of a non-static class within the main function for the console application. Merely calling the CelsiusToFahrenheit function will result in an error message resembling the following:

Error 1 An object reference is required for the non-static field, method, or property 'ConsoleApplication.TemperatureConverter.CelsiusToFahrenheit(string)' C:\Users\andrew\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 38 24

For accessing member functions inside non-static classes we must always create an instance of that class, as shown in the following code sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

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

            return fahrenheit;
        }

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

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

            return celsius;
        }
    }

    class Program
    {       
        static void Main(string[] args)
        {
            TemperatureConverter tc = new TemperatureConverter();
            double F = tc.CelsiusToFahrenheit("100.0");

            string valueString = "100 degrees celcius = ";
            // convert double to string
            string txtFaren = Convert.ToString(F);           
            Console.WriteLine(valueString + txtFaren + " degrees Fahrenheit");
            Console.ReadKey(true);
        }
    }
}
`