No. The using statement does this for you.
According to MSDN , this code example:
using (Font font1 = new Font("Arial", 10.0f)) { byte charset = font1.GdiCharSet; }
when compiling, it expands to the following code (pay attention to additional curly brackets to create a limited area 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 is mentioned , if you bind methods or use object initializers in the using declaration itself and throw an exception, the object will not be deleted. It makes sense if you look at what it will be expanded to. For instance:
using(var cat = new Cat().AsDog()) {
expands to
{ var cat = new Cat().AsDog(); // Throws try { // Never reached } finally { if (cat != null) ((IDisposable)cat).Dispose(); } }
AsDog will obviously make an exception, as a cat can never be as amazing as a dog. The cat will never be removed. Of course, some people may argue that cats should never be removed, but this is another discussion ...
In any case, just make sure that what you do using( here ) is safe and that you are good to go. (Obviously, if the constructor does not work, the object will not be created to begin with, so there is no need to dispose of it).
source share