C# Error CS0245 – Destructors and object.Finalize cannot be called directly

C# Compiler Error

CS0245 – Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.

Reason for the Error

You will receive this error in your C# code when you try to call the object’s destructor or Finalize method directly.

For example, try compiling the below code snippet.

namespace DeveloperPubNamespace
{
    class Employee
    {
        void Cleanup()
        {
            // The below line causes the error code CS0245
            this.Finalize();  
        }
    }

    class Program
    {
        public static void Main()
        {
        }
    }
}

This program will result with the C# error code CS0245 because the Function Cleanup() makes a call to this.Finalize() directly which is not allowed.

Error CS0245 Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available. DeveloperPublish C:\Users\SenthilBalu\source\repos\ConsoleApp3\ConsoleApp3\Program.cs 8 Active

Solution

The C# compiler does not allow you to call the Finalize method directly. Instead, try using the IDisposable interface and implement the Dispose method as shown below.

using System;

namespace DeveloperPubNamespace
{
    class Employee :IDisposable
    {
        public void Dispose()
        {
            // Add your cleanup logic
        }

    }

    class Program
    {
        public static void Main()
        {
        }
    }
}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...