Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Use of unassigned local variable, using a foreach and if

Tags:

c#

I have this following code:
I get the error, "Use of un-Assigned Local variable" I'm sure this is dead simple, but im baffled..

    public string return_Result(String[,] RssData, int marketId)
    {
        string result;
        foreach (var item in RssData)
        {
            if (item.ToString() == marketId.ToString())
            {
                result = item.ToString();
            }
            else
            {
                result = "";
            }

        }
        return result;
    }
like image 640
Anil Avatar asked Jul 03 '11 18:07

Anil


2 Answers

Initialize result when you declare it. If the collection is empty neither of the branches of the if statement will ever be taken and result will never be assigned before it is returned.

public string return_Result(String[,] RssData, int marketId)
{
    string result = "";
    foreach (var item in RssData)
    {
        if (item.ToString() == marketId.ToString())
        {
            result = item.ToString();
        }
    }
    return result;
}
like image 128
tvanfosson Avatar answered Sep 30 '22 01:09

tvanfosson


If there are no items in RssData, then result will have never been set, and thus invalid.

Either initialize result (e.g., string result = null;) or consider that in your design by checking for emptiness, and setting or returning a failure state in that scenario.

like image 21
pickypg Avatar answered Sep 30 '22 00:09

pickypg