C# Variable Initialization Question

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

    These are only equivalent for fields (class variables). Fields are automatically assigned the default values when the class is initialized. Within a method or property, the unassigned variable remains unassigned and will cause a compiler error if you try to access it's value.

提交回复
热议问题