C#C
C#3y ago
DaVinki

❔ Can someone help me fully understand ref returns?

I have not been able to get this through my head aside from a few things like never using a ref return if a variable does not exist outside of scope. What about something like keeping local variables alive through ref returns?

Seeing the Span<T> type do these things confuses me. How is it able to do something like this considering ref return constraints, knowing it's a ref struct only on the stack? It's local but the GC knows it's still in use after returning
    public static Span<int> SpanOf(int[] arr)
    {
        var span = new Span<int>(arr);
        return span;
    }

But you can't do anything like this which is what confuses me about the whole thing:
    public static ref int RefCopyOf(int n)
    {
        ref var refCopyOfN = ref n;
        return ref refCopyOfN;
    }
Was this page helpful?