Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C# Program to Demonstrate the Static Constructor in Structure

  • Last Updated : 25 Nov, 2021

A Structure is a well-defined data structure that can hold elements of multiple data types. It is similar to a class because both are user-defined data types and both contain a bunch of different data types. You can also use pre-defined data types. However, sometimes the user might be in need to define its own data types which are also known as User-Defined Data Types. A structure can also hold constructors, constants, fields, methods, properties, and indexers, etc. We can create a structure by using the struct keyword followed by the name of the structure.

Syntax:

public struct structure_name

{

    // Body of the structure

}

A Static constructor is a type of constructor that is called before the first instance of the structure or class gets created. It is initialized with static fields or data of the structure and is to be executed only once. We can create a static constructor by using static keyword and followed by constructor name.

Syntax:

static class()

{

    // Body of the static constructor 

}

Given a structure, now our task is to use a static constructor in the given structure. So to this, we have to follow the following approach.

Approach

  • Create a structure named GFG.
  • Create a static constructore with no parameters inside the structure.
public struct class
{
    static class()
    {
        // Constructor body
    }
}
  • Create a non-static method named GFG by passing an integer parameter to it.
  • Assign the variable to call the non static constructor in a separate method inside the structure.
  • In the main method, create an object for the structure and access the both static and non static methods by creating the object.

Example:

C#




// C# program to illustrate how to use the 
// static constructor in the structure
using System;
  
// Create a structure
public struct GFG
{
      
    // Static method names GFG
    static GFG()
    {
        Console.WriteLine("Hello! Static constructor is called");
    }
  
    // Non static method
    public GFG(int variable)
    {
        Console.WriteLine("Hello! Non-Static constructor is called");
    }
}
  
// Driver code
class Geeks{
      
static void Main(string[] args)
{
      
    // Create the object for 
    // the structure 
    GFG obj = new GFG(2);
}
}

Output:

Hello ! Static constructor is  called
Non-Static constructor is called


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!