C#: Use of unassigned local variable, using a fore

2020-01-27 08:15发布

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

标签: c#
6条回答
祖国的老花朵
2楼-- · 2020-01-27 08:32

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;
}
查看更多
▲ chillily
3楼-- · 2020-01-27 08:44

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2020-01-27 08:45

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;
查看更多
神经病院院长
5楼-- · 2020-01-27 08:46

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.

查看更多
甜甜的少女心
6楼-- · 2020-01-27 08:46

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.

查看更多
虎瘦雄心在
7楼-- · 2020-01-27 08:46

This can happen for all variable types as well.

For collections and objects, initialize using new.

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

查看更多
登录 后发表回答