C# Finalize vs Dispose

Dispose is called explicitly by the developer. We can use Dispose method to release both managed and unmanaged resources. 

Finalize can only release unmanaged resources. Dispose is faster than finalize because it can be called Quickly and explicitly by the user and does not have to wait for the garbage collector to run.

Managed and unmanaged resources Example -

The term "unmanaged resource" is usually used to describe something not directly under the control of the garbage collector. For example, if you open a connection to a database server this will use resources on the server (for maintaining the connection) and possibly other non-.net resources on the client machine, if the provider isn't written entirely in managed code.

This is why, for something like a database connection, it's recommended you write your code thusly:

  1. using(var connection = new SqlConnection("_connectionString"))
  2. {
  3.  //Code to connect here
  4. }


As this ensures that Dispose() is called on the connection object, ensuring that any unmanaged resources are cleaned up.

Comments

Popular posts from this blog

C# | Association, Aggregation and Composition

Throw vs Throw ex in C#

String[] args in C#