Sunday, June 16, 2013

Clean up unmanned code in C#

Introduction


The code then execute in CLR (Common Language Runtine) is called managed code. 

And the code execute outside the scope of CLR is known as unmanaged code. The examples of unmanaged code is COM component, some database call etc.

CLR is responsible for cleanup managed code. But for clean up unmanaged code we need to do some thing extra. C# provide us an interface called IDisposable which need to be implemented in those class where we used our unmanaged code. IDisposable interface has only one method

public void Dispose();


Example


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example_IDisposible
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ABC abc = new ABC())
            {
                // your code
            }
        }
    }

    public class ABC : IDisposable
    {
        // ------- your unmanaged code ---------- //

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        public void Dispose(bool val)
        {
            if (val)
            {
                // Clean up managed code
            }
            //Clean up unmanaged code, large variable
        }
        ~ABC()
        {
            Dispose(true);
        }
    }
}