Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
final, finally and finalize in C#
In C#, the terms final, finally, and finalize serve different purposes. While final doesn't exist in C#, finally and finalize are crucial concepts for exception handling and resource cleanup respectively.
final (sealed in C#)
C# does not have a final keyword like Java. Instead, C# uses the sealed keyword to achieve similar functionality −
public sealed class SealedClass {
// cannot be inherited
}
public override sealed void SealedMethod() {
// cannot be overridden further
}
The sealed keyword prevents overriding of methods or inheritance of classes. When applied to a method, it must be an overridden method in a derived class.
Example
using System;
public class BaseClass {
public virtual void Display() {
Console.WriteLine("Base class method");
}
}
public class DerivedClass : BaseClass {
public override sealed void Display() {
Console.WriteLine("Derived class sealed method");
}
}
// This would cause a compilation error:
// public class FurtherDerived : DerivedClass {
// public override void Display() { } // Error: Cannot override sealed method
// }
public class Program {
public static void Main() {
DerivedClass obj = new DerivedClass();
obj.Display();
}
}
The output of the above code is −
Derived class sealed method
finally
The finally block executes regardless of whether an exception occurs or not. It's commonly used for cleanup operations like closing files, database connections, or releasing resources.
try {
// code that might throw exception
}
catch (Exception ex) {
// exception handling
}
finally {
// cleanup code - always executes
}
Example
using System;
public class Program {
public static void Main() {
try {
Console.WriteLine("Inside try block");
int result = 10 / 0; // This will throw exception
Console.WriteLine("This won't execute");
}
catch (DivideByZeroException ex) {
Console.WriteLine("Exception caught: " + ex.Message);
}
finally {
Console.WriteLine("Finally block always executes");
}
Console.WriteLine("Program continues...");
}
}
The output of the above code is −
Inside try block Exception caught: Attempted to divide by zero. Finally block always executes Program continues...
finalize
The Finalize() method is called by the garbage collector before an object is destroyed. It's used to clean up unmanaged resources like file handles, database connections, or native memory allocations.
~ClassName() {
// finalize code
// cleanup unmanaged resources
}
Example
using System;
public class ResourceManager {
private bool disposed = false;
public ResourceManager() {
Console.WriteLine("Resource allocated");
}
~ResourceManager() {
Console.WriteLine("Finalizer called - cleaning up resources");
Cleanup();
}
private void Cleanup() {
if (!disposed) {
Console.WriteLine("Cleaning up unmanaged resources");
disposed = true;
}
}
public void Dispose() {
Console.WriteLine("Dispose called explicitly");
Cleanup();
GC.SuppressFinalize(this);
}
}
public class Program {
public static void Main() {
ResourceManager rm1 = new ResourceManager();
rm1.Dispose(); // Explicit cleanup
ResourceManager rm2 = new ResourceManager();
// rm2 will be finalized by GC
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
The output of the above code is −
Resource allocated Dispose called explicitly Cleaning up unmanaged resources Resource allocated Finalizer called - cleaning up resources Cleaning up unmanaged resources
Comparison
| Concept | C# Equivalent | Purpose | When Used |
|---|---|---|---|
| final | sealed | Prevent inheritance/overriding | Class or method declaration |
| finally | finally | Guaranteed execution of cleanup code | Exception handling |
| finalize | ~ClassName() | Clean up unmanaged resources | Before garbage collection |
Conclusion
While C# doesn't have a final keyword, it uses sealed for similar functionality. The finally block ensures code execution regardless of exceptions, while finalize provides a last chance to clean up unmanaged resources before garbage collection.
