S
S
Sergey2020-11-08 09:24:06
C++ / C#
Sergey, 2020-11-08 09:24:06

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);


And so it works! :-)
int a=1;
    int b=5;
    switch(a){
      case 1:
        b=100;
        Console.WriteLine ("изнутри "+b);
        break;
    }
    Console.WriteLine ("снаружи "+b);


How so?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Korotenko, 2020-11-08
@firedragon

You clearly wrote that an unassigned variable is being used. Poke by mistake will transfer you to her
9d3a65121b.jpg

int a = 1;
            int b ;
            switch (a)
            {
                case 1:
                    b = 100;
                    Console.WriteLine("изнутри " + b);
                    break;
                default:
                    b = 0;
                    break;
            }
            Console.WriteLine("снаружи " + b);

V
Vasily Bannikov, 2020-11-08
@vabka

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); //<-тут ошибка

Alternatively, if you don’t want to initialize b right away, you can add a default branch to switch:
int a=1;
    int b;
    switch(a){
      case 1:
        b=100;
        Console.WriteLine ("изнутри "+b);
        break;
       default:
         b = -1;
         break;
    }
    Console.WriteLine ("снаружи "+b);

I would also advise using switch-expression from C# 8 - it immediately excludes such a class of errors
var a = 1;
var b = a switch {
   1 => 100,
   _ => -1 // Если не добавить эту ветку, то будет ошибка, что switch-expression покрывает не все возможные варианты
};
//b гарантированно инициализировано

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question