Why compile error “Use of unassigned local variabl

2018-12-31 08:43发布

My code is the following

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

Why is there an error Use of unassigned local variable tmpCnt? I know I didn't explicitly initialize it but due to Default Value Table a value type is initialized with 0 anyways. The reference also reminds me:

Remember that using uninitialized variables in C# is not allowed.

But why do I have to do it explicitly if it's already done by default? Wouldn't it gain performance if I wouldn't have to do it? Just wondering...

8条回答
零度萤火
2楼-- · 2018-12-31 09:21

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.

查看更多
牵手、夕阳
3楼-- · 2018-12-31 09:21

The default value table only applies to initializing a variable.

Per the linked page, the following two methods of initialization are equivalent...

int x = 0;
int x = new int();

In your code, you merely defined the variable, but never initialized the object.

查看更多
登录 后发表回答