I am confused about the order of execution in C# regarding the setting of fields and set/get properties. Why is the value in Test2 not set when the constructor gets called while the value in Test is?
When an instance of a class is created is there some type of hidden/default "constructor" that sets the fields but does not call the setter of properties?
Does the setter get automatically called after the constructor or do I explicitly have to call it?
And finally is there good reasoning for this order of execution?
OUTPUT:
Test: 5
Test2: 0
using System.IO;
using System;
class Program
{
static void Main()
{
Test test = new Test();
Test2 test2 = new Test2();
}
}
class Test
{
private int x = 5;
public Test(){
Console.WriteLine("Test: " + x);
}
}
class Test2
{
private int _x;
private int x{
get
{
return _x;
}
set
{
_x = 5;
}
}
public Test2(){
Console.WriteLine("Test2: " + x);
}
}
When an instance of a class is created is there some type of hidden/default "constructor" that sets the fields but does not call the setter of properties?
Why would it call the property setters? What would it call them with? (Your property setter doesn't use value
, which it normally would...)
It's not a matter of there being a hidden constructor - it's just that field initializers are executed prior to the base class constructor being called. Property setters are not implicitly called.
From section 10.11.2 of the C# 5 spec:
When an instance constructor has no constructor initializer, or it has a constructor initializer of the form
base(...)
, that constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class.
Note that as of C# 6, you can have automatically implemented properties with default values too:
public int Foo { get; set; } = 10;
That just means the backing field will be initialized with the value of 10
as a normal field would.
See more on this question at Stackoverflow