0

I have a label array pointing to a label such as,

label_array[i] = a_label;

The array has global while label has function scope. Is it possible to delete label via array?

7
  • What do you mean by "delete" in this context. Remove from the form? (I assume by "label" you mean a visual label.) Commented Mar 13, 2012 at 20:42
  • Are you sure you tagged this right? C# and pointers are seldom mixed. Commented Mar 13, 2012 at 20:42
  • @LasseV.Karlsen: With "delete" I mean remove totally. Commented Mar 13, 2012 at 20:43
  • 1
    "Remove totally" from what? Commented Mar 13, 2012 at 20:46
  • 3
    There's no need to "delete" like you do in C++. C# is an automatic-garbage-collection language. Commented Mar 13, 2012 at 21:13

1 Answer 1

1

Usually, you can dispose of your objects just by setting their references to null, the garbage collector will take care of disposing of those objects for you. However, not all objects can be disposed just by setting their reference to null. In fact, all objects that implement IDisposable should be disposed by calling their Dispose method as it the case for GDI objects which require an explicit call to Dispose to free up their resources (see this link for details)

This is being said, if a_label is a WinForms Label then you should do the following to dispose of it:

// REMOVE THE LABEL FROM THE PARENT CONTAINER FIRST 
// AND THEN DO THE FOLLOWING
label_array[i].Dispose();
label_array[i] = null;

EDIT Just to highlight what @Groo mentioned in the comment below, make sure you remove your Label from the parent container before disposing of it, thanks @Groo!

Sign up to request clarification or add additional context in comments.

2 Comments

I wouldn't recommend doing this before label is removed from its parent control's Controls collection.
Please don't say "dispose of" when releasing a reference, in .NET, disposing of an object and releasing references (eventually making it eligible for collection) is not the same at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.