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() { } } }