I'm trying to make a settings program for a project I'm working on, and I need a way to unload objects (specifically pictureboxes and labels). I probably will need the objects later, but I don't want them constantly loaded in memory, because I want to make my program as lightweight as I can.
I've tried nulling my objects, and it does null them, but now I can't RE-load them.
Here is the code:
public void LoadPage(string URL)
{
if (URL != currentPage)
{
if (this.SystemRootIcon != null)
{
this.SystemRootIcon.Dispose();
}
if (URL == "Root")
{
if (this.SystemRootIcon == null)
{
this.SystemRootIcon = new System.Windows.Forms.PictureBox();
// Below does not run
debug.Text = "RUNNING!";
((System.ComponentModel.ISupportInitialize)(this.SystemRootIcon)).BeginInit();
this.splitContainer1.Panel2.Controls.Add(this.SystemRootIcon);
this.SystemRootIcon.BackgroundImage = global::New_Control_Panel.Properties.Resources.imageres_195;
this.SystemRootIcon.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.SystemRootIcon.Location = new System.Drawing.Point(12, 42);
this.SystemRootIcon.Name = "SystemRootIcon";
this.SystemRootIcon.Size = new System.Drawing.Size(48, 48);
this.SystemRootIcon.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.SystemRootIcon.TabIndex = 18;
this.SystemRootIcon.TabStop = false;
this.SystemRootIcon.Visible = true;
((System.ComponentModel.ISupportInitialize)(this.SystemRootIcon)).EndInit();
}
currentPage = URL;
}
}
}
this.SystemRootIcon.Dispose();
does not set the value of SystemRootIcon
to null, thus the later condition if (this.SystemRootIcon == null)
will never be true. You need to set it to null explicitly after dispose.
Instead of testing for null, you could also test for IsDisposed
instead. That might be a bit safer to do, since it does not involve null tests and therefore bears less risks of running into NullReferenceExceptions.
So the first condition should be something like:
if (this.SystemRootIcon != null)
{
this.SystemRootIcon.Dispose();
this.SystemRootIcon = null;
}