Variable position problems, C #

What's wrong with the code? Why is the second report showing an error?

string level;
int key;

command.CommandText = "SELECT * FROM user WHERE name = 'admin'";

connection.Open();
Reader = command.ExecuteReader();

while (Reader.Read())
{
    level = Convert.ToString(Reader["level"]);
    key = Convert.ToInt32(Reader["key"]);

    MessageBox.Show(level); //Work fine
}

MessageBox.Show(level); //Show error:  Use of unassigned local variable 'level'

      

+2


a source to share


5 answers


The compiler has no way of knowing that the level got the value. For everything it knows, it Reader.Read()

always returns false, leaving the level empty.



The most common solution for this is to just initialize the level to null

(or I agree with AdaTheDev, string.Empty

might be a good choice too)

+6


a source


If the query does not return any results, the level was never assigned a value.

You can initialize a variable when you declare it to prevent it:



string level = String.Empty;

      

+4


a source


set default value on variable initialization

string level = string.Empty;

      

The compiler knows that a variable cannot be assigned inside a while loop, as this may not be true in all code paths.

+1


a source


It is possible that Reader.Read () will immediately return false, in which case "level" will never be assigned. If you initialize a variable with string level = string.Empty;

, you will bypass it.

0


a source


It's always a good idea to start initializing variables. C # forcefully shows this message. No one can guarantee that your level variable will be assigned inside a while - as @AdaTheDev pointed out

0


a source







All Articles