When to use IDisposable

#1 Why?
IDisposable is a reliable, and expected destructor for your code.
It fires off immeadiately when you call it, rather than waiting for the Garbage Collector (GC) to Finalize, or (for C# users) ~myClassName().

#2 What should I put in it?
Release all of your managed objects, such as Connections, Readers, Streams, Form objects.

#3 I don’t have anything but primitives in my class, do I still need it?
Probably not, as long as you are resetting your primitives on the constructor.

However, if you put in, as your last line of code, GC.SuppressFinalize(this), then your GC will not waist time with the destructor of your object, after dispose is called. This is very important for server objects, especially web based applications.

#4 Can I write a Dispose method without using IDisposable?
Yes. However, if you are using a object broker of any kind, it will not recognise this as a disposable object, and Dispose will not get called.

Object test is “TypeOf IDisposable”.

#5 How do I use it?

public class SomeClass : IDisposable
{

public void SomeClass()
{//Constructor
}

public ~SomeClass()
{//Destructor
}

public void Dispose() //IDisposable.Dispose
{//IDisposable
GC.SuppressFinalize(this); //A sample of self cleanup
}

}

Any other questions can be left at the front desk. Have a nice day.

This entry was posted in Brian's Code Extreme and tagged , . Bookmark the permalink.

One Response to When to use IDisposable

  1. Pingback: Someone at MS reads my blogs | Brian By Experience

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.