C# Variable Initialization Question

后端 未结 8 883
伪装坚强ぢ
伪装坚强ぢ 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:21

    As the following link states, they are exactly the same:

    http://msdn.microsoft.com/en-us/library/aa664742%28VS.71%29.aspx

    0 讨论(0)
  • 2020-12-10 04:23

    Various responses here are kind of misleading, including the referenced article in "Coding Horror" website.

    The compiler will optimize your code to remove all "unnecessary" initializations when configured to optimize the generated code. Please notice that this is the default behavior when compiling in "Release" mode.

    I, for one, think it's always very useful to initialize all your variables. The performance hit will be minimal in debug mode and none in release mode, but the gains of explicitly set the variables will be tremendous for anyone maintaining the code in the future, in the better "documenting code with code" style. I remember this very experienced coworker of mine that thought that the default value of Int32 was Int32.MinValue instead of 0. These types of confusion always happens to things implicited in the code and, to me, they should be avoided in most cases.

    0 讨论(0)
提交回复
热议问题