Answer the question
In order to leave comments, you need to log in
Why doesn't C# see the variable inside the switch?
There are A and B.
If A=1, then switch makes B=100 and displays it on the screen.
After that, I want to call variable B one more time.
Так не работает :-(
int a=1;
int b;
switch(a){
case 1:
b=100;
Console.WriteLine ("изнутри "+b);
break;
}
Console.WriteLine ("снаружи "+b);
int a=1;
int b=5;
switch(a){
case 1:
b=100;
Console.WriteLine ("изнутри "+b);
break;
}
Console.WriteLine ("снаружи "+b);
Answer the question
In order to leave comments, you need to log in
You clearly wrote that an unassigned variable is being used. Poke by mistake will transfer you to her
int a = 1;
int b ;
switch (a)
{
case 1:
b = 100;
Console.WriteLine("изнутри " + b);
break;
default:
b = 0;
break;
}
Console.WriteLine("снаружи " + b);
In the first variant
int a=1;
int b; //не инициализировано
switch(a){
case 1:
b=100;
Console.WriteLine ("изнутри "+b);
break;
}//если a != 1, то b всё ещё не инициализировано
Console.WriteLine ("снаружи "+b); //<-тут ошибка
int a=1;
int b;
switch(a){
case 1:
b=100;
Console.WriteLine ("изнутри "+b);
break;
default:
b = -1;
break;
}
Console.WriteLine ("снаружи "+b);
var a = 1;
var b = a switch {
1 => 100,
_ => -1 // Если не добавить эту ветку, то будет ошибка, что switch-expression покрывает не все возможные варианты
};
//b гарантированно инициализировано
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question