Q:

C# program to demonstrate the static constructor

0

C# program to demonstrate the static constructor

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

The source code to demonstrate the static constructor is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate the static constructor

using System;

public class StaticDemo
{
    static StaticDemo()
    {
        Console.WriteLine("Static constructor called");
    }

    public StaticDemo()
    {
        Console.WriteLine("Non-Static constructor called");
    }
}

class Test
{
    static void Main(string[] args)
    {
        Console.WriteLine("Main() method called");

        StaticDemo S1 = new StaticDemo();
        StaticDemo S2 = new StaticDemo();
    }
}

Output:

Main() method called
Static constructor called
Non-Static constructor called
Non-Static constructor called
Press any key to continue . . .

Explanation:

In the above program, we created two classes StaticDemo and Test. The StaicDemo class contains a static and non-static constructor. The static constructor is always called before the first object of the class gets created.

Now look to the Test class that contains the Main() method. The Main() method is the entry point for the program. Here, we printed a message "Main() method called" on the console screen. Then we created the two objects then a static construct gets called after then non-static constructor called for both objects.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | Class, Object, Methods

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to demonstrate the structure... >>
<< C# program to get the count of total created objec...