SoFunction
Updated on 2025-03-07

Understand static classes and static members and sealed classes in C# programming

Static class
Static classes are basically the same as non-static classes, but there is one difference: static classes cannot be instantiated. That is, you cannot use the new keyword to create variables of static class type. Because there are no instance variables, you need to use the class name itself to access members of the static class. For example, if a static class named UtilityClass has a public method named MethodA, the method is called as shown in the following example:

();

For method sets that only perform operations on input parameters without fetching or setting up any internal instance fields, static classes can be conveniently used as containers for these method sets. For example, in the .NET Framework class library, static classes contain methods that perform mathematical operations only without storing or retrieving data specific to a specific Math class instance. That is, apply class members by specifying class names and method names, as described in the following example.

double dub = -3.14;
((dub));
((dub));
(((dub)));

Output:

3.14
-4
 3


Like all class types, when a program that references a static class is loaded, the .NET Framework Common Language Runtime (CLR) loads the type information for the static class. The program cannot specify the exact time when the static class is loaded. However, it is guaranteed that the class is loaded before the first reference in the program, and the fields of the class are initialized and its static constructor is called. The static constructor is called only once, and the static class remains in memory for the lifetime of the application domain where the program resides.

The main features of static classes:

  • Contains only static members.
  • Unable to instantiate.
  • It is sealed.
  • Cannot include instance constructors.


Therefore, creating a static class is basically the same as creating a class that only contains static members and private constructors. The private constructor prevents the class from being instantiated. The advantage of using static classes is that the compiler can perform checks to ensure that instance members are not added accidentally. The compiler will ensure that no instances of such a class will be created.
Static classes are sealed and therefore cannot be inherited. They cannot be inherited from any class except Object. A static class cannot contain instance constructors, but can contain static constructors. If a non-static class contains static members that require important initialization, a static constructor should also be defined.

Here is an example of a static class that contains two methods to perform a round-trip conversion between Celsius and Fahrenheit:

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

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

  return celsius;
 }
}

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

  string selection = ();
  double F, C = 0;

  switch (selection)
  {
   case "1":
    ("Please enter the Celsius temperature: ");
    F = (());
    ("Temperature in Fahrenheit: {0:F2}", F);
    break;

   case "2":
    ("Please enter the Fahrenheit temperature: ");
    C = (());
    ("Temperature in Celsius: {0:F2}", C);
    break;

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

  // Keep the console window open in debug mode.
  ("Press any key to exit.");
  ();
 }
}

Output:

 Please select the convertor direction
 1. From Celsius to Fahrenheit.
 2. From Fahrenheit to Celsius.
 :2
 Please enter the Fahrenheit temperature: 20
 Temperature in Celsius: -6.67
 Press any key to exit.

Static members
A non-static class can contain static methods, fields, properties, or events. Even if no instance of the class is created, a static member in that class can be called. Always access static members by class name instead of instance name. No matter how many instances are created for a class, its static members have only one copy. Static methods and properties cannot access non-static fields and events in their containment types, and cannot access instance variables of any object (unless explicitly passed in method parameters).
It is more common to declare a non-static class with some static members instead of declaring the entire class as a static class. There are two common uses of static fields: one is to record the number of instantiated objects, and the other is to store values ​​that must be shared between all instances.
Static methods can be overloaded but cannot be overwritten because they belong to a class, not to any instance of the class.
Although fields cannot be declared as static const, the behavior of const fields is essentially static. Such fields belong to types, not to instances of types. Therefore, the const field can be accessed using notation as with static fields. No object instance is required.
C# does not support static local variables (variables declared within the scope of the method).
Static class members can be declared by using the static keyword before the member's return type, as shown in the following 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...
}

A static member is initialized before the first time is accessed and before the static constructor (if any) is called. To access a static class member, you should use the class name instead of the variable name to specify the location of the member, as shown in the following example:

();
int i = ;

If the class contains static fields, provide a static constructor that initializes these fields when loading the class.
Calls to static methods generate call instructions in Microsoft Intermediate Language (MSIL), while calls to instance methods generate callvirt directives that also check null object references. However, the performance difference between the two is not obvious most of the time.

Sealing class of C#
Use the sealed keyword to prevent inheritance of classes previously marked virtual or some class members.
The class can be declared as a sealed class by placing the keyword sealed before the class definition. For example:

public sealed class D
{
 // Class members here.
}

Sealing classes cannot be used as base classes. Therefore, it cannot be an abstract class, either. Seal classes are prohibited from derivation. Since seal classes are never used as base classes, some runtime optimizations can slightly increase the call speed of seal class members.
On derived classes that override virtual members of a base class, a method, indexer, property, or event can declare that member as a sealed member. This will cancel the virtual effect of the member when used in later derived classes. The method is to put the sealed keyword in the class member declaration before the override keyword. For example:

public class D : C
{
 public sealed override void DoWork() { }
}