开发者

Problems with the variable position, C#

开发者 https://www.devze.com 2022-12-28 14:00 出处:网络
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\'\";

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();

w开发者_StackOverflowhile (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'


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)


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;


set level to a default value when initialising the variable

string level = string.Empty;

The compiler knows that the variable may not be assigned to inside the while loop as this may not be executed on all code paths.


There is a chance that Reader.Read() will return false immediately, in which case "level" will never be assigned to. If you initialise the variable with string level = string.Empty; you'll get around it.


It is always a good practice to initialize your variables. C# enforces it showing that message. No one can guaranty that your level variable will be assigned inside the while - as @AdaTheDev pointed out

0

精彩评论

暂无评论...
验证码 换一张
取 消