How to Destroy Object in C#

Muhammad Maisam Abbas Feb 02, 2024
How to Destroy Object in C#

This tutorial will introduce the method to destroy a class object in C#.

Destroy Class Object by Assigning null Value in C#

The class object is a reference type variable in a C# program. It means that it is essentially a pointer that holds a reference to a class’s memory location. 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. It means that the object does not point to any memory location. The class object goes out of scope, and the garbage collector collects the garbage and deallocates the memory. The following code example shows us how we can destroy a class object by assigning a null value in C#.

using System;

namespace destroy_object {
  class Sample {
    public string Name { set; get; }
  }
  class Program {
    static void Main(string[] args) {
      Sample s = new Sample();
      s.Name = "Sample name";
      Console.WriteLine(s.Name);
      s = null;
    }
  }
}

Output:

Sample name

In the above code, we destroyed the object s of the Sample class with s = null in C#.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Csharp Class