Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you need to call IDisposable, if you are using `using` statements?

Tags:

c#

.net

I was reading another answer. And it made me wonder, when do does one need to explicitly call Dispose if I am using using statements?

EDIT:

Just to vindicate myself from being a total know-nothing, the reason I asked was because someone on another thread said something implying there was a good reason to have to call Dispose manually... So I figured, why not ask about it?

like image 234
Alex Baranosky Avatar asked Nov 27 '22 21:11

Alex Baranosky


1 Answers

You don't. The using statement does it for you.


According to MSDN, this code example:

using (Font font1 = new Font("Arial", 10.0f)) 
{
    byte charset = font1.GdiCharSet;
}

is expanded, when compiled, to the following code (note the extra curly braces to create the limited scope for the object):

{
  Font font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}

Note: As @timvw mentioned, if you chain methods or use object initializers in the using statement itself and an exception is thrown, the object won't be disposed. Which makes sense if you look at what it will be expanded to. For example:

using(var cat = new Cat().AsDog())
{
   // Pretend a cat is a dog
}

expands to

{
  var cat = new Cat().AsDog(); // Throws
  try
  {
    // Never reached
  }
  finally
  {
    if (cat != null)
      ((IDisposable)cat).Dispose();
  }
}    

AsDog will obviously throw an exception, since a cat can never be as awesome as a dog. The cat will then never be disposed of. Of course, some people may argue that cats should never be disposed of, but that's another discussion...

Anyways, just make sure that what you do using( here ) is safe and you are good to go. (Obviously, if the constructor fails, the object won't be created to begin with, so no need to dispose).

like image 53
Svish Avatar answered Dec 10 '22 23:12

Svish