Delete Object in C#

This tutorial will discuss the methods to delete an object of a user-defined class in C#.

Delete a User-Defined Class Object in C# by Assigning null Value to It

A class object is a reference variable that points to the memory location of that class. We can delete the object by assigning the null value to it. It means that the object currently contains no reference to any memory location. See the following example.

using System;

namespace delete_object
{
    public class Sample
    {
        public string value { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Sample x = new Sample();
            x.value = "Some Value";
            x = null;
            Console.WriteLine(x.value);
        }
    }
}

Output:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.

In the above code, we initialized the object x of the Sample class and assigned value to the value property. We then deleted the object by assigning null to x and printed the x.value property. It gives us an exception because x does not point to any memory location.

Another beneficial approach would be to call the garbage collector after we have deleted the object. This approach is illustrated in the code example below.

using System;

namespace delete_object
{
    public class Sample
    {
        public string value { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Sample x = new Sample();
            x.value = "Some Value";
            x = null;
            GC.Collect();
            Console.WriteLine(x.value);
        }
    }
}

In the above code, we called the garbage collector after assigning the null value to the x object with the GC.Collect() method 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.

Related Article - Csharp Object

  • Serialize an Object to XML in C#
  • Check if an Object Is Null in C#