Search code examples
c#parametersheap-memoryout

C# out-parameter


What is the difference between the following two code snippets?

public void foo(out classA x)
{
    y = new classA();
    x = y;
}

and the second:

public void foo(out classA x)
{
    classA y;
    x = y;
}

Is it true that the second snippet is dangerous, because x has now a reference to this local y, which might be already dead after exiting foo?

Why do we have to use "new" in general?

I'm a bit confused, because in C++, if x in the second snippet would be a pointer, the statement x = y would not even compile since y is not a pointer.


Solution

  • Your confusion, I think, is that in C++ the second example would return a reference to a stack-allocated object. That doesn't happen in C#.

    Given your second example in C#:

    public void foo(out classA x)
    {
      classA y;  // Doesn't allocate an object
      x = y;
    }
    

    This probably won't compile, anyway, because y is never assigned a value.