Static constructor C# with Example



Static constructor C# with Example

A static constructor is called the first time any member of a type is initialized, a static class member is called or a 
static method. The static constructor is thread safe. A static constructor is commonly used to: 
Initialize static state, that is state which is shared across different instances of the same class. 
Create a singleton 
Example: 
class Animal 
{ 
// * A static constructor is executed only once, 
// when a class is first accessed. 
// * A static constructor cannot have any access modifiers 
// * A static constructor cannot have any parameters 
static Animal() 
{ 
Console.WriteLine("Animal initialized"); 
} 
// Instance constructor, this is executed every time the class is created 
public Animal() 
{ 
Console.WriteLine("Animal created"); 
} 
public static void Yawn() 
{ 
Console.WriteLine("Yawn!"); 
} 
} 
var turtle = new Animal(); 
var giraffe = new Animal(); 
Output: 
Animal initialized 
Animal created 
Animal created 
View Demo 
If the first call is to a static method, the static constructor is invoked without the instance constructor. This is OK, 
because the static method can't access instance state anyways. 
 

Animal.Yawn(); 
This will output: 
Animal initialized 
Yawn! 
See also Exceptions in static constructors and Generic Static Constructors . 
Singleton example: 
public class SessionManager 
{ 
public static SessionManager Instance; 
static SessionManager() 
{ 
Instance = new SessionManager(); 
} 
} 

0 Comment's

Comment Form

Submit Comment