I have noticed the Tag properties with controls. Is it okay to use this to reference my custom objects, or should I stay away from it as it would require boxing and unboxing which has been mentioned as unsafe and is not recommended.
TreeNode tn = new TreeNode();
CustClass o = new CustClass()
o.number = 123;
tn.Tag = o;
class CustClass
{
public int number {get; set;}
}
C# Tag Property: Windows FormsUse the Tag property to store objects on Windows Forms controls. Tag. The Tag property stores an object reference. Windows Forms programs can use object models of arbitrary complexity. But the Tag property is a simple way to link a certain object to a certain control.
The following example uses the Tag property to store additional information about each control on the UserForm. The user clicks a control and then clicks the CommandButton. The contents of Tag for the appropriate control are returned in the TextBox.
In WPF, the FrameworkElement class includes a Tag property that allows storing some arbitrary data with an element. You'd normally use the Tag property to store some custom data on an element that inherits from FrameworkElement.
Similar to Google Analytics for websites, Control Tag is a snippet of code that gets placed in the </head> section of a website to enable tracking, targeting and more.
The purpose of the Tag
property is for you to use it for any purpose you want. You can safely store anything in there you want.
It is customary to declare a class that is specifically intended for being stored in the Tag
property (like you did with your CustClass
). But if you need only one value in it, then there is nothing wrong with storing an int
in it directly.
Where did you read that boxing/unboxing is “unsafe”? That is absolutely not true. (Some people claim that it is inefficient, but even that is not true.) Furthermore, your code does not even contain an example of boxing at all. CustClass
is a reference type. Only value types are boxed when assigned to object
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With