Operator ‘==’ cannot be applied to operands of type ‘char’ and ‘string’

Unlike C, a string and an array of char are different. A string in C# can be viewed as an array of char but you should consider them different, therefore the ‘==’ comparison isn’t appropriate. One easy way to see this is with the following simple expression

   if ("a" == 'a') { /* do something */ } // ERROR!

It looks like it should work but it generates the same error you are seeing, because it is trying to compare the string “a” to the char ‘a’. In your example code the Text property of your textbox control is of type string.

The string class has an indexer that allows you to treat a string as an array of char, but it’s usually better (simpler) to use one of the many string methods to accomplish your goal. Consider this:

        var gridcolumns = "abcdefgh";
        var gridrows = "12345678";
        var input = "a1"; // column row
        var col = gridcolumns.IndexOf(input[0]); // 0 -7
        var row = gridrows.IndexOf(input[1]); // 0 -7

In the code you gave I don’t see a line that would generate the error you provided. The following line serves no purpose

           Char.ToLowerInvariant(currentLocationTextBox.Text[0]);

Because you are not assigning the returned value to a variable, plus ‘cl’ already contains the lowercasing of that particular value.

This line

            if (cl[0] == gridColumns[i])

should not generate the error because both items are of type char.

Leave a Comment