1.

What is the difference between dispose() and finalize() methods in C#?

Answer»

Both dispose() and finalize() methods are used for unallocating and freeing up resources but:


  • dispose() method is called explicitly by the user, whereas finalize() method is called the system’s garbage collector at the end of execution.

  • dispose() method is defined in the IDisposable interface, whereas the finalize() method is defined in the Object class.

  • dispose() method is a part of the developer’s code, whereas finalize() method is a system-defined default method and not a part of the developer’s code.

BASIS FOR COMPARISONDISPOSE( )FINALIZE( )
Definitiondispose() method is defined in IDisposable interface.finalize() method is defined in java.lang.object class.
Syntax public void dispose( ){
// Dispose code here
}
protected void finalize( ){
// finalization code here
}
Invokeddispose() method is invoked by the user.finalize() method is invoked by the garbage collector.
Purposedispose() method is used to free unmanaged resources upon invoking.finalize() method is used to free the unmanaged resources when invoked by the garbage collector.
Implementationdispose() method is implemented whenever there is a close( ) method.Unlike dispose(), the finalize() method is implemented for freeing up unmanaged resources.
Access Specifierdispose() method is declared as public.finalize() method is declared as private.
Performancedispose() method happens instantly and hence is faster.finalize() method is slower in comparison with dispose() method and can affect the performance.



Discussion

No Comment Found