Why compile error “Use of unassigned local variable”?

前端 未结 10 2333
说谎
说谎 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 04:06

    Local variables aren't initialized. You have to manually initialize them.

    Members are initialized, for example:

    public class X
    {
        private int _tmpCnt; // This WILL initialize to zero
        ...
    }
    

    But local variables are not:

    public static void SomeMethod()
    {
        int tmpCnt;  // This is not initialized and must be assigned before used.
    
        ...
    }
    

    So your code must be:

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

    So the long and the short of it is, members are initialized, locals are not. That is why you get the compiler error.

提交回复
热议问题