Use of unassigned local variable <resolved>
This is driving me insane. I'm sure the mistake is rediculously simple to see but I can't figure it out. Maybe you guys can see what I'm doing wrong...
The error:
Code:
error CS0165: Use of unassigned local variable 'carType'
error CS0165: Use of unassigned local variable 'carMake'
error CS0165: Use of unassigned local variable 'carColor'
The code:
Code:
string carColor;
string carMake;
string carType;
switch(carList[lstMadeCars.SelectedIndex].GetType().Name)
{
case "Car":
{
carColor = ((Car)carList[lstMadeCars.SelectedIndex]).aCarColor.ToString();
carMake = ((Car)carList[lstMadeCars.SelectedIndex]).aCarMake.ToString();
carType = ((Car)carList[lstMadeCars.SelectedIndex]).aCarType.ToString();
break;
}
case "SportsCar":
{
carColor = ((SportsCar)carList[lstMadeCars.SelectedIndex]).aCarColor.ToString();
carMake = ((SportsCar)carList[lstMadeCars.SelectedIndex]).aCarMake.ToString();
carType = ((SportsCar)carList[lstMadeCars.SelectedIndex]).aCarType.ToString();
break;
}
}
lblResult.Text = carType + "\n" + carMake + " " + carColor; //carType, carMake, and carColor where all underlined by VS on this line
Am I missing something here? Thanks for any help in advance.
Re: Use of unassigned local variable
When you declare a variable without assigning a value (e.g. string x;), it is essentially points to absolutely nothing - thus the compilation error.
Easiest way to get rid of those compile errors would be to initialise your variables prior to entering the case statement:
Code:
string carColor = string.Empty;
string carMake = string.Empty;
string carType = string.Empty;
Re: Use of unassigned local variable
I figured it was something like that. So neither value types nor ref types are automatically given a value when declared within a function?