C# - finalize() vs finally

In C# programming, finalize() and finally serve distinct purposes, and their differences can be highlighted through a simple example.

finalize() Method

  • Purpose: The finalize() method in C# is a special method used in garbage collection. It is called by the garbage collector on an object when the garbage collector determines that there are no more references to the object.
  • Usage: It's typically overridden to clean up unmanaged resources that the object might be holding onto, like file handles or database connections.

finally Block

  • Purpose: The finally block is part of exception handling in C#. It is used to execute code regardless of whether an exception is thrown or not.
  • Usage: It's typically used to release resources or to perform cleanup operations that should happen whether or not an error occurred in the try block.

Here's a simple example to illustrate their differences:


using System;

class Program
{
    static void Main()
    {
        try
        {
            Console.WriteLine("Inside try block");
            // Code that might throw an exception
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception caught: " + ex.Message);
        }
        finally
        {
            Console.WriteLine("Finally block executed");
            // Cleanup code goes here
        }
    }
}

class ExampleClass
{
    ~ExampleClass()
    {
        // This is the finalize method
        Console.WriteLine("Finalize method called");
        // Cleanup unmanaged resources here
    }
}
	
Output Explanation
  • When you run the Main method, it will execute the try block. If any exception occurs, it will be caught in the catch block, and regardless of whether an exception occurred or not, the finally block will always execute.
  • The output will include "Inside try block" and "Finally block executed", with the "Exception caught" part appearing only if an exception is thrown.
  • The ExampleClass demonstrates a destructor (or finalize method in C#). This will not produce an immediate output when an instance of ExampleClass is created and destroyed because it's up to the garbage collector to decide when to call the finalize method.

In summary, finalize() is used for cleaning up resources before an object is garbage collected, while finally is used to execute code regardless of whether an exception occurred.

Points to Remember:
finalize() Method
  • Garbage Collection: Involved in the garbage collection process and called automatically on objects no longer in use.
  • Resource Cleanup: Used for cleaning up unmanaged resources like file handles and network connections.
  • Not Explicitly Called: You do not call finalize() manually; it is called by the garbage collector.
  • Unpredictability: Execution time is uncertain and depends on the garbage collector.
  • Performance Overhead: Can lead to performance issues if overused or improperly used.
finally Block
  • Exception Handling: Part of the try-catch structure, used for code that must always execute.
  • Guaranteed Execution: Code inside the finally block always executes, regardless of exceptions.
  • Resource Release: Commonly used for releasing resources or cleanup operations.
  • No Return Statements: Avoid return statements inside finally to prevent confusing control flow.
  • Always Last: Executed last, even if there's an exception or a return statement in the try or catch blocks.