7

Coming from C++, returning a local variable was a bad idea (when allocated memory on the stack).

Now using C# I'm getting the impression it isn't a bad idea (when returning a value, not a reference).

Why is that? I understand C# uses the GC but I'm not sure what difference that would make in this case.

Ben Y
  • 291
  • 6
  • 14
  • 1
    Returning a local variable is not problematic in all cases (it is if the variable is a pointer to something that will not live after the function exits). Returning a **reference** to a local variable is problematic. – Mehrdad Afshari Mar 16 '14 at 03:34

1 Answers1

14

The problem in C/C++ is that you can return a pointer to data that is located on the stack. If you do that the pointer is invalid as soon as the stack frame is destroyed. In managed C# you can't do such a thing.

Returning locals in C# is fine. If you return a value type, the value is copied. If you return a reference, the reference itself is copied (but it still points to the same object on the heap). In either case, there's no issue.

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317