I have this Dispose method I want to change. (Yeah I should check every object for null, I know)
protected override void Dispose(bool disposing)
{
if( disposing )
{
if( monthLineBrush != null)
monthLineBrush.Dispose();
monthHeaderLineBrush.Dispose();
shadowBrush.Dispose();
monthHeaderLineBrushDark.Dispose();
monthFontBrush.Dispose();
weekendBgBrush.Dispose();
whiteBrush.Dispose();
dayFontBrush.Dispose();
chartBrush.Dispose();
chartWarningBrush.Dispose();
barBrush.Dispose();
monthLinePen.Dispose();
monthHeaderLinePen.Dispose();
monthHeaderLinePenDark.Dispose();
warningLinePen.Dispose();
monthFont.Dispose();
yearFont.Dispose();
weekLinePen.Dispose();
dayLinePen.Dispose();
tooltip.Dispose();
toolTipLabel.Dispose();
}
base.Dispose(disposing);
}
VS uses a System.ComponentModel.IContainer object named components , and only disposes this components object. Yet I can’t find any code where the different objects are added to the components objedct ??
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
How does this work ?
The code to add each object that is created to the
componentscontainer is automatically generated and added to the*.Designer.csfile associated with each form by the designer.For example, the
Form1.Designer.csfile might look something like this in a brand new, empty project once you’ve added aToolTipcontrol to the form:There are two relevant lines of code in that whole mess, the two that appear at the very top:
The first line creates a
System.ComponentModel.Containerobject calledcomponents, to which all of the components that implementIDisposablewill be added when they are created.The second line creates a
ToolTipobject (in response to one being drug to the form’s surface during design time), and uses a constructor overload that accepts a parameter of typeIContainer.Extending this same song and dance to the other components that are added to your form allows them all to be disposed at one go with the
Disposemethod provided by thecomponentscontainer.