Static Constructor in C#
Static constructors in C# are constructors implemented to be invoked only once and only during the creation of the reference for a static member implemented in the class. The primary function for a static constructor is to initialize the static members for the class and only once execution. The static constructor as the name suggests does not allow explicit control to the user but is executed automatically upon the invoke of the instance of the class, Further, the static constructor doesn’t take any parameter or access declaration in its definition, thus it can’t be called directly. Static constructors cannot be inherited or overloaded and only accessible to the CLR (Common Language Runtime).
Features and Uses of Static Constructors in C#
Following are some features and uses of static constructors in c# explained in details:
Features for Static Constructor
The following features describe the static constructor:
- The user does not have any control over the static constructor on runtime. These are predefined in the code before precompiling and the value remains fixed for the entire duration.
- The static constructor operation can be further broken down into two stages i.e. static data members initializing and static action execution which occurs in the sequential order as defined.
- A static method does not have any access modifier in its definitions and hence cannot be called upon by other components in the program.
Uses for Static Constructor
Static constructors find its major use in log programs where it is used to write the parameter entries initialized during each instance. Static constructors are the ideal positions to create database connections as they are loaded first and remain static throughout. In C# programming language the static constructors following the following Syntax.
Syntax:
class ABC { //defining the static constructor using the same name as class static ABC() { //constructor specific code comes here } }
How Static Constructors Work in C#?
Here are some basic working principle of static constructor in C# which are as follows:
- When a class or an object of the class is created as a struct, constructors are called upon to create the data members associated with the class. These constructors have the same name as the class.
- In order to understand the concept of static constructors, we would first need to understand the concept behind static methods and classes.
- A static class is differentiated from a regular class due to the fact that the static class cannot be instantiated i.e. the new keyword cannot be used for creating the new instance of the class.
- Hence the class cannot be accessed using the new instance and needs to be called upon by the static class name itself. These classes are used to work upon the input fields and operated to create an initial and fixed value of the input parameters.
- A static constructor as the name suggest is used to set up or initialize any static data required at the pre-rendered stages of the class construct. The static constructor is called upon before the first instance of the class is created or the reference is looked upon for any static members.
- Thus one can define static constructors as the first instance of the class that is created in run time, also this is a single occurrence event and is not repeated again.
Examples to Implement Static Constructors
Here are some of the examples of static constructor in C# which are given below:
Example #1
Code:
using System; namespace HappyConstructor { class Happy { //let us declare and initialise the static data members private static int id = 7; public static int Id { get { return id; } } public static void printVariable() { Console.WriteLine("Happy.id = " + id); } static void Main(string[] args) { //let us print the value of ID from the class Happy. printVariable (); } } }
Output:
Explanation: In the above, the static member id is declared for use and initialized to the initial value of 10.
Example #2
Code:
using System; namespace Happy1Constructor { class Happy1 { private static int Id; //data member (id) is set conditionally here to show actions of a Static constructor static Happy1 () { if (Happy1.Id < 10) { Id = 25; } else { Id = 1000; } Console.WriteLine("Static Constructor for Class Happy Called.."); } public static void print() { Console.WriteLine("Happy1.Id = " + Id); } public static void Main(string[] args) { // the value of Id is displayed as Happy1.print(); } } }
Output:
Explanation: In the example above the constructor is conditionally dependent upon the Happy.cs file generated in example1. Here the static constructor initializes itself. since the value is in the first case the Id field generated is 7 and as per the conditional operator if the value of the field is less than 10 then the value for the Id field for the Happy1 constructor shall be 25. This is a classic example of initializing a static constructor upon the first instance of loading of the class. The static constructor makes use of this feature to preload the input parameters for the program referencing.
Conclusion
A static constructor is used to initialize any static data and or in performance of any particular actions that need to be performed once and only once for the program. This constructor is called upon before any of the objects of the class is initiated or any of the members are loaded on to the run time environment.
The above is the detailed content of Static Constructor in C#. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.
