Understanding static classes and static members and sealed classes in C programming

  • 2021-09-05 00:41:09
  • OfStack

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 use the class name itself to access the members of the static class. For example, if a static class named UtilityClass has a public method named MethodA, call the method as shown in the following example:


UtilityClass.MethodA();

Static classes can easily be used as containers for method sets that operate only on input parameters without getting or setting any internal instance fields. For example, in the. NET Framework class library, the static class System. Math contains methods that perform only mathematical operations without storing or retrieving data specific to a particular Math class instance. That is, class members are applied by specifying class names and method names, as described in the following example.


double dub = -3.14;
Console.WriteLine(Math.Abs(dub));
Console.WriteLine(Math.Floor(dub));
Console.WriteLine(Math.Round(Math.Abs(dub)));

Output:


3.14
-4
 3


As with all class types 1, when a program that references a static class is loaded, the. NET Framework common language runtime (CLR) loads the type information for that static class. The program cannot specify an exact time to load a static class. However, you are guaranteed to load the class before it is first referenced in your program, initialize its fields and call its static constructor. The static constructor is called only once, and the static class 1 remains in memory for the lifetime of the application domain in which the program resides.

Main features of static classes:

Contains only static members. Unable to instantiate. It's sealed. Cannot contain instance constructors.


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

The following is an example of a static class that contains two methods that convert back and forth between Celsius and Fahrenheit:


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 TestTemperatureConverter
{
 static void Main()
 {
  Console.WriteLine("Please select the convertor direction");
  Console.WriteLine("1. From Celsius to Fahrenheit.");
  Console.WriteLine("2. From Fahrenheit to Celsius.");
  Console.Write(":");

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

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

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

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

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

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 member
Non-static classes can contain static methods, fields, properties, or events. Static members of a class can be called even if no instance of the class is created. Static members are always accessed by class name instead of instance name. No matter how many instances of a class are created, its static members have only one copy. Static methods and properties cannot access non-static fields and events in their containing 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 1 static members, rather than declaring the whole class as a static class. Static fields have two common uses: 1 is to record the number of instantiated objects, and 2 is to store values that must be shared across all instances.
Static methods can be overloaded but cannot be overridden because they belong to the class and not to any instance of the class.
Although a field cannot be declared as static const, the behavior of an const field is static in nature. Such a field belongs to a type, not an instance of a type. Therefore, the const field can be accessed using the ClassName. MemberName notation just like the static field 1. Object instances are not required.
C # does not support static local variables (variables declared within the scope of a method).
You can declare a static class member 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...
}

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


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

If the class contains static fields, provide a static constructor that initializes those fields when the class is loaded.
Calls to static methods generate invocation instructions in the Microsoft intermediate language (MSIL), while calls to instance methods generate callvirt instructions, which also check for null object references. However, the performance difference between the two is not obvious most of the time.

Sealed class of C #
Using the sealed keyword prevents inheritance of classes or some class members that were previously marked as virtual.
You can declare a class as a sealed class by placing the keyword sealed before the class definition. For example:


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

Sealed classes cannot be used as base classes. Therefore, it cannot be an abstract class either. Sealed classes prohibit derivation. Because sealed classes are never used as base classes, some runtime optimizations can slightly speed up invocation of sealed class members.
On a derived class that overrides a virtual member of the base class, a method, indexer, property, or event can declare that member as a sealed member. When used in future derived classes, this will cancel the virtual effect of members. This is done by placing the sealed keyword before the override keyword in the class member declaration. For example:


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


Related articles: