Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to check if the object is null before a dispose() command?

I have an object, for example HttpWebResponse ,that implements IDisposable, and therefore should be disposed.

Having this:

HttpWebResponse a = ....;  

What will be the correct way of handling the object?

a.Dispose(); 

Or:

if (a!= null)
    a.Dispose();  

Should I even care if the object is null? Can't I just Dispose it anyway?

like image 785
user990635 Avatar asked Jun 30 '13 12:06

user990635


1 Answers

It's generally recommend to wrap anything which implements IDisposable with the using statement

using (var a = new HttpWebResponse(...))
{
}

It's the equivalent of writing

var a = new HttpWebResponse(...);
try
{
   // use a
}
finally
{
    if (a != null)
        a.Dispose();
}

Should I even care if the object is null? Can't I just Dispose of it anyway

Well no, because if you attempt to call Dispose on a null object the application will throw a NullReferenceException. Given your circumstance where you feel the using statement isn't a valid option another neat of way tidying this up is to write an extension method e.g.

public static class Ext
{
    public static void SafeDispose(this object obj)
    {
        if (obj != null)
            obj.Dispose();
    }
}
...
var a = new ...;
a.SafeDispose();

This then would allow you to call the method on a null object.

like image 192
James Avatar answered Oct 15 '22 21:10

James