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#.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.