//CodeSample1
//declare class fileds but not initialize them.
public class Cat
{
public int Age;
public string Name;
}
Cat aCat = new Cat();
Check the result, aCat.Age is 0, aCat.Name is null.
How the fields are initialized? The above code just declare fields and not initialize them.
If you do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values as listed in Default Values Table.(From Microsoft document 1)
So it's the compiler generated default constructor initialize fields. Is it right?
Changed Code, initialize fields when declare them.
//CodeSample2
//declare class fields and initialize them at same time.
public class Cat
{
public int Age = 4;
public string Name = "Black";
}
Cat aCat = new Cat();
This time the Result is that aCat.Age is 4, and aCat.Name is "Black".
I know the result is as expected. But do not understand how it works.
Fields are initialized immediately before the constructor for the object instance is called. (From Microsoft Document 2)
Combine the Microsoft document 1 and Microsoft Document 2, CodeSample1 and CodeSample2 should have the same results (I know it strange).
My understanding is, in CodeSample2, firstly Age field is initialize to 4, then the compiler generated default constructor is called and set the age to default value (0).
Have I misunderstood the documents, or the documents are somewhat wrong?
If there are more accurate documents, please show me.