Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did I get the compile error "Use of unassigned local variable"?

Tags:

c#

.net

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 anyway. 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?

like image 436
theknut Avatar asked Feb 10 '12 18:02

theknut


People also ask

What does it mean use of unassigned local variable?

Use of unassigned local variable 'name' The C# compiler doesn't allow the use of uninitialized variables. If the compiler detects the use of a variable that might not have been initialized, it generates compiler error CS0165.

What happens when the local variable is not initialized used inside a program?

In C and C++, local variables are not initialized by default. Uninitialized variables can contain any value, and their use leads to undefined behavior. Warning C4700 almost always indicates a bug that can cause unpredictable results or crashes in your program.

How do I fix CS0165?

The CS0165 error is caused when a variable created within a method is not assigned with a value using the new keyword. The error CS0165 is resolved by assigning the local variable with a new instance of it's type or as a reference to a variable of the same type.

What is the value of unassigned string in C#?

In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.


2 Answers

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.

like image 116
James Michael Hare Avatar answered Oct 23 '22 21:10

James Michael Hare


Default assignments apply to class members, but not to local variables. As Eric Lippert explained it in this answer, Microsoft could have initialized locals by default, but they choose not to do it because using an unassigned local is almost certainly a bug.

like image 26
Sergey Kalinichenko Avatar answered Oct 23 '22 22:10

Sergey Kalinichenko