I am writing a C#.NET application. I have a form. When the form is created I create an instance of a class. When I close the form, I want to dispose of the class so that the next time I open the form I can just create a fresh new instance of the class. So, in the form_Closing event I added code like this: classInstance = null; The problem is, for some reason, the next time I open the form the class is not equal to null but rather it is in the same state as it was right before I closed the form. Why is this happening?
EDIT: Adding Info:
myHandler is a field in the Form class.
it looks like this:
private HSFW_Handler myHandler;
The Class that I am referring to is a singleton so I create it like this:
public static HSFW_Handler GetInstance()
{
if (myHSFW == null)
{
myHSFW = new HSFW_Handler();
return myHSFW;
}
else return myHSFW;
}
I create an initial instance of it in the Form_Shown event
private void SetupDialogForm_Shown(object sender, EventArgs e)
{
try
{
myHandler = HSFW_Handler.GetInstance();
UpdateDisplay();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The Form Closing looks like this…
private void SetupDialogForm_FormClosing(object sender, FormClosingEventArgs e)
{
myHandler = null;
}
Let’s look at this code:
And this:
Notice anything?
You’re setting
myHandlertonull; but this appears to be an instance-level member ofSetupDialogForm. Or anyway, it’s not the same asmyHSFW, which is your static variable in theHSFW_Handlerclass.When you do this…
…you’re making
myHandlera reference to the same object pointed to byHSFW_Handler.myHSFW; but they’re still two separate references. Setting one tonullhas no impact on the other.The point of all this is that you need to actually change the value of
myHSFWtonullto get the behavior you seem to want.I’d do it like this:
Then: