views:

5279

answers:

6

I have a class which implements UserControl. In .NET 2005, a Dispose method is automatically created in the MyClass.Designer.cs partial class file that looks like this:

  protected override void Dispose(bool disposing)
  {
     if (disposing && (components != null))
     {
        components.Dispose();
     }
     base.Dispose(disposing);
  }

If I want to add my own Dispose functionality, where would I put it? Since this file is generated, I don't want to add code here and risk it getting blown away.

+4  A: 

I believe in this case the code-generator honors your code. It should be safe to put it in the codebehind.

Micah
+2  A: 

In VS 2005 (and 2008) you can update the Dispose method and it will not get removed when you edit the control from the designer.

akmad
+1  A: 

You can move it out from the .designer.cs file and into the main .cs file if you want. As has been said already, it won't be overwritten.

Mark Heath
+11  A: 

In such a case I move the generated Dispose method to the main file and extend it. Visual Studio respects this.

An other approach would be using a partial method (C# 3.0).

Michael Damatov
A partial method does not work in this scenario.
Micah
The Dispose method in Designer file could be extended to include a call to a partial method, which may be implemented in the main file.
Michael Damatov
Since the MyClass.Designer.cs file is already a partial file, you can simply add the needed logic to the Dispose method already generated. Visual Studio will not overwrite the method once it's been created so you're safe to modify it.
Scott Dorman
+2  A: 

All Component classes implement Disposed event. You can add event handler and clean up things.

@Jacob Seleznev: Not sure why more people didn't upvote this. Maybe they didn't see it? I consider the Disposed event the proper way to add disposal functionality to any class that supports it.
supercat
A: 

You just need to overload the public void Dispose() method in the Component Class that the user control inherits.

make sure you pass the call to the base method as well as doing your dispose functionally or you'll break the functionality unless you fully implement it

Mike