Search code examples
c#garbage-collectiontry-finally

Is using try/finally a good practice for memory management?


One of my senior told me to use try/ finally block for all the methods to clear the initialized objects data. for eg:

var serviceProxy = new NotificationServiceProxy();
try
{
     return serviceProxy.GetNotifications(userID, request.Filters, request.FilterProperty, usertypeid);
}
finally
{
     serviceProxy = null;
}

Is that a good practice? if i'm using try/ catch for all my methods to clear the initialized objects data.


Solution

  • Not in C#, use using instead:

    using(var serviceProxy = new NotificationServiceProxy()){
        serviceProxy.GetNotifications(userID, request.Filters, request.FilterProperty, usertypeid);
        // Do stuff with the service proxy
    }
    
    // serviceProxy has now been cleaned up
    

    This is the pattern to ensure that IDisposable variable get cleaned up.

    For instances that aren't disposable this isn't needed - just let them pass out of scope and leave it to the GC.

    If NotificationServiceProxy uses lots of resources and you need to be sure that it is finalised correctly then make it disposable and always wrap it in a using or in another class that also implements IDisposable. If it doesn't then this try-finally pattern is a waste of time.