What Does "Use of Unassigned Local Variable" Mean

What does Use of unassigned local variable mean?

The compiler isn't smart enough to know that at least one of your if blocks will be executed. Therefore, it doesn't see that variables like annualRate will be assigned no matter what. Here's how you can make the compiler understand:

if (creditPlan == "0")
{
// ...
}
else if (creditPlan == "1")
{
// ...
}
else if (creditPlan == "2")
{
// ...
}
else
{
// ...
}

The compiler knows that with an if/else block, one of the blocks is guaranteed to be executed, and therefore if you're assigning the variable in all of the blocks, it won't give the compiler error.

By the way, you can also use a switch statement instead of ifs to maybe make your code cleaner.

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

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.

C# Beginner - Use of Unassigned Local Variable Issue

The problem is that if product1 does not equal any of the values in your if statements, then none of those sections will ever run, and so in theory there is a danger that price1 might never be given a value. And it can't use something which doesn't have a value to add it to something else. That's what the compiler is complaining about. You need to give price1 a default value when you first declare it, as a fallback option in case the user enters something which is not one of the four expected product names.

double price1 = 0;

Is probably ok for this scenario, but you can choose whatever value you think is best, as long as there is some kind of value.

You will have the exact same issue with price2 as well.

Compiler error - use of unassigned local variable . what can go wrong?

The use of an unassigned variable can be a potential bug or not (it almost always is). The question here is; if it is a bug, when would you like to know about it? At compile time or at runtime where it can be relatively hard to spot if the code is sufficiently complex or the introduced bug is subtle?

A simple example:

string Join(params object[] array)
{
string foo;

foreach (var o in arr)
foo += o.ToString();
}

So now, we have two options: the compiler lets you compile this happily and watches you crash and burn in runtime, or it tells you straightaway you have bug. The latter choice seems better to me.

Now, when you wrote this question, you were probably thinking in value types more than in reference types; an unassigned reference type is practically an immediate NullReferenceException and, although vexing, easy to fix once you run the code for the first time.

Value types on the contrary have usable default values, but that makes the situation a whole lot worse. Now maybe you forgot to initialize a variable to a sensible value and nothing apparently obvious is going wrong in runtime but maybe you've just introduced a not so obvious bug in your program:

int totalDays(DateTime date)
{
DateTime now; //TODO: initialize to server time, not local DateTime.Now
return (now - date).TotalDays;
}

Writing this code you spill your coffee, then you get a phone call from you wife telling you your dog got sick and puked on your favorite (and expensive) rug and again on the way to the vet in your brand new car... by the time you get back you've forgotten about totalDays (I finished writing it didn't I?) and you start working on other stuff in your project. By the end of the day/week, you need to meet a deadline and you ship a bug in your code. The compiler can warn you easily that something smelly is going on. Why on earth wouldn't you want it to?

Convinced?

How to fix 'Use of unassigned local variable' in C#

Here's a fixed version of your code, with comments as to why I made the change:

class Program
{
static void Main(string[] args)
{
//fix the 'use of undefined' error
int average = 0;
int[] scores = new int[10];

Console.WriteLine("Enter 10 scores");

//it's better to scope loop iteration variables to the loop unless you specifically need them outside
for (int i = 0; i < 10; i++)
{
scores[i] = Convert.ToInt32(Console.ReadLine());
}

for (int i = 0; i < 10; i++)
{
//your old code would crash here, and had the wrong algorithm for calculating an average; it didn't sum all the entered values, just the last two
average += scores[i];
}

average /= 10;

Console.WriteLine("Average of All the Scores: {0}", average);
Console.Read();
}
}

I was puzzled as to why the error occurred too because the second loop was clearly assigning a value and I knew that inner scopes could set values and the compiler would recognise them.. learning day for me too as I was formerly unaware that some loops are excluded even when they're set up so they look like they will definitely run. In simple terms it seems that when a loop is set up so that its running is conditional on a variable, the flow analysis considers that in some scenarios the loop might not run even though it's clear to the human reading the code that the loop will always run. Consider these:

//this is fine, flow analysis determines this loop will always run
int average;
while(true){
average = 0;
break;
}
average /= 10;

//this raises the same error even though we as a human can definitely see this loop will always run
int average;
int w = 0;
while(w<1){
average = 0;
}
average /= 10;

Making the loop conditional on a variable meant the compiler wa and longer sure the variable was assigned

As another more involved example, you could also fix your error with this bizarre construct as your first loop:

        for (int i = 0; true; i++)
{
average = 0;
scores[i] = Convert.ToInt32(Console.ReadLine());
if(i >= 10)
break;
}

Again the compiler can be sure this loop will always run and your variable will be assigned

here's Peter's comment in case the other answer/the comment goes away:

the compiler doesn't implement any static flow analysis that would confirm that the average variable is set. According to the "definite assignment" rules of C#, loops are ignored because it's possible for a loop to not iterate even once. Thus, average is not definitely assigned, and thus the error. See marked duplicate, and of course the C# language specification, for more details.




Related Topics



Leave a reply



Submit