Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "using" statement to dispose

Tags:

c#

.net

Does this make sense ?

Having a simple class

   class Test
   {
     public Test()
     {
        // Do whatever
     }
   }

and then instantiating it

using(new Test())
{
  // Nothing in here
}

The using statement is there just to make sure Test is disposed. When will it be disposed if I just call

new Test()
like image 833
Jla Avatar asked Aug 04 '10 07:08

Jla


People also ask

Does using Always dispose?

No it doesn't.

What statement describes a Dispose method?

C# provides a special "using" statement to call Dispose method explicitly. using statement gives you a proper way to call the Dispose method on the object. In using statement, we instantiate an object in the statement. At the end of using statement block, it automatically calls the Dispose method.

Why do we use the using statement?

The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations. The main goal is to manage resources and release all the resources automatically.


2 Answers

Test isn't IDisposable, so that won't even compile. But if it was disposable, yes using will do it, and new by itself won't. It is an unusual usage, but I've seen similar. Rarely.

Based on your comment (main question), I suspect that you are confusing garbage collection and disposal. There is no way to forcibly make something get collected, short of GC (which you should not do). Unless you have a really good reason to want it collected, just let it be - chances are it is "generation 0" and will be collected cheaply anyway.

Also, the "do whatever" suggests doing something in a constructor but not caring about the created object; a static method would be preferable:

public class Test { /* could be static */
     public static void DoSomething() { ... }
}
...
Test.DoSomething();
like image 57
Marc Gravell Avatar answered Sep 30 '22 11:09

Marc Gravell


By not assigning the instance to a variable, it will be eligible for GC as soon as it goes out of scope.

Or, is there something else you are trying to accomplish with this?

like image 38
Jordan S. Jones Avatar answered Sep 30 '22 10:09

Jordan S. Jones