Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

The final line in the HideCalibration method is probably to remove the reference to the form, so that the garbage collector can remove it and free up a bit of memory on the heap.

The first line (static CalibrationForm form = null;) is simply to make it obvious what the initial value of the static variable is.

It is to make sure all references in memory to form are gone. There is no other reason, and in fact I believe it has no further use whatsoever.

In fact, what the CLR does is keeping a managed heap containing all class, class doesn't have any references any more, it can be garbage collected, otherwise it doesn't.

In this case, the Dispose removed the Win32 handles, but not the memory allocated from the .NET part, so that's why you set it to null.

Read this on GC internals.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top