Where and why use int a=new int?

Miriah picture Miriah · Apr 21, 2011 · Viewed 43.2k times · Source

Just curious, what is the difference between:

int A = 100;

and

int A = new int();  

I know new is used to allocate memory on the heap..but I really do not get the context here.

Answer

Aliostad picture Aliostad · Apr 21, 2011
static void Main()
{
    int A = new int();
    int B = default(int);
    int C = 100;
    Console.Read();
}

Is compiled to

.method private hidebysig static void  Main() cil managed
{
  .entrypoint
  // Code size       15 (0xf)
  .maxstack  1
  .locals init ([0] int32 A,
           [1] int32 B,
           [2] int32 C)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  IL_0003:  ldc.i4.0
  IL_0004:  stloc.1
  IL_0005:  ldc.i4.s   100
  IL_0007:  stloc.2
  IL_0008:  call       int32 [mscorlib]System.Console::Read()
  IL_000d:  pop
  IL_000e:  ret
} // end of method Program::Main

As you can see first one just initialize it and second one is just the same and third one initialize and set to 100. As for the IL code generated, they both get initialized in a single line.

so

int A = new int();

Is the same as

int A = default(int);