I have an object that is declared at the class level which is giving CA2000 warning. How can I get rid of the CA2000 warning from the code below?
public partial class someclass : Window
{
System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog()
{
AddExtension = true,
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "xsd",
FileName = lastFileName,
Filter = "XML Schema Definitions (*.xsd)|*.xsd|All Files (*.*)|*.*",
InitialDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop),
RestoreDirectory = true,
Title = "Open an XML Schema Definition File"
};
}
The warning is- Warning CA2000 In method 'SIMPathFinder.SIMPathFinder()', object 'new OpenFileDialog()' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'new OpenFileDialog()' before all references to it are out of scope.
CA2000 says that instances of your class own a disposable object that should be disposed to free used (unmanaged) resources before the instance of your class gets out of scope.
A common pattern to do this is to implement the
IDisposable
interface and anprotected virtual Dispose
method:Read more about the Dispose-Pattern
As a side note: It seems your mixing WPF and Windows Forms. You inherit from
Window
(which I presume isSystem.Windows.Window
as your question is tagged wpf), but try to use aSystem.Windows.Forms.OpenFileDialog
.To mix these two UI frameworks is not a good idea. Use
Microsoft.Win32.OpenFileDialog
instead.