2

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;
}
3
  • 2
    Given that in C# structs are allocated on the stack This a false assumption, and hence any conclusions you draw from it aren't meaningful. Commented Oct 9, 2017 at 15:56
  • 2
    Structs in C# are pass-by-value. You are not returning a reference here, so no. Commented Oct 9, 2017 at 15:56
  • @Sweeper All methods that aren't marked as ref in their return type return a value, all methods that are return a reference. The type is relevant, what matters is the signature of the method. Commented Oct 9, 2017 at 15:57

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

This wouldn't make sense either, since the local variable will go out of scope before it can be used. Such a thing is possible in C++, but it results in undefined behaviour and it is likely that the compiler notifies you of this mistake.
1

keyword struct in C# describes a 'value type'. When you return a value type from a method, it creates new copy of it. Beware of shallow copies, should that structure contain embedded containers (such as List<T>, ...)

2 Comments

Unless you use a ref return.
@Servy, particularly agree with you, but in this example he returns local variable. But, the return value cannot be a local variable in the method that returns it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.