1

I think the main point of my question is: what is best practise or is Visual Studio 2019 giving me wrong hints about disposing items? This post talks about bugs in the code analysis, but disposing items is still a bit outside my field of good knowledge.

I have a form where I declare some fields:

public partial class FormRequestLines : Form
{ 
    Process view3dProcess;
    Process view2dProcess;
    Label label;
    ......

The fields are used to (re)start and kill processes and write and hide to a newly created label in different methods.

To dispose these fields, I created a FormClosed method:

private void FormRequestLines_FormClosed(object sender, FormClosedEventArgs e)
{
    if (view2dProcess != null) { view2dProcess.Dispose(); }
    if (view3dProcess != null) { view3dProcess.Dispose(); }
    if (label != null) { label.Dispose(); }
}

1) Is it correct that the fields should be disposed?
2) Is this the correct way and place of disposing fields?

Visual studio gives me these warnings:
VS code analysis

Ps: I use the designer of VS to create a form.

Jannick Breunis
  • 195
  • 2
  • 14
  • 1
    Is there any reason why you aren't doing this in the form's Dispose method? Also take a look at C#'s null-condional operation (`.?`), it will make your null tests easier on the eyes. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and- – Flydog57 Sep 20 '19 at 14:08
  • 2
    It is normal, code analysis isn't smart enough to know anything about the FormClosed event. A Form class has a proper Dispose() method, it is however located in the somename.designer.cs file and editing that file is something that everybody learned not to do. Cut+paste to move that method to your somename.cs file is fine however. – Hans Passant Sep 20 '19 at 14:23

1 Answers1

2

Static code analysis tools expects that you do dispose in Dispose() method. You need to override the Dispose method from Form and remove FormRequestLines_FormClosed.

See difference between Form.Close and Form.Dispose

Typically this is automatically overridden in the FormRequestLines.Designer.cs file, so you will need to move the dispose into your code file so that you can add whatever code you need to add without it being rewritten by the designer.

protected override void Dispose(bool disposing)
{
  if (disposing)
  {
    components?.Dispose();
    view2dProcess?.Dispose();
    view3dProcess?.Dispose();
    label?.Dispose();
  }

  base.Dispose(disposing);
}
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116