Static constructor and C# implementation

less than 1 minute read

Static Constructor

  • Instance constructors are used to initialize an object
  • Static constructors are used to initialize a class
  • Will only ever be executed once
  • Run before the first object of that type is created.
  • Have no parameter
  • Do not take an access modifier
  • May co-exist with a class constructor

Syntax:

class Lion
{
    static Lion()
    {
        // class-specific initialization
    }
}

Example:

class RandomNumberGenerator
{
    private static Random randomNumber;
    public static string AuthorName { get; set; }

    public RandomNumberGenerator(String msg)
    {
        Console.WriteLine(msg);
        //Constructor for object
    }

    //Static constructor
    static RandomNumberGenerator()
    {
        AuthorName = "Mahedee Hasan";
        randomNumber = new Random();
    }

    public int Next()
    {
        return randomNumber.Next();
    }
}

class Program
{
    static void Main(string[] args)
    {
        RandomNumberGenerator randomNumber
        = new RandomNumberGenerator("Generate 10 Random Number");

        for (int i = 0; i < 10; i++) 
        { 
            Console.WriteLine(randomNumber.Next()); 
        } 

        Console.WriteLine("Author Name: " + RandomNumberGenerator.AuthorName); 
        Console.ReadKey(); 
    } 
} 

Tags:

Categories:

Updated: