7

Although topic has been discussed here before, but the proposed solutions don't seem to work..

I have a button-click-callback method in my form application, that shows a folder picker dialog:

private void ButtonSelectReporterFolderClick(object sender, EventArgs e)
{
    using (var dialog = new FolderBrowserDialog()) // causes warning
    {
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            this.boxReporterFolderPath.Text = dialog.SelectedPath;
        }
    }
}

This produces a warning:

CA2000: Microsoft.Reliability : In method 'MainWindow.ButtonSelectReporterFolderClick(object, EventArgs)', object '<>g__initLocal' is not disposed along all exception paths. Call System.IDisposable.Dispose on object '<>g__initLocal' before all references to it are out of scope.

I also tried using a try-finally block or even calling dialog.Dispose without any blocks, all to no avail - the warning remains, always at the line of initialization.

Efrain
  • 3,248
  • 4
  • 34
  • 61
  • Sorry, but I can't reproduce the CA2000 warning for the above code. Are you sure it isn't being caused by something else? – Nicole Calinoiu Jul 22 '11 at 11:49
  • No, I wish.. did you run it in a proper windows form application callback? – Efrain Jul 22 '11 at 15:16
  • I don't see a CA2000 violation in the method even when it's wired as a button Click event handler in a vanilla Windows form in a vanilla Windows Forms executable. Do you see a violation if you add the minimum "repro" code to a new Windows Forms application? – Nicole Calinoiu Jul 22 '11 at 18:37

1 Answers1

5

The warning is not because FolderBrowserDialog is not disposed, it is because it has some public members that implements IDisposable interface and you're not disposing them separately. Of course, FolderBrowserDialog object knows how to dispose of it's dependencies but FxCop has no way of knowing that so it gives a warning. Just ignore the warning in your case.

Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • 1
    so.. basically FolderBrowserDialog is not CA2000 compliant? O_o – Efrain Jul 22 '11 at 11:21
  • 1
    Actually same things happen with some other controls too, nothing special for FolderBrowserDialog. (it happens to me all the time with font object, image control, etc.) – Teoman Soygul Jul 22 '11 at 11:40
  • 2
    It's more a case that CA2000 is almost useless. It generates so many false positives that the genuine warnings get lost in the noise. – LukeH Jul 22 '11 at 13:35