Search code examples
c#using

Will using destroy data if return will be inside


While working on my project, I was wondering, will using auto-destruct data if return will be inside of a using.

Example block of code:

using(ManagedObject obj = new ManagedObject()) 
{
    int usualNumber = 0;

    // some magic stuff
    ...
    // magic stuff ends

    return usualNumber; // return goes inside of 'using' brackets
}

And here is the question, will our ManagedObject which implements IDisposable be disposed by 'using' statement?


Solution

  • using is a Syntactic sugar, it need to contain an object which implements IDisposable interface when you leave the using scope .net will call the IDisposable.Dispose method Automatically.

    Here is a sample c# online

    when the program leave Test method. .net will call IDisposable.Dispose method Automatically