-1

I'm making a basic chat program as a thesis and I've run into this problem.

enter image description here

As you can see on the picture, it gives me an unassigned variable error at line 107, but it works perfectly fine afterwards (like at line 125). The switch case always starts with case 1, in which I create a new UserLogin form called login. After that it decides wether it should go to case 2 or 3. Neither of them has any unassigned variable error except the line 107 one. I don't really have a clue as to why is this happening.

B.K.
  • 9,982
  • 10
  • 73
  • 105
DarkSide
  • 19
  • 2

2 Answers2

3

That's because the only place the variable gets assigned at is case 1. You need to assign it outside of the switch statement, since there is a possibility that case 1 will never execute, thus, the variable will never be assigned.

B.K.
  • 9,982
  • 10
  • 73
  • 105
3

Even though you know you'll hit case number 1 before hitting 2 or 3, the compiler doesn't.

You need to assign login a value before the switch block, even if it's just null.

login = null;

switch (...)
{
    case 1:
        login = new UserLogin();
        ...

If you know you're always going to hit case 1 first, consider just assigning login a new UserLogin before you even enter the switch statement.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165