C# program to demonstrate the static constructor in the structure

Here, we are going to demonstrate the static constructor in the structure in C#.
Submitted by Nidhi, on November 08, 2020

Here, we will create a structure with the static and non-static constructor. The static constructor is called before the first instance of the structure gets created. We cannot create a parameter less non-static constructor in a structure.

Program:

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

//C# program to demonstrate the 
//static constructor in the structure

using System;
public struct StructDemo
{
    static StructDemo()
    {
        Console.WriteLine("Static constructor called");
    }

    public StructDemo(int dummy)
    {
        Console.WriteLine("Non-Static constructor called");
    }
}

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

        StructDemo S1 = new StructDemo(1);
        StructDemo S2 = new StructDemo(2);
    }
}

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 a structure StructDemo and a class Test. The StructDemo structure contains a static and non-static constructor. The static constructor is always called before the first instance of the structure 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 instances then a static construct gets called after then non-static constructor called for both instances.





Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.