- Finalize method is used for garbage collection. So before destroying an object this method is called as part of clean up activity by GC.
- Finally block is used in exception handling for executing the code irrespective of exception occurred or not.
Finalize:
In C#, "finalize" is used as a method name in the context of object finalization. The Finalize
method is automatically called by the garbage collector before an object is destroyed. It allows the object to perform any necessary cleanup operations.
Example:
csharp
class MyClass
{
~MyClass()
{
// Finalize method
// Perform cleanup operations here
}
}
Finally:
In C#, "finally" is used in exception handling to define a block of code that will be executed, regardless of whether an exception is thrown or not. The code inside the finally
block is executed after the try
block and any associated catch
blocks.Example:
csharp
try
{
// Code that may throw an exception
}
catch (Exception ex)
{
// Exception handling
}
finally
{
// Code that will be executed regardless of whether an exception occurred or not
}
In the above example, the code inside the finally
block will always be executed, even if an exception is thrown and caught in the catch
block or if the code executes without any exceptions. It is commonly used to release resources or perform cleanup actions that should always be done, such as closing files or releasing database connections.