If it is default constructor, who will initialize the member variables to zero then how come this will be possible
class A
{
public int i;
public int j;
public A()
{
i=12;
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
Console.WriteLine(a.i + "" + a.j);
Console.ReadLine();
}
}
Because field initializers run before constructors. You didn't assign j
value in your constructor, it will be 0
by default since it is an int
.
From 10.4.4 Field initialization
The initial value of a field, whether it be a static field or an instance field, is the default value (Section 5.2) of the field's type.
Who do that? Well, looks like newobj
does that when you call new
. Take a look dyatchenkos' answer for more details.
A field initialization happens before a constructor call through the newobj
command. It is easy to check after decompilation of the executable with the following C# code:
using System;
namespace ConsoleApplication1
{
public class A { public int j; }
class Program
{
static void Main(string[] args)
{
A g = new A();
Console.WriteLine(g.j);
}
}
}
Part of the decompilted MSIL code (method main):
//000017: {
IL_0000: nop
//000018: A g = new A();
IL_0001: newobj instance void ConsoleApplication1.A::.ctor()
IL_0006: stloc.0
//000019: Console.WriteLine(g.j);
IL_0007: ldloc.0
IL_0008: ldfld int32 ConsoleApplication1.A::j
IL_000d: call void [mscorlib]System.Console::WriteLine(int32)
IL_0012: nop
//000020: }
As we can see the MSIL uses the newobj
instruction to create an instance of the A class. According to the following microsoft acticle:
The newobj instruction allocates a new instance of the class associated with ctor and initializes all the fields in the new instance to 0 (of the proper type) or null references as appropriate. It then calls the constructor ctor with the given arguments along with the newly created instance. After the constructor has been called, the now initialized object reference (type O) is pushed on the stack.
If it is wrong, please comment, otherwise assign it as a right answer, please.
In C#, int
variables will always default to 0 unless otherwise specified. In your constructor:
public A ()
{
i=12;
}
When your object is instantiated, your i
property will be initialized to 12, while your j
property will be initialized to 0.
In your code:
public class Program
{
A a = new A(); // You instantiated your object, i will be assigned 12
Console.WriteLine(a.i.ToString() + "" + a.j.ToString());
// Your output will be 12 0 because you didn't initialize j so the default is 0
Console.ReadLine();
}
I hope this helps!
The answer lies in the fact that c# numeric fields are 0 by default. While in C++ the int field is some random value by default
During the instance creation, its variables are made available too. And since int is not nullable, it initializes with default(int). Which is 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With