sajbeer
sajbeer

Reputation: 201

Destroy an object in C#

How to destroy an object in finally block.

For example

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

    }
    catch() {

    }
    finally {
        // destroy obj here
    }
 }

Upvotes: 13

Views: 105560

Answers (2)

Neel
Neel

Reputation: 11731

First of all, there is nothing called Destroy in C# language. Instead, we call Dispose.

The Garbage Collector automatically executes cleanup procedures when an object goes out of scope but for the unmanaged resources like sockets, db calls etc and you need to Dispose the object as shown below:

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

    }
    catch()
    {

    }
    finally
    {
       obj.Dispose();
    }
}

...and implement Dispose functionality in your class as shown below:

      /// <summary>
      /// Dispose all used resources.
      /// </summary>
      public void Dispose()
      {
          this.Dispose(true);
          GC.SuppressFinalize(this);
      }

        /// <summary>
        /// Dispose all used resources.
        /// </summary>
        /// <param name="disposing">Indicates the source call to dispose.</param>
        private void Dispose(bool disposing)
        {
            if (this.disposed)
            {
                return;
            }

            if (disposing)
            {
                ////Number of instance you want to dispose
            }
        }

Another way to hinder the lifespan of an object is to write your code inside a using block as shown below:

using(var obj = new ClassName())
{
}

For more details for using check it here

Upvotes: 8

MarkO
MarkO

Reputation: 2233

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
}

Upvotes: 36

Related Questions