C
C#2y 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;
}
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;
}
7 Replies
TheRanger
TheRanger2y ago
local variables gets deleted when the program exits the method
Aaron
Aaron2y ago
so, that span example isn't getting a ref to the array local it's getting a ref to the first item of the array, which is on the heap which has a lifetime longer than your method so it's fine to return
Anton
Anton2y ago
You can do the second thing if you pass that n as ref
uselessxp
uselessxp2y ago
is there a way, a tool, to see what happens to variables and other stuffs during the debug, or you have just know it by theory?
deem
deem2y ago
Debug > Windows > Locals
Anton
Anton2y ago
debugger
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.