Possible Duplicate:
Where and why use int a=new int?
What's the difference between these two below?
int i =0;
int i = new int();
Is there any difference in case of memory allocation ? Is there any other difference?
Possible Duplicate:
Where and why use int a=new int?
What's the difference between these two below?
int i =0;
int i = new int();
Is there any difference in case of memory allocation ? Is there any other difference?
Both of them compiles to same thing.
Suppose you have:
static void Main(string[] args)
{
int i = 0;
int j = new int();
Console.Write("{0}{1}", i, j);
}
If you build in Release mode and see the executable in ILSpy, it compiles to:
private static void Main(string[] args)
{
int i = 0;
int j = 0;
Console.Write("{0}{1}", i, j);
}
new int()
is same as default(int)
Here is the IL
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 27 (0x1b)
.maxstack 3
.locals init ([0] int32 i,
[1] int32 j)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: ldstr "{0}{1}"
IL_0009: ldloc.0
IL_000a: box [mscorlib]System.Int32
IL_000f: ldloc.1
IL_0010: box [mscorlib]System.Int32
IL_0015: call void [mscorlib]System.Console::Write(string,
object,
object)
IL_001a: ret
} // end of method Program::Main
The first one
int i = 0;
Initialize a new integer of name i
. Then, sets its value to 0
While the second one
int i = new int();
Initializes a new integer of name i
to the default value (which is 0
). This is also similar to
int i = default(int);
Thanks,
I hope you find this helpful :)