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

前端 未结 6 961
说谎
说谎 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 14:59

    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.

    0 讨论(0)
  • 2020-11-30 15:01

    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.

    0 讨论(0)
  • 2020-11-30 15:08

    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;
    
    0 讨论(0)
  • 2020-11-30 15:09

    This can happen for all variable types as well.

    For collections and objects, initialize using new.

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

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-11-30 15:12

    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.

    0 讨论(0)
提交回复
热议问题