开发者

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

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()开发者_Python百科;
            }
            else
            {
                result = "";
            }

        }
        return result;
    }


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.


Change your line from

string result;

To

string result = string.Empty; // or null depending on what you wish to return (read further)

The compiler is just saying "Hey, you are using result and it has not been assigned yet!". This even ocurrs when you are assigning it for the first time, if you're not doing so in the initial instantiation.

You will also want to consider how you need to handle your code if you return an empty string, due to your array argument being passed in empty. You could choose to return an empty string, or a null value. This is just a behaviorial decision.


This can happen for all variable types as well.

For collections and objects, initialize using new.

eg. List<string> result = new List<string>();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜