Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with the variable position, C#

Tags:

c#

What's wrong with the code? Why on the second report shows a mistake?

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'
like image 712
lolalola Avatar asked Mar 23 '26 14:03

lolalola


2 Answers

The compiler has no way of knowing level got a value. For all it knows, Reader.Read() always returns false, thus leaving level without a value.

The most common solution to this is to just initialize level to null (or I agree with AdaTheDev, string.Empty might be a good choice here too)

like image 78
Matt Greer Avatar answered Mar 25 '26 04:03

Matt Greer


If the query returns no results, level would never have been assigned a value.

You can initialise the variable when you declare it to prevent it:

string level = String.Empty;
like image 26
AdaTheDev Avatar answered Mar 25 '26 03:03

AdaTheDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!