Why cannot return a nested ref return result if the inner method has another ref/out parameter?

为君一笑 提交于 2021-02-19 05:05:48

问题


I thought I understood limitations of ref returns as well as escaping scopes.

But now I found a case and I don't get why is it illegal. It seems that ref return cannot be used if the value to return comes from a nested method with any ref/out arguments.

public static ref T RefReturn<T>()
{
    ref T result = ref GetResult<T>(normalParam: default); // compiles
    // ref T result = ref GetResult<T>(out bool outParam); // CS8157 at the return statement
    // ref T result = ref GetResult<T>(boxedParam: new StrongBox<bool>()); // a suboptimal workaround

    // ... code

    return ref result;
}

// the bodies below are just dummy examples
private static ref T GetResult<T>(bool normalParam) => ref (new T[1])[0];

// note that this method compiles in itself but unlike in case of the the previous method
// it is illegal to return its result again
private static ref T GetResult<T>(out bool outParam)
{
    outParam = true;
    return ref (new T[1])[0];
}

// though a ref/out parameter does not work we can mimic something similar without
// making it impossible to return its result from a caller
private static ref T GetResult<T>(StrongBox<bool> boxedParam)
{
    boxedParam.Value = true;
    return ref (new T[1])[0];
}

I can live with the workaround but I don't understand how an independent by-ref argument makes this solution harmful. AFAIK they must not be dangerous to the inner ref result; otherwise, the inner method itself should trigger some error, too. Or am I wrong? What do I miss?

Here is the live example of the code sample above.

来源:https://stackoverflow.com/questions/65613857/why-cannot-return-a-nested-ref-return-result-if-the-inner-method-has-another-ref

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!