A static constructor is a method that initializes static data members of a class or executes a specific task that needs to be done only once. This constructor is automatically invoked before the first instance of a class is created, or any static data members are accessed.
In this post, We will learn about the C# static constructor with multiple examples.
Table of Contents
- 1 Characteristics of Static constructor in C#:
- 2 5 Scenarios Where Static Constructors Are Useful in C#
- 3 FAQs
- 3.1 Q: What is static constructor in C#?
- 3.2 Q: Why static constructor is parameterless in C#?
- 3.3 Q: Can we have static and default constructors in C# at the same time?
- 3.4 Q: Can a static constructor throw exceptions in C#?
- 3.5 Q: Can you call a static constructor explicitly in C#?
- 3.6 Q: When is a static constructor called in C#?
- 3.7 Q: How is a static constructor different from an instance constructor in C#?
- 3.8 Q: Can a static constructor have parameters in C#?
- 3.9 Q: What can you do in a static constructor in C#?
- 4 Summary:
Syntax
The examples below will show you how to declare static constructor syntax without any parameters or access modifiers.
// Creating a class
public class Customer
{
// Creating a static constructor
static Customer()
{
// Code that needs to be execute only once.
}
}
Characteristics of Static constructor in C#:
A static constructor in C# has the following characteristics.
Characteristic | Description |
---|---|
Access Modifiers: | A static constructor has no access modifiers and cannot be called directly. |
Automatic Invocation: | A static constructor is automatically called by the .NET runtime before the first instance of the class is created, or any static members are referenced. |
Instantiation: | A static constructor cannot be called using the new operator. |
Parameters: | A static constructor takes no arguments and cannot be parameterized. |
Inheritance: | A static constructor is not inherited and cannot be overridden. |
Execution: | A static constructor is only executed once per application domain, regardless of the number of instances of the class created. |
Overloading: | The static constructor never overloads because it does not accept any input parameters. |
Quantity: | A class or struct can have only one static constructor. |
Naming: | The name of a static constructor must be the same as the class or struct name. |
Return Type: | A static constructor has no return type, not even void. |
Invocation Order: | In C#, a static constructor is called before the Main() method. |
Object-Independence: | A static constructor is object-independent because it can be only called by the CLR and not by the developer. |
Initialization: | Non-static data members cannot be initialized in the static constructor. |
Readonly Fields: | A field declared static read-only could only be assigned during its declaration or in a static constructor. |
C# Static constructor example
Following is an example of a static constructor in C#.
using System;
namespace StaticConstructorExample
{
// Customer class
public class Customer
{
// Static Constructor
static Customer()
{
Console.WriteLine("Static constructor executed !");
}
//Default constructor
public Customer()
{
Console.WriteLine("Default constructor executed !");
}
}
class Program
{
static void Main(string[] args)
{
// Here, Static and instance constructors
// will invoke for the first instance
Customer customer1 = new Customer();
// Here only default constructor will invoke not the static constructor.
Customer customer2 = new Customer();
Console.ReadLine();
}
}
/* Output:
Static constructor executed !
Default constructor executed !
Default constructor executed !
*/
}
Output:
In the above example, the Static constructor gets invoked only once at the time of the first object creation of the Customer
class.
For the next object creation, only the default constructor will be called.
Note: If you don’t provide a static constructor in a class to initialize static fields or variables, the C# compiler will initialize static fields to default values.
5 Scenarios Where Static Constructors Are Useful in C#
Here are some scenarios where you might want to use a static constructor in C#:
- Initializing static fields or properties:Â You can use a static constructor to initialize static fields or properties of a class. It is useful when you have some values that need to be set before any instances of the class are created.
- Loading configuration files or resources: You can use a static constructor to load configuration files or other resources your class needs to function. It ensures that the resources are loaded before any instances of the class are created.
- Registering events or services: You can use a static constructor to register events or services your class needs to interact with. A static constructor can be useful when you want to ensure that these events or services are registered before any instances of the class are created.
- Enforcing class invariants: You can use a static constructor to enforce class invariants, such as ensuring that specific fields have valid values or that some constraints are met.
- Initializing unmanaged resources: You can use a static constructor to initialize unmanaged resources, such as opening a file or initializing a database connection. It ensures that the resources are available before any instances of the class are created.
Overall, static constructors are useful when you want to ensure that some initialization code is executed before any instances of a class are created.
FAQs
Following are some frequently asked questions and answers about Static constructor in C#:
Q: What is static constructor in C#?
A static constructor in C# is a special method that is called automatically when a class is first loaded into memory. It is used to initialize any static members of the class.
Q: Why static constructor is parameterless in C#?
There is no way to call a static constructor explicitly. Therefore, having a parameterized static constructor is pointless.
Q: Can we have static and default constructors in C# at the same time?
Yes, A non-static class can have both static as well as default constructors at the same time.
Q: Can a static constructor throw exceptions in C#?
Yes, a static constructor in C# can throw exceptions if an error occurs during initialization. For example, if a static constructor tries to read a file that does not exist, it may throw a FileNotFoundException
.
Q: Can you call a static constructor explicitly in C#?
No, a static constructor in C# cannot be called explicitly. It is automatically called by the .NET runtime before the first instance of the class is created or any static members are referenced.
Q: When is a static constructor called in C#?
A static constructor is called automatically when the class is first accessed or when an instance is created.
Q: How is a static constructor different from an instance constructor in C#?
A static constructor is called automatically when the class is loaded into memory, whereas an instance constructor is called when an instance of the class is created. Also, a static constructor takes no parameters, whereas an instance constructor can take parameters.
Q: Can a static constructor have parameters in C#?
No, a static constructor in C# cannot have parameters.
Q: What can you do in a static constructor in C#?
In a static constructor in C#, you can initialize any static fields or properties of the class, load configuration files or resources, register events or services, enforce class invariants, and initialize unmanaged resources.
References MSDN: Constructors
Summary:
In this article, we learned about the static constructor in C# with examples. I hope you enjoyed this post and found it useful. In case you have any doubts, please post your feedback, question, or comments below.
Articles to Check Out
- Types of Constructors in C#
- Private Constructor in C# with example
- Copy Constructor in C# with example
- C# Abstract class Vs Interface
- C# Interface – Understanding Interfaces in C# (With Examples)
- C# Array vs List: When should you use an array or a List?
- Generic Delegates in C# With Examples
- C++ vs C#: Difference Between C# and C++
- C# Enum | How to Use enumeration type in C#?
- Properties In C# with examples
- Multithreading in C#
- Lock keyword in C#
- Monitor keyword in C#
- C# Encapsulation: Everything You Need to Know
- C# List Class With Examples
- C# Monitor class in multithreading
- C# Struct vs Class
- C# Dictionary with Examples
- Var keyword in C#
- Difference Between Array And ArrayList In C#: Choosing the Right Collection - May 28, 2024
- C# Program to Capitalize the First Character of Each Word in a String - February 21, 2024
- C# Program to Find the Longest Word in a String - February 19, 2024