0

Which of these codes is preferred‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌?

int a = new int();
a = 111;

or

int a;
a = 111‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌;

What does new int() exactly do?

Minimus Heximus
  • 2,683
  • 3
  • 25
  • 50

3 Answers3

3

The second, and if possible, simply:

int a = 111;

Value types do not need to use new()

Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized. (From MSDN)

Cyral
  • 13,999
  • 6
  • 50
  • 90
1

Consider using the var keyword.

var i = 111;

i will automatically be resolved to an int at compile time.

Owen James
  • 628
  • 7
  • 16
0

The second code is preferred because the first one is equivalent to:

int a;
a = 0;
a = 111;

Now its clear tht the second code is more reasnonable.