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()
No it doesn't.
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.
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.
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();
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With