© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
10 replies
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;
    }
    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;
    }
    public static ref int RefCopyOf(int n)
    {
        ref var refCopyOfN = ref n;
        return ref refCopyOfN;
    }
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ Can someone help me understand this?
C#CC# / help
2w ago
✅ Can someone help me understand GetType()
C#CC# / help
4mo ago
can someone help me read and understand this
C#CC# / help
2y ago
Can someone please help me understand this StackOverflow answer?
C#CC# / help
4y ago