Home > Back-end >  Calling a method inside using block
Calling a method inside using block

Time:11-24

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?

CodePudding user response:

No, it would not impact the auto disposable ability. A using block will call Dispose on the wrapped object at the end of the block, regardless of whether that object was created using the new X(...) syntax or was returned from another method.

CodePudding user response:

Both code fragments will behave the same, you're just fiddling with some object references but this won't change the scope of the using statement in this case.

CodePudding user response:

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.

  • Related