views:

39

answers:

2

I'm creating a group of form controls for each object in a list, is it OK to store a reference to the object in the controls Tag property?

I'm doing this so I can have a generic Click event on the controls, so when they are clicked I can update a field in the object that they represent.

So the click handler will look something like this.

private void Item_Clicked(object sender, system.EventArgs e)
{
     if(sender.GetType() == typeof(System.Windows.Forms.Label))
     {
          System.Windows.Forms.Label label = (System.Windows.Forms.Label)sender;
          MyObject myObject = label.Tag;
          myObject.Value = true;
     }
}

Is this an acceptable thing to do in this situation, or is there a better way to handle this?

+2  A: 

Yes this is legal to do and is one of the patterns the Tag property was designed for.

The biggest danger here is that another peice of code attempts to use the same Tag property for their own feature. This would create a race for the Tag property and lead to runtime bugs. A safer approach would be to create a private map between a Label and MyObject using a Dictionary instance.

private Dictionary<Label,MyObject> _map = new Dictionary<Label,MyObject>();
...
private void Item_Clicked(object sender, system.EventArgs e) 
{ 
     if(sender.GetType() == typeof(System.Windows.Forms.Label)) 
     { 
          System.Windows.Forms.Label label = (System.Windows.Forms.Label)sender;
          MyObject myObject = _map[label];
          myObject.Value = true; 
     } 
}

This approach has the extra overhead of a Dictionary but produces more reliable code (IMHO).

JaredPar
That approach would work if I was only using Labels. My example was a shortened version of what I'm doing. In reality I have a few if statements to determine what type of control was clicked. In my case should I create a Dictionary like this Dictionary<Control,MyObject>?
Tester101
@Tester101 yes if you need to map Controls (not just Labels as in your example) to MyObject then that would work
Rune FS
+1  A: 

It's acceptable if it works for you. I've stored things in the tag properly like this before, and it works fine. Things to consider: the size of the object you're storing and the lifecyle of the object (could it be disposed of or destroyed between accesses).

Another approach, that I have used, is to store a "hint" that would help you retreive or recreate the object. For example, if it's a database object, store the Id property (maybe an integer or Guid) which is much [potentially] much smaller than the object itself.

Coding Gorilla