VA systems engineer
VA systems engineer

Reputation: 3189

Why can't I directly access the properties of a custom object that I've assigned to a WinForms Control.Tag property?

I want to set a Winforms Control.Tag property with my custom object ButtonMetaData and then access the properties of ButtonMetaData using the Control.Tag property. Should work because the Tag property is defined as an object, right? See Figure 1.

However, in order to access the properties of ButtonMetaData, I'm forced to assign the Tag object to an intermediate object variable (x in my example) in order to access the ButtonMetaData properties. When I try and access them using the Tag object that has been cast to ButtonMetaData, the compiler complains. See Figure 2.

Why can't I directly access the properties of ButtonMetaData using the Tag object that has been cast to ButtonMetaData?

Figure 1

Figure 1

Figure 2

public class ButtonMetaData
{
    public bool clickedByUser;
    public bool clickedProgramatically;

    public ButtonMetaData(bool clickedByUser, bool clickedProgramatically)
    {
        this.clickedByUser = clickedByUser;
        this.clickedProgramatically = clickedProgramatically;
    }
}

private void Button1_Click(object sender, EventArgs e)
{
    Button button = (Button)sender;

    button.Tag = new ButtonMetaData(clickedByUser: true, clickedProgramatically: false);

    //BUILDS OK
    ButtonMetaData x = (ButtonMetaData)button.Tag;
    Console.WriteLine(x.clickedByUser);
    Console.WriteLine(x.clickedProgramatically);
    //BUILDS OK

    //DOESN'T BUILD - error on field clickedByUser and error on field clickedProgramatically
    Console.WriteLine((ButtonMetaData)button.Tag.clickedByUser);
    Console.WriteLine((ButtonMetaData)button.Tag.clickedProgramatically);
    //DOESN'T BUILD - error on field clickedByUser and error on field clickedProgramatically

}

Upvotes: 0

Views: 90

Answers (1)

richej
richej

Reputation: 834

You forgot some brackets. You need to cast button.Tag to ButtonMetaData. Try this:

 Console.WriteLine(((ButtonMetaData)button.Tag).clickedByUser);

Without brackets you are casting button.Tag.clickedByUser to ButtonMetaData...

Upvotes: 5

Related Questions