Вопрос

I have a method declaration like this:

public int myMethod(int x, out int y, out int z)
{
    int k;
    foreach(int i in someList)
    {
        if(anotherMethod(out k))
        {
            z = k;
        }
        else
        {
            z = 0;
        }
    }

    y = someValue;

    return anotherValue;
}

but I get this compiling error

The out parameter 'z' must be assigned to before control leaves the current method

Это было полезно?

Решение

If someList is empty, it will never enter the foreach loop, and therefore z will never be assigned. To resolve this, ensure that z is given a value regardless of of the contents of someList:

public int myMethod(int x, out int y, out int z)
{
    z = 0; // or whatever default value you like

    ...
}

However, you should probably consider refactoring this code. It's likely there's a better way to accomplish this. If you'd really like to return 3 different int values, you might consider using a Tuple<int, int, int> or creating a custom data type to represent the value.

Другие советы

Reason : out paramaeters must be initialised before returning from the function.

You are assigning value for parameter z inside if block so compiler could not identify whether it can be initialized or not hence initialize your parameter z before if block as below:

public int myMethod(int x, out int y, out int z)
{
    int k;
    z=0;
    foreach(int i in someList)
    {

        if(anotherMethod(out k))
        {
            z = k;
        }
        else
        {
            z = 0;
        }
    }

    y = someValue;

    return anotherValue;
}

If someList is empty, then z will never be assigned a value, which violates it's being an out variable. Remove the out constraint, or reconfigure your function logic.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top