Why compile error “Use of unassigned local variable”?

前端 未结 10 2183
说谎
说谎 2020-11-22 03:16

My code is the following

int tmpCnt;  
if (name == \"Dude\")  
   tmpCnt++;  

Why is there an error Use of unassigned local variabl

10条回答
  •  你的背包
    2020-11-22 03:53

    While value types have default values and can not be null, they also need to be explicitly initialized in order to be used. You can think of these two rules as side by side rules. Value types can NOT be null==> the compiler guarantes that. If you ask how? the error message you got is the answer. Once you call their constructors, they got inialized with their default values.

    int tmpCnt; // not accepted 
    int tmpCnt = new Int(); // defualt value applied tmpCnt = 0 
    

提交回复
热议问题