0

I didn't understand the actual use of new int()

So my qustion is what is the difference between

int myNumber = 5;

and

int myNumber = new int(); 

What is the best use of new int() or when should we use new int() I know the memory allocation difference (stack and heap) but i didn't find any actual use of new int()

Mohd Ahmed
  • 1,422
  • 13
  • 27

3 Answers3

0

Never use new int();. Always use:

int myNumber = 5;

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

bool myBool = new bool(); // <== just looks odd, right?
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70
  • 2
    I just want to ask, why? – Soner Gönül Jul 09 '13 at 09:40
  • Even if there is a difference, as pointed out by others. The difference is so tiny you should not bother about 4 Bytes (an integer), except if you're programming for micro processors. Instead you should bother about readability of your written code. – Fabian Bigler Jul 09 '13 at 09:45
  • There are times, especially in generic programming, where you might well be doing a `new int()` under the hood. – Moo-Juice Jul 09 '13 at 09:49
0
int myNumber = new int();

is equivalent to:

int myNumber = 0;
Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
Bas
  • 26,772
  • 8
  • 53
  • 86
0
int myNumber;

int myNumber = 0;

int myNumber = new int(); 

The effect should be exactly the same, you can try to ILDASM them if you're doubtful

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
br1
  • 313
  • 1
  • 10