IDisposable and .NET Gabage Collection

Posted in C#, on 6/7/2013

One day I saw people write following code, a class holde list of properties and imprement IDisposable.

 public class BaseEntity : IDisposable
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime Date { get; set; }

        public void Dispose()

I was supprised, an experienced .NET developer will do this, because not only imprement IDisposable. It's not using it anywhere. I thought I was crazy and I might not know something new happening, and I searched entire solution no where is use it. I guess some .NET developer might have not understanding some basic stuff for .NET, at least I think.

using clause

like class Stream, Bitmap in C# .net, you will use using clause. By use using, so at the end of the using it will call the Dispose() method and imprement your own logic to release the resource. So I saw lots of .NET developer don't use using when there's IDisposable had been impremented. Because you don't want to use try catch and final, that's not good way of use a class which imprement IDisposable.

In additional, some developer said, "what happen if some developer doesn't use using, so if we imprement IDisposal, then it should be fine, right?". No, imprement IDisposal mean nothing for Gabage collector. Gabage will do nothing if you just imprement IDisposal. You have either use Using or call the Dispose() your self.

And more, above case you don't need to imprement IDisposal, why, It's managed class in C#! managed class basically mean every code is buildable in your solution could be Managed code, basically most likely if you use build-type in .NET to create any object it buildable mean managed. If that managed, .NET will handler all the memory release for you. 

I'm so sad when I have to explain this to developer who have many years of experience, lastly, I think most of time you don't have to imprement your own IDisposal unless you have to access some resource which is not managed code, like WinAPI, excel and some OS resource, out of appliction code base.

For more information, you can reference following as...

You can use .NET ~ destruction just for safty when IDisposal method failed, but if you have huge resource need to be release then imprement IDisposal.

Destruction in .NET

Imprement Disposal

Using Statement