What's different between "return new MyClass();" and "MyClass mc = new MyClass(); return mc;"

Is there a difference between the following methods of a class:

public MyClass GetMyClassInstance()
{
    return new MyClass();
}

and

public MyClass GetMyClassInstance()
{
    MyClass myClassObj = new MyClass();
    return myClassObj;
}

Does the second option is memory-leak proof ? or rather, what are the impacts of both the methods on memory-leak?

I may be wrong, but I know, there is no issue with memory-leak with both the methods. But still need to hear from experts here.

Jon Skeet
people
quotationmark

There's no significant difference at all. The latter is slightly more longwinded, but does allow you to easily inspect the value in the debugger before it's returned - that's about the only difference.

There's certainly no difference in terms of memory leakage. I'd expect that in an optimized build running under an optimizing JIT compiler you'd probably end up with the exact same native code. (The IL is slightly different even under an optimizing build, in that there's an extra stloc/ldloc pair in the second form, but the JIT could easily optimize that away.)

You should use whichever form you find most convenient, basically.

people

See more on this question at Stackoverflow