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?
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):
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
It complains because at the time of If statment the variable has not got any value.
just do
string strType = "";
This error means you didn't previously declare that variable. Just initialise those variables in the beginning of your while loop.
Example:
If you order your IF statements a little different, you can even avoid the reassigning of an empty value to the variable.
when declaring string strType you must assign a value, something like
More details: Compiler Error CS0165
be nice, use String.Empty;
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:
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?