Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int num = new int(); What happens when this line executes?

Got to know a new thing today that we can create integers by using new operator as below

int num = new int();

Now I wonder if I create an integer in this manner then the resulting integer will be a value type or reference type? I guess it will be a value type. I tried the below code

int num1 = 10;
int num2 = new int();
int num3;
num1 = num2;
num2 = num3;

I got the below build error:

Use of unassigned local variable 'num3'

I know why this build error is given. But I wonder when and how to use new int() and how exactly does this work? Can anyone please put some light on this?

Thanks & Regards :)

like image 209
Narendra Avatar asked Sep 07 '25 05:09

Narendra


1 Answers

int i = new int();

is equavalent to

int i = 0;

There is no difference between them. They will generate the same IL code at all.

  // Code size       4 (0x4)
  .maxstack  1
  .locals init ([0] int32 num)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  IL_0003:  ret

From Using Constructors (C# Programming Guide)

Constructors for struct types resemble class constructors, but structs cannot contain an explicit default constructor because one is provided automatically by the compiler. This constructor initializes each field in the struct to the default values.

Default value of integers is 0. Check for more Default Values Table

like image 95
Soner Gönül Avatar answered Sep 08 '25 20:09

Soner Gönül