OOPS Concept - Static class and static constructor

This post is about refreshing couple of basis rules/points in respect of OOPS. Considering C# as one of the languages which support OOPS, following points has been described.

Let's start wih the concept.

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. You need to call class.method directly like Math.Abs() or Math.Floor().

Creating a static class is basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

Non-Static Class, Static field and constructure, usage like singleton and below:
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  • Static constructors are also a convenient place to enforce run-time checks on the type parameter that cannot be checked at compile time via type-parameter constraints.

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed only once. It is called automatically before the first instance is created or any static members are referenced.

    public class MyFactoryBase

    {

        static MyFactoryBase()

        {

            Console.WriteLine("Static constructor of MyFactoryBase");

        }

        public virtual void WriteLogmessages()

        { Console.WriteLine("Base method MyFactoryBase"); }

    }


Below are some important points:

  • A static constructor doesn't take access modifiers or have parameters.
  • A class or struct can only have one static constructor.
  • Static constructors cannot be inherited or overloaded.
  • A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.
  • The user has no control on when the static constructor is executed in the program.
  • A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced. A static constructor runs before an instance constructor. 
  • If you don't provide a static constructor to initialize static fields, all static fields are initialized to their default value.
  • If a static constructor throws an exception, the runtime doesn't invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain. Most commonly, a TypeInitializationException exception is thrown when a static constructor is unable to instantiate a type or for an unhandled exception occurring within a static constructor.
  • The runtime calls a static constructor no more than once in a single application domain. That call is made in a locked region based on the specific type of the class. 
A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.

Main features of a static class:
  • Contains only static members.
  • Cannot be instantiated.
  • Is sealed.
  • Cannot contain Instance Constructors.

Creating a static class is therefore basically 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:
  • 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. They cannot inherit from any class or interface except Object. However, they can contain a static constructor.

Now, considering private constructore which prevents to instance a class. Let's see how it is being used in Sealed class. One thing to remember, you cannot inherit a Sealed class, but Sealed class can inherit other class.

//Singleton class example with private constructor
//Sealed class can inherit a base class
public sealed class getDBConnOpen : MyFactoryBase
{
    private static getDBConnOpen? _Instances;
    private getDBConnOpen() {
        Console.WriteLine("Trying to call WriteLogMessage from Sealed calss inherit from MyFactoryBase");
        WriteLogmessages();
    }

    public static getDBConnOpen GetInstance() 
    { 
        if( _Instances == null ) 
        {
            _Instances = new getDBConnOpen();
        }
        return _Instances;
    }

    public void setAddOperation() { }
}

Source: Micrsoft

Comments

Popular posts from this blog

How to fix Azure DevOps error MSB4126

SharePoint Admin Center

How to create Custom Visuals in Power BI – Initial few Steps