C# Static Constructor Example

CSharp · Console

/Program.cs

using System;

					
public class Program
{
	public static void Main()
	{
		var turtle = new Animal();
		var giraffe = new Animal();
	}
}

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!");
    }
}
;