Unassigned variable in C #

4

The variable in the last console.writeLine is giving that was not assigned being in the ifs, I would like to know why.

string c, nome;
double s, sn;

Console.WriteLine("Escreva o nome:");
nome = Console.ReadLine();
Console.WriteLine("Escreva o salário:");
s = double.Parse(Console.ReadLine());
Console.WriteLine("Escreva a categoria:");
c = Console.ReadLine();

if (c == "a" || c == "c" || c == "f" || c == "h")
{
    sn = s * 1.10;
}
else if (c == "b" || c == "d" || c == "e" || c == "i" || c == "j" || c == "t")
{
    sn = s * 1.15;
}
else if (c == "k" || c == "r")
{
    sn = s * 1.25;
}
else if (c == "l" || c == "m" || c == "n" || c == "o" || c == "p" || c == "q" || c == "s")
{
    sn = s * 1.35;
}
else if (c == "u" || c == "v" || c == "x" || c == "y" || c == "w" || c == "z")
{
    sn = s * 1.50;
}
else
{
    Console.WriteLine("Categoria inválida!");
}

Console.WriteLine(" Nome: {0}\n Categoria: {1}\n Novo salário: R$ {2:0.00}", nome, c, sn);

Console.ReadKey();
    
asked by anonymous 14.09.2018 / 20:37

2 answers

3

Because if the code drops in else the variable will never receive a value.

Just initialize the variable with the default value.

double s, sn = 0;
// ...

Trying to read the code, it seems to me that it would be more reasonable to "cancel" the operation and return on else .

else
{
    Console.WriteLine("Categoria inválida!");
    return;
}
    
14.09.2018 / 20:41
1
  

I would like to know why

Responding to your question, the reason this message occurs is that there is a path that the code can go through, which is the last else , where the variable sn has not been assigned to any value and at the end of the program you are showing the value of this variable.

The solution that @LINQ gave you so that the error does not occur is to start the variable with a value of 0 at the beginning. Another way would be to put in the last else a statement sn = 0;

    
14.09.2018 / 21:05