C# Variable Initialization Question

后端 未结 8 908
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 03:25

Is there any difference on whether I initialize an integer variable like:

int i = 0;
int i;

Does the compiler or CLR treat this as the same

8条回答
  •  执念已碎
    2020-12-10 04:05

    With all this talk, it is worth mentioning the "default" keyword in C#.

    I.e. int i; is equivalent to int i = default(int); which is equivalent to int i = 0; and MyClass o = default(MyClass); is equivalent to MyClass o = null;

    This is especially relevant when using linq methods such as .SingleOrDefault() because you can always use the following to make your code more readable:

    int someValue = collection..SingleOrDefault();
    if (someValue == default(int))
    {
      //Code for the default case
    }
    

    and

    MyClass someValue = collection..SingleOrDefault();
    if (someValue == default(MyClass))
    {
      //Code for the default case
    }
    

提交回复
热议问题