Static Constructor in C#

王林
Release: 2024-09-03 15:12:52
Original
505 people have browsed it

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
}
}
Copy after login

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 ();
}
}
}
Copy after login

Output:

Static Constructor in C#

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();
}
}
}
Copy after login

Output:

Static Constructor in C#

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!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!