May 8, 2010

Static constructor of a derived class is called before the static constructor of the base class

However, for non-static constructors, the order is the other way around. See examples below:

Example 1. Static constructors

public class Test
    {
        static Test()
        {
            Console.WriteLine("test constructor");
        }
    }

    public class TestExtended : Test
    {
        static TestExtended()
        {
            Console.WriteLine("test extended constructor");
        }
    }

Output:
test extended constructor
test constructor

Example 2. Public constructors

public class Base
    {
        public Base()
        {
            Console.WriteLine("base constructor");
        }
    }

    public class BaseExtended : Base
    {
        public BaseExtended()
        {
            Console.WriteLine("base extended constructor");
        }
    }

Output:
base constructor
base extended constructor

No comments:

Post a Comment