"Ref-safe-to-escape examples"

// References passed in as fields on ref-struct parameters have ref-safe-to-escape scopes of "calling method".
// This makes sense because clearly the references ALREADY exist outside this method, they were set when they were passed in.
static ref int CallingMethodExample(SomeRefStructType s1, SomeRefStructType s2) {
	s2.AnIntegerRefField = ref s1.AnIntegerRefField; // 'ref s1.AnIntegerRefField' has a ref-safe-to-escape scope of "calling method", so this is permitted
	return ref s1.AnIntegerRefField;  // 'ref s1.AnIntegerRefField' has a ref-safe-to-escape scope of "calling method", so this is permitted
}

// References passed in directly to methods as parameters have ref-safe-to-escape scopes of "return only".
// "Return only" scope lies somewhere inbetween "current method" and "calling method" -- the ref is allowed
// to escape the current method but ONLY via return statement.
static ref int ReturnOnlyExample(ref int x, SomeRefStructType s) {
	s.AnIntegerRefField = ref x; // 'ref x' has a ref-safe-to-escape scope of "return only", so this does not compile
	return ref x; // 'ref x' has a ref-safe-to-escape scope of "return only", so this is permitted
}

// References to stack variables will always have a ref-safe-to-escape scope of "current method"
// (meaning those references can exist only within the current method but may not escape any further).
static ref int CurrentMethodExample(SomeRefStructType s) {
	var x = 123;
	s.AnIntegerRefField = ref x; // 'ref x' has a ref-safe-to-escape scope of "current method", which means the reference is NOT allowed to escape OUTSIDE the current method, so this does not compile
	return ref x; // 'ref x' has a ref-safe-to-escape scope of "current method", which means the reference is NOT allowed to escape OUTSIDE the current method, so this does not compile
}


Code snippet taken from "Complete C# Quick Reference - C# 11".