Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destroy an object in C#

Tags:

c#

object

How to destroy an object in finally block.

For example

 Public void fnName()
 {
    ClassName obj = new ClassName();
    try {

    }
    catch() {

    }
    finally {
        // destroy obj here
    }
 }
like image 769
sajbeer Avatar asked Sep 10 '14 12:09

sajbeer


People also ask

How do you destroy an object in C++?

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.

Can you destroy an object in C#?

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.

Which function is used to destroy object?

Destructor function is automatically invoked when the objects are destroyed.

What is destroy in C#?

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() { ... } }


1 Answers

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
}
like image 166
MarkO Avatar answered Oct 05 '22 03:10

MarkO