Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one is better to use and why in c#

Tags:

c#

Which one is better to use?

int xyz = 0;

OR

int xyz= default(int);

like image 490
Venom Avatar asked Jul 08 '10 06:07

Venom


2 Answers

int xyz = 0;

Why make people think more than necessary? default is useful with generic code, but here it doesn't add anything. You should also think if you're initializing it in the right place, with a meaningful value. Sometimes you see, with stack variables, code like:

int xyz = 0;

if(someCondition)
{
  // ...
  xyz = 1;
  // ...
}
else
{
  // ...
  xyz = 2;
  // ...
}

In such cases, you should delay initialization until you have the real value. Do:

int xyz;

if(someCondition)
{
  // ...
  xyz = 1;
  // ...
}
else
{
  // ...
  xyz = 2;
  // ...
}

The compiler ensures you don't use an uninitialized stack variable. In some cases, you have to use meaningless values because the compiler can't know code will never execute (due to an exception, call to Exit, etc.). This is the exception (no pun intended) to the rule.

like image 110
Matthew Flaschen Avatar answered Nov 15 '22 23:11

Matthew Flaschen


It depends what you want to achieve.

I would prefer

int xyz = 0;

as I believe it is more readable and not confusing.

default keyword is mostly suitable for Generics.

like image 39
Incognito Avatar answered Nov 16 '22 00:11

Incognito