puffer-354 puffer-354 - 3 months ago 12
C# Question

Public string does not exist in the current context

I'm making a random name generator, everything goes right, until I add the separate parts of the names together:

string name = name1 + name2 + name3;


I get a "use of unassigned variable" for the first section, and a "does not exist in the current context" for the second and third sections. Here's the code for the first section:

int n1 = rand.make(1, 11); //just a random number function
string name1;
switch (n1)
{
case 1:
name1 = ".";
break;
case 2:
name1 = ".";
break;
case 3:
name1 = ".";
break;
case 4:
name1 = ".";
break;
case 5:
name1 = ".";
break;
case 6:
name1 = ".";
break;
case 7:
name1 = ".";
break;
case 8:
name1 = ".";
break;
case 9:
name1 = ".";
break;
case 10:
name1 = ".";
break;


the second and third sections are the same but in an if, so I make the string public and then all the variables in the switch are given the same "does not exist in the current context".

That's all I can think to do so far.

Answer

Even though you're smart enough to know that rand.make(1, 11) will return a value between 1 and 10, and that one of those case statements will definitely apply, the compiler is not.

As far as the compiler is concerned, if none of those case statements applies, then name1 will not have a value assigned to it.

Either give name1 an initial value, or create a default case in your switch statement.