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?
Yes this is legal to do and is one of the patterns the
Tagproperty was designed for.The biggest danger here is that another peice of code attempts to use the same
Tagproperty for their own feature. This would create a race for theTagproperty and lead to runtime bugs. A safer approach would be to create a private map between aLabelandMyObjectusing aDictionaryinstance.This approach has the extra overhead of a
Dictionarybut produces more reliable code (IMHO).