In C++, returning a reference of an object allocated on the stack in a method, yields garbage values due to the fact, that the stack object is destroyed as soon the method leaves the scope. Given that in C# structs are allocated on the stack, would this yield garbage values as well?
struct Test
{
//data
}
Test Foo()
{
Test t1 = new Test();
return t1;
}
I think you should read this: http://mustoverride.com/ref-returns-and-locals/
In short, the C# Design team decided to disallow returning local variables by reference.
Even with the
ref
keyword, if you go ahead and try this:You will see that the compiler errors out with the following:
keyword struct in C# is allow to describe value type. When you return value type from method, it creates new copy of it.