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

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;
}

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.


That is because the compiler can't know that there always are any items in RssData. If it would be empty, the code in the loop would never be executed, and the variable would never be assigned.

Just set the variable to null when you create it, so that it always has a value:

string result = null;

If RssData has zero items, the loop will not run, leaving result undefined. You need to initialize it to something (e.g. string result = "";) to avoid this error.