It is generally recommended that you wrap something that implements IDisposable using the statement
using (var a = new HttpWebResponse(...)) { }
This is the equivalent of writing
var a = new HttpWebResponse(...); try {
Do I even have to take care if the object is null? I canβt just get rid of him anyway
Well no, because if you try to call Dispose on a null object, the application will throw a NullReferenceException . Given your circumstances, when you think the using statement is not a valid option, another neat way to remove it is to write an extension method, for example.
public static class Ext { public static void SafeDispose(this object obj) { if (obj != null) obj.Dispose(); } } ... var a = new ...; a.SafeDispose();
This will allow you to call the method on the null object.
James source share