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

前端 未结 6 982
说谎
说谎 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: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.

提交回复
热议问题