In this article, I will explain the difference between the “Finalise” And “Finally” Methods In .NET
These two are different concepts in .NET, and they are used for different purposes.
Finalize
Finalize
is a method that is part of the .NET object lifecycle. It is automatically called by the garbage collector before an object is removed from memory. The purpose of the Finalize
method is to release any unmanaged resources that the object is holding, such as file handles, database connections, or network sockets. The Finalize
method cannot be called explicitly, and it does not return any value.
Example:
public class MyClass { private FileStream _file; public MyClass() { _file = new FileStream("data.txt", FileMode.Create); } ~MyClass() { if (_file != null) { _file.Dispose(); _file = null; } } }
In this example, the MyClass
object has a FileStream
object _file
as a member variable. The FileStream
an object is created in the constructor of MyClass
. The ~MyClass()
method is the Finalize
method of the class, and it is called by the garbage collector before the object is removed from memory. The purpose of the Finalize
method is to release the file handle held by the _file
object by calling the Dispose
method. This ensures that the file is properly closed and resources are released.
finally
finally
is a keyword used in a try-catch-finally block. The purpose of the finally
block is to ensure that certain code is executed, regardless of whether an exception is thrown or not. The code in the finally
block is always executed, regardless of whether the code in the try
block is executed successfully or not. The finally
block is optional, but if it is present, it must be placed after the catch
block. The finally
block can be used to release resources that were acquired in the try
block, such as file handles, database connections, or network sockets.
Example:
try { // some code that may throw an exception } catch (Exception ex) { // handle the exception } finally { // this code is always executed, regardless of whether an exception was thrown or not Console.WriteLine("Finally block executed."); }
In this example, the try
block contains some code that may throw an exception. If an exception is thrown, the catch
block handles the exception. Regardless of whether an exception was thrown or not, the code in the finally
block is always executed. In this case, the finally
block simply writes a message to the console to indicate that it has been executed.