开发者

C# - Error "not all code paths return a value" with an array as out parameter

I currently have the below code:

public int GetSeatInfoString(DisplayOptions choice, out string[] strSeatInfoStrings)

    {
        strSeatInfoStrings = null;
        int count = GetNumOfSeats(choice);

        if ((count <= 0))
            return 0;

        strSeatInfoStrings = new string[count];

        int i = 0;

 开发者_C百科       for (int index = 0; index <= m_totNumOfSeats - 1; index++)
        {
            if (string.IsNullOrEmpty(m_nameList[index]))
                strSeatInfoStrings[i++] =

m_nameList[index].ToString(); }

    }

This code produces an error of, "...GetSeatInfoString.DisplayOptions, out string[])': not all code paths return a value. Basically, what I am looking to do in the above method is to cycle through an array and for any values in the array that contain a string, I want these then adding to the new array, strSeatInfoStrings which in turn, can be called from a separate class and the new array content then displayed in a listbox.

Any suggestions on how to rectify this?

Thanks in advance


You have no final return before the method exits. You are exiting if there are no elements but you need a return at the end. If you are not interested in the value then why not set the return type to void?


You can add return strSeatInfoStrings.Length at the end

public int GetSeatInfoString(DisplayOptions choice, out string[] strSeatInfoStrings)

    {
        strSeatInfoStrings = null;
        int count = GetNumOfSeats(choice);

        if ((count <= 0))
            return 0;

        strSeatInfoStrings = new string[count];

        int i = 0;

        for (int index = 0; index <= m_totNumOfSeats - 1; index++)
        {
            if (string.IsNullOrEmpty(m_nameList[index]))
                strSeatInfoStrings[i++] =
m_nameList[index].ToString(); }

    return strSeatInfoStrings.Length;

    }


You need to return an integer value according to your methods signature.

After the for loop is where a value should be returned.


The error isn't anything to do with your out parameter.

Your method

public int GetSeatInfoString(
                   DisplayOptions choice, out string[] strSeatInfoStrings)

is declared as returning an int, and doesn't do this for all code paths.


You are only returning a value if count <= 0. Either you need to return a value after the for loop, or change the method signature to be void, depending on what you want the return value to represent.

If you want to return the array with the counts in, then change the return type to string[] and remove the out argument.


What value do you want to return from this function? I guess that you need to add this line to the end:

return i;

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜