Windows Develop Bookmark and Share   
 index > Windows Forms General > Dispose and custom components
 

Dispose and custom components

I am designing a custom component (Non visible componenent). I inherited my class from System.ComponentModel.Component class. I know Component implements IDisposable. But how could I release resources used by my control ? Component class doesn't allow overriding Dispose. So how to dispose the objects used in my custom control ? Do I need to implement IComponent directly in my custom control instead of inheriting it from Component class ?

Thanks
Navaneeth  Friday, April 11, 2008 1:50 PM

Like below; basically, there is a pattern that IDisposable and finalizer (~Foo) share an implementation; the bool parameter tells you which it is... so you should only normally do your code in the "true" case (unless you are touching unmanaged resources):

Code Snippet

class Foo : Component

{

protected override void Dispose(bool disposing)

{

if (disposing)

{

// your code

}

base.Dispose(disposing);

}

}

Marc Gravell  Friday, April 11, 2008 1:55 PM

Like below; basically, there is a pattern that IDisposable and finalizer (~Foo) share an implementation; the bool parameter tells you which it is... so you should only normally do your code in the "true" case (unless you are touching unmanaged resources):

Code Snippet

class Foo : Component

{

protected override void Dispose(bool disposing)

{

if (disposing)

{

// your code

}

base.Dispose(disposing);

}

}

Marc Gravell  Friday, April 11, 2008 1:55 PM
Thanks Marc, But Component class won't allow to override Dispose(), or am I missing something ?
Navaneeth  Friday, April 11, 2008 1:57 PM

Code Snippet

class Foo :Component , IDisposable

{

protected override void Dispose(bool disposing)

{

if (disposing)

{

// your code

}

base.Dispose(disposing);

}

new public void Dispose()

{

base.Dispose();

}

}

David M Morton  Friday, April 11, 2008 2:06 PM

But it will allow you to override Dispose(bool disposing)... i.e. what I posted. Does this not compile for you? Works fine here...

(what version of .NET are you using?)

Marc Gravell  Friday, April 11, 2008 2:06 PM
Hi,

Thanks. Your code compiled correctly. I haven't noticed it. When I given the override, VS shows the intelisence in which Dispose(bool) was not listed. This was the confusion. Anyway thanks for solving that.
Navaneeth  Friday, April 11, 2008 2:10 PM

You can use google to search for other answers

Custom Search

More Threads

• Checking a event handler exists
• Creating a login form
• Redrawing buttons...using inheritance
• The button question
• Mutli frame images?
• increasing resolution disperses position of controls in a windows form app. why?
• Regarding DataGrid
• Using Keyboard and Mouse Hooks
• "not statement" error - VS prob or what?
• gridview validating event