Killzone Killzone - 3 months ago 16
C# Question

How to reference a variable outside of scope in C#

My professor asked us to create a program that takes in a user's height and weight, and then calculate bmi. I decided to take it a little further and added in some "input validation" logic. This means that if someone inputs "cat" for their weight, it let the user know that "cat" is not a valid weight.

class MainClass
{
public static void Main ()
{
float userWeight;
float userHeight;
bool weight = true;
Console.Write ("Weight: ");
while (weight)
{
var inputWeight = (Console.ReadLine ());
if (!float.TryParse (inputWeight, out userWeight)) {
Console.WriteLine ("Invalid input");
Console.Write ("Please try again: ");
}
else
{
weight = false;
}
}
bool height = true;
Console.Write ("Height: ");
while (height)
{
var inputHeight = (Console.ReadLine ());
if (!float.TryParse (inputHeight, out userHeight)) {
Console.WriteLine ("Invalid input");
Console.Write ("Please try again: ");
}
else
{
height = false;
}
}
float bmiHeight = userHeight * userHeight; // error for userHeight
float bmi = userWeight / bmiHeight * 703; // error for userWeight
Console.WriteLine ("You BMI is " + bmi);
}
}


The error I get is "use of unassigned local variable..". I know that I am assigning the user variables within IF statements, and that they only persist until the end of that IF statement.

My question is, how do I assign a variable in an if statement, and then reference the new value of that variable outside of that statement?

Certainly I don't have to nest them all, because that seems tedious....

Answer

The issue here is that there is a chance that your variables userHeight and userWeight are still holding garbage value since you did not initialize them.

You can try initializing them with a default valid:

float userHeight = DEFAULT_HEIGHT;
float userWeight = DEFAULT_WEIGHT;