views:

99

answers:

2

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 recomended.

TreeNode tn = new TreeNode ();
CustClass o = new CustClass()
o.number = 123;
tn.Tag = o;

class CustClass
{
    public int number {get; set;}
}
+10  A: 

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.

Timwi
Unboxing is inefficient when used in large amounts, but for one int in a control it's unlikely to be noticed.
Joel Coehoorn
+2  A: 

I don't think this would be a boxing or unboxing problem to use it the way you want. As far as I know, that Tag property is for the programmer's purpose only, so you can use it quite the way you need it to be used.

Please see Control.Tag property on MSDN for further reference on how to use this property.

For instance, I used to use it to input instructions to the user in Windows Forms applications. When the control GotFocus event triggered, the instructions Label.Text property was assigned the value of my control Tag property which contained the instruction string.

Will Marcouiller