Skip to main content

C#: Static Class and Static Constructor and their usages in C#

Static Class:
A class can be static, and it can have static members, both functions and fields. Static class can be created with the static keyword. Following are some important points about static class:

·         A static class is a class whose members must be accessed without an instance of the class. In other words, the members of a static class must be accessed directly from (using the name of) the class.
·         A static class can only have a static constructor and public/private does not apply since your code can never call this constructor (the CLR does).
·         You cannot create a new instance of static class using a constructor. The static keyword on a class enforces that a type not be created with a constructor.
·         By eliminating the constructor or the ability to create variables of a type, we introduce global variables and single-instance fields.
·         All members (except for constants) of static class must be declared as static. You cannot declare a non-static member in a static class.
·         In the static class, we access members directly on the type. This eliminates misuse of the class.
·         If you create a class marked as static, you cannot derive a class from it (i.e. it is work as sealed).
·         With the help of static class you can achieve information hiding. You can use regular classes and static classes in the same way, but the static modifier imposes an extra restriction. The constructor is eliminated.
·         With static classes, we can enforce coding standards and expectations with a minimum of effort.

Example of static class:

public static class Rectangle
{
    public static int width;
    public static int height;
    public static int GetArea()
    {
        return width * height;
    }
}

Let’s now use our static class:

public class TestStatic
{
    public static void Main()
    {
        Rectangle.width = 20;
        Rectangle.height = 35;
        Console.WriteLine("Rectangle Details:");
        Console.Write("Width: " + Rectangle.width);
        Console.Write("Height: " + Rectangle.height);
        Console.Write("Rectangle Area:");

        //Call 'GetArea' method of with class name
        //(i.e. no need of object)
        Console.WriteLine(Rectangle.GetArea());
    }
}

Static Constructor:

Like a class member or normal method, a constructor can also be made static. A static constructor in C# is a chunk of code that is executed just after all the static variables for a class is initialized. There are rules you must follow. If you want to use a static constructor, you must explicitly create it (the compiler doesn't create a static constructor for you).

In C# we have two types of constructor:
·         A class constructor (static constructor) and
·         An instance constructor (non-static constructor).

Why we use static constructor:
Whenever anyone thinks about static constructor, there is a question comes in mind why we need to use static constructor though we have static data members those can certainly be initialized at the time of their declaration. But there are times when value of one static member may depend upon the value of another static member. In such cases we definitely need some mechanism to handle conditional initialization of static members. To handle such situation, C# provides concept of static constructor.

·         One of the reasons for using a static constructor is to initialize the static fields of the class or take any action that would be shared by all instances of the class.
·         Another reason to use a static constructor is to initialize the static member variables.

Example of static constructor:

public class TestStatic
{
    public static int val;
    static TestStatic()
    {
        val = 5;
    }
}

Some important point regarding static constructor are:

·         Since static constructor is a class constructor, they are guaranteed to be called as soon as we refer to that class or by creating an instance of that class.
·         The static constructor does not have parameters and must become the default constructor. That is, you must create a constructor that doesn't take any argument.
·         A static constructor does not take access modifiers and can't access any non-static data member of a class.
·         It can only access the static member(s) of the class.
·         Only one static constructor is allowed per class (i.e. no constructor overloading).
·         Static constructor is used to initialize static data members as soon as the class is referenced first time, whereas an instance constructor is used to create an instance of that class with new keyword.
·         A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
·         A static constructor cannot be called directly.
·         The user has no control on when the static constructor is executed in the program.
·         The static constructor executes before any instance of the class is created or any of the static members for the class are referenced.
·         The static constructor for a class executes at most one time during a single program instantiation
·         A static constructor is a handy place to initialize that database connection, because it means that the connection will get created right before it is first needed.


Comments

Popular posts from this blog

C#: Merging Excel cells with NPOI HSSFWorkbook

In this post we’ll see how to merge the two or more cell with each other while creating the excel sheet using NPOI . Mentioned below is code to merge multiple cells, in this example we are merging first cell to fifth cell of first row (you can adjust row or cell range by passing particular parameters in CellRangeAddress). //Created new Workbook var hwb = new NPOI.HSSF.UserModel. HSSFWorkbook (); //Create worksheet with name. var sheet = hwb.CreateSheet( "new sheet" ); //Create row and cell. var row = sheet.CreateRow(0); var cell = row.CreateCell(0); ; //Set text inside cell cell.SetCellValue( "This is Merged cell" ); cell.CellStyle.WrapText = true ; //define cell range address // parameters: -> first row to last and first cell to last cell var cra = new NPOI.SS.Util. CellRangeAddress (0, 0, 0, 4); //Add merged region to sheet. sheet.AddMergedRegion(cra); Hope this solution helps you J

Error 405 : ASP.NET Core Web API PUT and DELETE Methods not allowed

Recently, while working with .Net core API I came across the issue of “Error 405 — Methods not Allowed” After some research, I found out that both GET and POST requests working fine but neither PUT nor DELETE requests working. Another thing is that the PUT and DELETE request was also working fine on my local machine but failed when we host on our Azure server. When I explored the issue on the web it led me to the conclusion that WebDAVModule seems to set PUT and DELETE request methods disabled by default and due to that PUT and DELETE throw 405 errors. To make the PUT and DELETE requests work, we need to override the WebDAVModule setting in web.config file by adding the below settings under “ system.webServer ”. < system.webServer >   < modules runAllManagedModulesForAllRequests = " false " >     < remove name = " WebDAVModule " />   </ modules > </ system.webServer > There may be 2 web.config files in y...

How to set Swagger as the default start page for API hosted on the Azure web app?

I created an Asp.Net Core 2.x Web API and configured Swagger on it, below is the code added in Configure method under Startup.cs file, for full swagger configuration, check here //Add swagger configuration app.UseSwagger(); app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" ); }); On my local machine when I run the API it is automatically redirected to the Swagger page. However, when I hosted this API as an Azure web app it is not redirecting directly to the Swagger and to access the swagger, I had to append /swagger in the URL, for example, https://testapi.azurewebsites.net/swagger/ Solution: Set RoutePrefix to string.Empty under app.UseSwaggerUI like below: app.UseSwaggerUI(c => {     c.SwaggerEndpoint( "../swagger/v1/swagger.json" , "Test API V1" );      c.RoutePrefix = string .Empty; // Set Swagger UI at apps root }); And that’s it, now when you b...