How to destroy an object in finally block.
For example
Public void fnName()
{
ClassName obj = new ClassName();
try {
}
catch() {
}
finally {
// destroy obj here
}
}
In C++, the operator delete destroys an object by calling its destructor, and then deallocates the memory where that object was stored. Occasionally, however, it is useful to separate those two operations. [1] Destroy calls an object's destructor without deallocating the memory where the object was stored.
Unfortunately, there is no such thing as destroying an object in C#. We can only dispose of an object in C#, which is only possible if the class implements IDisposable . For the objects of any other class types, we have to assign a null value to the class object.
Destructor function is automatically invoked when the objects are destroyed.
In C#, destructor (finalizer) is used to destroy objects of class when the scope of an object ends. It has the same name as the class and starts with a tilde ~ . For example, class Test { ... //destructor ~Test() { ... } }
Do nothing. Your reference (obj) will go out of scope. Then the Garbage Collector will come along and destroy your object.
If there are (unmanaged) resources that need to be destroyed immediately, then implement the IDisposable interface and call Dispose in the finalize block. Or better, use the using statement.
EDIT
As suggested in the comments, when your ClassName implements IDisposable, you could either do:
ClassName obj = null;
try{
obj = new ClassName();
//do stuff
}
finally{
if (obj != null) { obj.Dispose(); }
}
Or, with a using statement:
using (var obj = new ClassName())
{
// do stuff
}
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