What is the Finalize() and Dispose() methods in C#?
Arun Singh
Finalize: 1. Finalize() belongs to the Object class. 2. It is automatically called by the Garbage Collection mechanism when the object goes out of the scope(usually at the end of the program 3. It is slower method and not suitable for instant disposing of the objects. 4. It is non-deterministic function i.e., it is uncertain when Garbage Collector will call Finalize() method to reclaim memory. 5. Example: class employee { //This is the destructor of emp class ~employee() { } //This destructor is implicitly compiled to the Finalize method. } Dispose: 1. Dispose() belongs to the IDisposable interface 2. We have to manually write the code to implement it(User Code) ex: if we have emp class we have to inherit it from the IDisposable interface and write code. We may have to suppress the Finalize method using GC.SuppressFinalize() method. 3. Faster method for instant disposal of the objects. 4. It is deterministic function as Dispose() method is explicitly called by the User Code. 5. Example: user interface Controls. Forms, SqlConnection class have built in implementaion of Dispose method. try { string constring = "Server=(local);Database=my; User Id=sa; Password=sa"; SqlConnection sqlcon = new SqlConnection(constring); sqlcon.Open(); // here connection is open // some code here which will be execute } catch { // code will be execute when error occurred in try block } finally { sqlcon.Close(); // close the connection sqlcon.Dispose(); // detsroy the connection object }