Why does’t this code output the value of 50?
class Program
{
static void Main(string[] args)
{
var myClass = new TestConstructor() { MyInt = 50 };
}
}
class TestConstructor
{
public int MyInt { get; set; }
public TestConstructor()
{
Console.WriteLine(this.MyInt);
Console.Read();
}
}
This code:
is effectively transformed into:
How would you expect the property to be set before the constructor was executed?
(The use of a temporary variable here isn’t important in this case, but it can be in other cases:
In the second line, it’s important that
myClass.MyIntstill refers to the first object, not the newly-created one.)