Sunday, May 9, 2021

Static constructor in c#

In this article i will explain what static constructor in c# and what is use of the static constructor in c#.

 The static constructor creating by use of the static keyword in c# class. static constructor invoked only once for all of the instances of the class and it is invoked during the creation of first instance of the class or the first reference to the static member in the class. A static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.  

Key points of the static constructor  : 

  • Static constructor does not have access modifier or have parameter.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • Static constructor can not we called directly.
  • The use has no control over when static constructor is executed in the program.
  • 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

 The following example is the use static constructor:


using System;
                    
public class Program
{
    public static void Main()
    {
        Circle c1=new Circle(5);
        Console.WriteLine("Area of circle is {0}",c1.CalculateArea());
    }
}
public class Circle
    {
        static float _PI;
        int _Radius;
        static Circle()
        {
            Circle._PI = 3.14f;
        }
        public Circle(int radius)
        {
            this._Radius = radius;
        }
        public float CalculateArea()
        {
            return Circle._PI * this._Radius * this._Radius;
        }
    }
 
Output : 
 
Area of circle is 78.5 

No comments:

Post a Comment

Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...