I am creating tic-tac-toe simple game,all works correctly until checking buttons content and I am stucked with a problem:

it always returns false even when buttons have right content.

I've tried to change to string both(Content and 'x' or '0')-doesn't work button.Content should be object

if ((buttons[0].Content == (object)'x' || buttons[0].Content==(object)'0') &&(buttons[3].Content == (object)'x' || buttons[3].Content == (object)'0')
               && (buttons[6].Content == (object)'x' || buttons[6].Content == (object)'0'))
            {
                MessageBox.Show("You have won", "Tic-tac-toe");
                this.Close();
            }

I expect checking with true output so the game will finish.

1 Answers

0
Community On Best Solutions

System.Char is a ValueType. So, when you cast it to System.Object CLR created a copy of this object and stored it on the managed heap. This method is called Boxing. (Read more at MSDN: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing).

So, you have two different instances of System.Object: the first is stored at the Button.Content property and the second was gotten by cast. Then you apply == operator to these instances. When it happens CLR tries to compare references of the operands. But as I have already said you have two different objects, so, as expected, its references are not equal. That's why you got false as a result.

To solve you problem I suggest you try to cast Button.Content to System.Charand not vice versa. Or use System.String instead of System.Char as a content of your buttons. Because System.String is a reference type.