Static Classes in C#

By | May 21, 2014

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

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.

The main features of a static class are:

  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors

Example of a Static Class:

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;
}
}
}

Leave a Reply