C# – Common uses for the Tag property


I've started using this alot to link elements of my UI to their data backing class (whatever that might be). What are some of the common uses you put the Tag property to use for?

Indeed, do you use it at all? I know I didn't for a very long time.

Best Solution

Just as you describe, the most frequent use of the Tag property I have come across and use in both WinForms, WPF and Silverlight is to indicate the real data that the control relates to. This is especially useful on ListViewItem instances or auto-generated user interface where you want to use the same event handler for multiple objects where only the target data is different (i.e. the action to be performed remains the same).

However, I have also used the Tag to store an enumeration value (though you should avoid value types as it would cause boxing when assigning the value to the Tag property) or a string that is then used to determine the action that needs to be performed instead of the data on which to perform it, and in one particular usage, I stored a delegate so that I could auto-generate some buttons and embed their handlers in the Tag (the handler information was supplied in a data driven manner).

I am sure there are many other ways to use Tag and many other ways to replace the uses of Tag with something more strongly typed, but that's how I've used it.