Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where and why use int a=new int?

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.

like image 471
Miriah Avatar asked Apr 21 '11 16:04

Miriah


People also ask

What is the use of new int?

Creates a integer array of 'n' elements.

What is the difference between int and new int?

There is no difference between the two of them. But you should never instintiate your value types with the 'new' keyword.

Why do we use new int in java?

new int[] means initialize an array object named arr and has a given number of elements,you can choose any number you want,but it will be of the type declared yet.

What is the use of new int in C++?

*new int means "allocate memory for an int , resulting in a pointer to that memory, then dereference the pointer, yielding the (uninitialized) int itself".


2 Answers

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); 
like image 69
Aliostad Avatar answered Sep 23 '22 07:09

Aliostad


Difference?

the latter ends with A being 0, not 100.

When?

Pretty much never. Maybe in some generated code it is simpler to use the new TypeName() syntax, but default(TypeName) would be preferred even then.

And new does not "allocate memory on the heap". It initializes an instance; that is all.

like image 20
Marc Gravell Avatar answered Sep 25 '22 07:09

Marc Gravell