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 to share