Constructor and Property Initialization

suggest change

Shall the property value’s assignment be executed before or after the class’ constructor?

public class TestClass 
{
    public int TestProperty { get; set; } = 2;
    
    public TestClass() 
    {
        if (TestProperty == 1) 
        {
            Console.WriteLine("Shall this be executed?");
        }

				if (TestProperty == 2) 
        {
            Console.WriteLine("Or shall this be executed");
        }
    }
}

var testInstance = new TestClass() { TestProperty = 1 };

In the example above, shall the TestProperty value be 1 in the class’ constructor or after the class constructor?


Assigning property values in the instance creation like this:

var testInstance = new TestClass() {TestProperty = 1};

Will be executed after the constructor is run. However, initializing the property value in the class’ property in C# 6.0 like this:

public class TestClass 
{
    public int TestProperty { get; set; } = 2;

    public TestClass() 
    {
    }
}

will be done before the constructor is run.


Combining the two concepts above in a single example:

public class TestClass 
{
    public int TestProperty { get; set; } = 2;
    
    public TestClass() 
    {
        if (TestProperty == 1) 
        {
            Console.WriteLine("Shall this be executed?");
        }

        if (TestProperty == 2) 
        {
            Console.WriteLine("Or shall this be executed");
        }
    }
}

static void Main(string[] args) 
{
    var testInstance = new TestClass() { TestProperty = 1 };
    Console.WriteLine(testInstance.TestProperty); //resulting in 1
}

Final result:

"Or shall this be executed"
"1"

Explanation:

The TestProperty value will first be assigned as 2, then the TestClass constructor will be run, resulting in printing of

"Or shall this be executed"

And then the TestProperty will be assigned as 1 due to new TestClass() { TestProperty = 1 }, making the final value for the TestProperty printed by Console.WriteLine(testInstance.TestProperty) to be:

"1"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents