Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...