Use of unassigned local variable - if statements

2019-05-21 19:25发布

问题:

I'm doing the following block of code and the compiler is complaining about unassigned local variables and could use some help identifying what's up.

while (rsData.Read())
{
    if (rsData["TYPE"] != DBNull.Value)
        strType = rsData["TYPE"].ToString().Trim();


    if (strType == "01")
    {
        if (rsData["Text"] != DBNull.Value)
            strwho = rsData["Text"].ToString();

        if ((strwho.Length < 10 || (strwho.IndexOf("NULL") > 1)))
            strwho = "";
    }
    else if (strType == "07")
    {
        if (rsData["Text"] != DBNull.Value)
            strmetades = rsData["Text"].ToString();

        if ((strmetades.Length < 10 || (strmetades.IndexOf("NULL") > 1)))
            strmetades = "";
    }

It complains on all of the 'if (strType == "01")' lines and I'm not sure what's up. I've thought of using a switch for this but that seems to get the same issue also.

Any ideas?

回答1:

when declaring string strType you must assign a value, something like

string strType = null;

More details: Compiler Error CS0165



回答2:

The reason for this is that you are not assign strType variable to any value before you use it. According to C# compiler rules you must assign variable to any value before you begin to use it in any way.

In other words, what should be enough is assign an empty string before consditions, like shit for example:

strType = srting.Empty; //at least one value is already assigned!

while (rsData.Read())
{
    .... //your code here
}

Why this? To avoid ambiguity and not clear code presentation.

More on this, dierctly read a small article from Eric Lippert: Why are local variables definitely assigned in unreachable statements?



回答3:

It complains because at the time of If statment the variable has not got any value.

just do string strType = "";



回答4:

You should assign some value to local variable before you use it. You can initialize it in place where you declare it (before while block):

var strType = ""; // or null

Or (if you don't want strType to remember its value from previous iteration), make sure it gets initial value both when reader contains data, or when there is DbNull

strType = rsData["TYPE"] == DBNull.Value ? "" : rsData["TYPE"].ToString().Trim();


回答5:

be nice, use String.Empty;

string strType=String.Empty;


回答6:

This error means you didn't previously declare that variable. Just initialise those variables in the beginning of your while loop.

Example:

while (rsData.Read())
{
    string strType = string.Empty;
    string strwho = string.Empty; // Do this if you have the same error for strwho
    string strmetades = string.Empty; // Do this if you have the same error for strmetades

    // Your other code comes here
}

If you order your IF statements a little different, you can even avoid the reassigning of an empty value to the variable.