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

前端 未结 6 986
说谎
说谎 2020-11-30 14:19

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 ret         


        
6条回答
  •  隐瞒了意图╮
    2020-11-30 15:11

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

提交回复
热议问题