Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What use is the Tag property in .net

Tags:

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;}
}
like image 591
Brad Avatar asked Sep 29 '10 16:09

Brad


People also ask

What is Tag property in C#?

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.

What is Tag property in VB net?

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.

What is Tag property in WPF?

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.

What is the use of control Tag?

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.


1 Answers

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.

like image 130
Timwi Avatar answered Oct 29 '22 05:10

Timwi