.Net Control.Tag - Common and Unusual Uses

As my program grows and grows, I find myself using Control.Tag more and more. I'm not quite sure why Microsoft put it there, but I find it very useful.

I was left wondering: what was their original purpose? What is considered acceptable and what is considered a taboo?

According to MSDN, Control.Tag "Gets or sets an object that contains data about the control."

In my calendar application, I save the actual Appointment object that represents the AppointmentControl . I suspect this is intentional use, and the MSDN example seems to confirm this, however I am also doing some more unusual things.

For example, when I have the back / next pair of buttons, and I want to go back to shutdown when we reach the beginning, and next to shutdown when we get to the end, then I will save the next button in the tag of the previous and previous buttons in the tag of the next. That way, I can always set ((Button)Tag).Enabled = true per click (because when you go back, the next button is explicitly disabled, and vice versa).

In addition, my calendar consists of a (visually) two-dimensional array of panels. I save a DateTime that corresponds to each panel in Panel.Tag , and when the user approaches to see time intervals in one day, the panels making up each time interval have a TimeSpan in their tag, which represents the slot start time.

So, I am wondering: What do you think is the most commonly used Tag? What more unusual Tag app did you use or see? Do you think that storing a linked object (as in the example with my back / next button) is โ€œhackedโ€?

Some people oppose the use of tags, suggesting that they are remnants of older languages. A common complaint is that itโ€™s better to simply extend the control so that it contains a strongly typed object, rather than something arbitrary that you must use when using it. What do you think about it?

+4
source share
1 answer

This came from VB6, its controls also had the Tag property. This is a very bad option for a field in your class; it is not type safe because Tag is of type Object. It is difficult to read the code; it has a non-specific name. If you want it to be associated with a control, use inheritance. Derive the class from the control type and add the necessary properties. Or add a field to your form.

+5
source

Source: https://habr.com/ru/post/1346645/


All Articles