When you create a form or a user control, the WinForms designer generates a dispose method that looks like this:
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
The problem with this code is that it can lead to incorrect behaviour if it is ever edited to dispose of additional objects. I have seen .designer.cs files with dispose methods that look like this:
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
if (_myDisposable != null)
_myDisposable.Dispose();
if (_myOtherDisposable != null)
_myOtherDisposable.Dispose();
}
base.Dispose(disposing);
}
… which is incorrect, as the disposal of _myDisposable and _myOtherDisposable should not depend on whether or not components is null.
So, ignoring the argument about whether or not it is good practice to edit this designer generated code, and ignoring the fact that you can change it by editing the templates, my question is: Why doesn’t the designer generate code that looks more like this?
protected override void Dispose(bool disposing)
{
if (disposing)
{
if(components != null)
components.Dispose();
}
base.Dispose(disposing);
}
This code has the same end result, but is safer and less prone to errors during modification.
The answer is: because your convenience was not the primary concern of whoever wrote this function at Microsoft. Or perhaps they thought that you, being a non-Microsoft employee, cannot possibly be any good as a programmer, therefore, you should probably stay away from risky businesses such as modifying an object’s Dispose() method.
By the way, the Dispose() method lies outside of the area within the .Designer.cs file which is designated as “do not edit this designer generated code”, so I suppose it is okay to edit it.