3

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?

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
PipBoy
  • 1,127
  • 4
  • 11
  • 16
  • 2
    where do you declare strType? – Zaki May 04 '12 at 13:20
  • Are you 100% you are getting an error and not a warning? I honestly would simply get rid of the variable and simply check the value of `rsData["TYPE"].ToString().Trim()` considering the performance costs of the doing so are trivial. – Security Hound May 04 '12 at 14:30

6 Answers6

16

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

string strType = null;

More details: Compiler Error CS0165

jorgehmv
  • 3,633
  • 3
  • 25
  • 39
  • Do I have to implicitly define them as null? I've declared the strings at the beginning of the code but not specifically stated them as null. – PipBoy May 04 '12 at 13:24
  • yes, you need to explicitly assign any value at the moment of the declaration or before the variable is used in a sentence (in your case a if statement) you can assign either null, string.Empty, "", etc – jorgehmv May 04 '12 at 13:25
  • 1
    This answer is seems misleading - there is no need to always assign a variable, providing that in the code-paths where it is not assigned, it is never used. The code could be fixed just as easily (and potentially more correctly) by putting "else { continue; }" on the first "if". – Iridium May 04 '12 at 13:32
  • Thanks - worked perfectly and I've learnt something for the future! – PipBoy May 04 '12 at 13:34
  • @Iridium I think that simply assigning a value in the declaration is clearer and simpler than adding "else { continue; }" sentence – jorgehmv May 04 '12 at 13:34
  • @jorgehmv Based on the code we've been given, a null TYPE results in none of the following "if" statements being executed. Assuming this is the whole code for the row-processing loop, it seems to me that by putting "else { continue; }" it's making it much clearer that no further processing occurs on this row, otherwise it's necessary to read all of the following code to determine this. – Iridium May 04 '12 at 13:42
  • @Iridium - You are 100% correct. Which is the reason I have to downvote this answer. It also has to do with the fact the user didn't explain the reason you have to assign a value. As you point out, you don't actually have to, considering a string variable already has a default value. – Security Hound May 04 '12 at 14:32
  • The answer works, it solved the problem, it does not matter that string has null as default value (everything has a default value in c#). I do not agree with the downvote – jorgehmv May 04 '12 at 15:00
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?

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • The potential side-effect with the code you provided is that if the dataset contains rows with null TYPEs interspersed with non-null ones, the value of TYPE from the previous non-null row will be used whenever a row with a null TYPE is encountered (providing there has been at least one row with non-null TYPE processed so far), which may or may not be desired. – Iridium May 04 '12 at 13:37
  • @Iridium: I understand your point, but I didn't dig into the code flow, but express a concept. The correct **default** value has to be chose by OP itself. If you note, while loop is not complete in code provided, so... – Tigran May 04 '12 at 13:40
0

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();
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
0

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

just do string strType = "";

Zaki
  • 5,540
  • 7
  • 54
  • 91
0

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.

Styxxy
  • 7,462
  • 3
  • 40
  • 45
-1

be nice, use String.Empty;

string strType=String.Empty;
user1208484
  • 110
  • 2
  • 2
    This doesn't explain the reason for his error, so the answer is sort of useless, the default value of a string is already an empty string. – Security Hound May 04 '12 at 14:27