Minimus Heximus
Minimus Heximus

Reputation: 2815

Initialization of simple types

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

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

or

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

What does new int() exactly do?

Upvotes: 0

Views: 58

Answers (3)

Owen James
Owen James

Reputation: 628

Consider using the var keyword.

var i = 111;

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

Upvotes: 1

user5320118
user5320118

Reputation: 1

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.

Upvotes: 0

Cyral
Cyral

Reputation: 14153

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)

Upvotes: 3

Related Questions