There's an advice in C++: "Never Return a Reference to a Local Object", as below quoted from "C++ Primer":
"There's one crucially important thing to understand about returning a reference: Never return a reference to a local variable.
"When a function completes, the storage in which the local objects were allocated is freed. A reference to a local object refers to undefined memory after the function terminates. Consider the following function:
// Disaster: Function returns a reference to a local object
const string &manip(const string& s)
{
string ret = s;
// transform ret in some way
return ret; // Wrong: Returning reference to a local object!
}
"This function will fail at run time because it returns a reference to a local object. When the function ends, the storage in which ret resides is freed. The return value refers to memory that is no longer available to the program."
Question: so does this still apply to C#? or it doesn't matter as GC is introduced?
It is not possible to return references to local variables in .NET
See: Why doesn't C# support the return of references?
See also: Ref returns and ref locals (Eric Lippert's Blog)
C# language does not allow that. In C# there are two very different kinds of references:
1) References to classes and similar "Reference Types". Since the target of these is always allocated on the heap the reference will always be valid after returning.
2) References to local variables/parameters. Called managed references
in the CLR. For example:
void DoSomething(ref int i, ref object o)
You can't declare a return type that uses this kind of reference in C# (The CLR itself offers some restricted support for that). Since you can only pass them to other functions as parameters, can't store them in fields, and can't return them it's impossible to keep one of those around after the function returns. So once again using them is safe.
Basically in C# you can only use them for pass-by-reference parameters. Note that you can have a ref
to a reference type variable(ref object o
) but not a reference to a reference ref ref int i
.
Eric Lippert posted a blog entry on this kind of reference a few days ago detailing the problems with ref
return values: Ref returns and ref locals
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With