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);
}
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire