My question is not about how to solve this error(I already solved it) but why is this error with boolean value.
My function is
private string NumberToString(int number, bool flag)
{
string str;
switch(flag)
{
case true:
str = number.ToString("00");
break;
case false:
str = number.ToString("0000");
break;
}
return str;
}
Error is Use of unassigned local variable 'str'. Bool can only take true or false. So it will populate str in either case. Then why this error?
Moreover this error is gone if along with true and false case I add a default case, but still what can a bool hold apart from true and false?
Why this strange behaviour with bool variable?
The error you get is about
stringvariable and notbooleanpossible values.The fact that there is no way that noone of
casesrun, is a true (in this case), but compiler doesn’t go so far in analyzing the code. It just looks on variable that is not assigned and used in some conditions and there is not default one, so suppose that there could be some case when it remains unassigned.