C# return struct reference from method

夙愿已清 提交于 2020-05-24 05:08:12

问题


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;
}

回答1:


keyword struct in C# is allow to describe value type. When you return value type from method, it creates new copy of it.




回答2:


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.

– Disallow returning local variables by reference. This is the solution that was chosen for C#. - To guarantee that a reference does not outlive the referenced variable C# does not allow returning references to local variables by reference. Interestingly, this is the same approach used by Rust, although for slightly different reasons. (Rust is a RAII language and actively destroys locals when exiting scopes)

Even with the ref keyword, if you go ahead and try this:

public struct Test
{
    public int a;
}

public ref Test GetValueByRef()
{
    var test = new Test();
    return ref test;
}

You will see that the compiler errors out with the following:

Cannot return local 'test' by reference because it is not a ref local



来源:https://stackoverflow.com/questions/46650478/c-sharp-return-struct-reference-from-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!