Search code examples
c#disposeidisposable

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?


Solution

  • 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.