Search code examples
c#.netidisposable

Calling a method inside using block


I've a class SomeDisposable and I'm using it in using block like this

using(var someDisposable = new SomeDisposable(1)) 
{

}

Can I change to something like

using (var someDisposable = Get(1))
{

}
public SomeDisposable Get(int x)
{
   return new SomeDisposable(x);
}

Would it impact the auto disposable ability?


Solution

  • The compiler will turn your first code into

    SomeDisposable someDisposable = new SomeDisposable(1);
    try
    {
    }
    finally
    {
        if (someDisposable != null)
        {
            ((IDisposable)someDisposable).Dispose();
        }
    }
    

    It will turn the second code into

    SomeDisposable someDisposable2 = Get(1);
    try
    {
    }
    finally
    {
        if (someDisposable2 != null)
        {
           ((IDisposable)someDisposable2).Dispose();
        }
    }
    public SomeDisposable Get(int x)
    {
       return new SomeDisposable(x);
    }
    

    (Source) As you can see, it doesn't make a difference. The finally block will be executed the very same way in both variants.