Puneet Pant
Puneet Pant

Reputation: 1048

What happens when we initialize a value type by using new keyword?

When we initialize a value type by using new keyword like:-

int i=new int();

Then what happens with memory allocation of this object. Is memory allocated on the stack or on the heap ?

Upvotes: 1

Views: 387

Answers (2)

ayun12
ayun12

Reputation: 539

It is being allocated on the stack.

Take a look at the IL in the following answer: Where and why use int a=new int?

int A = new int() compiles to:

IL_0001:  ldc.i4.0         // Push 0 onto the stack as int32.   
IL_0002:  stloc.0          // Pop a value from stack into local variable

int C = 100 compiles to:

IL_0005:  ldc.i4.s   100   // Push num onto the stack as int32
IL_0007:  stloc.2          // Pop a value from stack into local variable

There is basically no difference between them.

You can use this as a reference:

https://en.wikipedia.org/wiki/List_of_CIL_instructions

Update: As @Adrian wrote, it depends on the scope. There is not difference between int a = 10 and int a = new int() but it wasn't exactly the question.

Upvotes: 2

adjan
adjan

Reputation: 13652

It depends on where this statement is written. If it's in the body of a method, the value will be allocated on the stack:

void Method()
{
    int i = new int(); // Allocated on stack
}

IL-Code:

ldc.i4.0
stloc.0    // store as local variable

If you write it in the body of a class, it will be allocated on the heap, as every reference type is allocated on the heap:

class Class
{
    int i = new int(); // Allocated on heap
}

IL-Code:

ldc.i4.0
stfld      int32 Class::i  // store in field

The same applies for initializing fields in a method or constructor of a class. For structs, it depends on where they are currently allocated.

Upvotes: 2

Related Questions