The FolderBrowserDialog component in .NET Framework (and the OpenFileDialog) implements the IDisposible interface, meaning we should call its Dispose method at some appropriate time after we’ve done with it or something bad happens (unmanaged resource leaks).
In Visual Studio WinForm designer, if I drag a FolderBrowserDialog component onto a Form, the code generated by the designer does not seem to take care of this at all, no code calls the Dispose method on the FolderBrowserDialog.
In contrast, if I drag a Timer (the one in the System.Windows.Forms namespace) which also implements IDisposible interface, the code generated would be:
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
By associating the timer with the container (this.components), the timer is guaranteed to be properly disposed when the container is disposed- happens when Form.Close() or Form.Dispose() is called.
So why FolderBrowserDialog component receives this special treatment?
Good spot! The reason is probably that the
FolderBrowserDialogdoes not provide a constructor that takes anIContainerargument, whereasTimerdoes.As to why this is so, you can only ask the original winforms designers. Maybe it isn’t really designed to be used in the designer in this way? They only meant it to be used in code in a
usingstatement?Bear in mind that
FolderBrowserDialog, and its parents, don’t actually overrideDisposefromComponent, so it doesn’t actually need to dispose anything.