Okay, I am trying to make a simple text game. Things were going so well, but then this little guy crept in here.
Maybe you can see something I can't? The compiler is telling me that the variable I am trying to return has not been initialized. I know that I initialized the variable in the first few lines, I just didn't assign it a value until later on. The only way that bCanMoveN could possibly remain null is if my switch statement ended up using the default variable. I tried assigning a value in the default case (for whatever reason), but it still gives me the same message. What gives?
--Use of unassigned local variable 'bCanMoveN'--
public class Movement
{
public static bool CanMove(string strMoveCurrentRoom, char chaDirection)
{
bool bCanMoveN;
bool bCanMoveE;
bool bCanMoveS;
bool bCanMoveW;
switch (strMoveCurrentRoom)
{
case "FRONT YARD":
bCanMoveN = true;
bCanMoveE = false;
bCanMoveS = false;
bCanMoveW = false;
break;
case "LIVING ROOM":
bCanMoveN = true;
bCanMoveE = true;
bCanMoveS = true;
bCanMoveW = true;
break;
default:
//error in method CanMove(). Nonexistant room.
break;
}
return bCanMoveN; <- error is here.
}
}
Ryan AlfordPosted Aug 16, 2008, 10:34 AM
setting all of the boolean objects to false when they are instantiated, you would not get the error.
AnthonyPosted Aug 18, 2008, 11:09 AM
AlanPosted Aug 16, 2008, 6:31 AM
The compiler needs to be sure that bCanMoveN will always have been assigned a value by the end of the method.
It can't be sure of this because if the 'default' case occurs, it will still be unassigned.
You therefore need to give it a value either initially or within the 'default' case (before 'break' of course).