Search code examples
c#.netformsnulldispose

Why Form needs to be set to null?


I'm learning C #, the example programs that I have seen I find code like this:

static CalibrationForm form = null;

and this

public static void HideCalibration()
{
 form.Hide();
 form.Dispose();
 form = null;
}

Is there any particular reason why the form should be set to null?

What is the meaning of a form is set to null?


Solution

  • In this (IMO poor) example, form is a static field that holds a reference to the form instance that is going to be available from all locations in the application. The problem is that Dispose() is not enough - it cannot be garbage collected if it is referenced by a static field, because static fields do not go out of scope. Ever. Setting the field to null allows the instance to be collected.

    Note also that any references to the form will keep it alive - not just this field; event subscriptions are notorious ways to keep things alive artificially.

    But emphasis: that is a horrid example. I do not recommend coding with forms in static fields.