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

I have an object, such as HttpWebResponse , that implements IDisposable and therefore needs to be deleted.

Having this:

 HttpWebResponse a = ....; 

What will be the correct way to handle the object?

 a.Dispose(); 

Or:

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

Do I even have to take care if the object is null? Can't I just destroy him?

+4
source share
2 answers

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 { // use a } finally { if (a != null) a.Dispose(); } 

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.

+9
source

first check if it is null and then delete, otherwise you will get an exception.

0
source

Source: https://habr.com/ru/post/1488948/


All Articles