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

47,046

Solution 1

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.

Solution 2

Dweeberly's answer when applied... and shortened: Answer: Change the single quotes to double-quotes.

My reasoning: Assume the following code:

string IAmAString;
// set string to anything
IAmAString = "Q";
if (IAmAString == 'Q')
{
 // do something, but never gets here because "Q" is a string, and 'Q' is a char
 // Intellisense gives error on the if statement of 
 // 
 // "Operator '==' cannot be applied to operands of types 'string' and 'char'"
 //
 // because C# is a strongly typed language, and the '==' is not by 
 // default (in VS2012) overloaded to compare these two different types.
 // You are trying to compare a string with something that
 // is not-string, and C# is trying to let you know 
 // that that is not going to work.
}

It is fixed by changing the quotes to double-quotes. C# definitely seems to consider single quotes around a single character to be Char, and not string.

just change the quotes within the if statement:

IAmAString = "Q";
if (IAmAString == "Q")
{
 // does whatever is here within reason; "Q" is a string and "Q" is a string
}

At least this worked for me, and that's my 'quick' (where 'q' != "q") explanation of why.
Getting back to work...

Share:
47,046
TargetofGravity
Author by

TargetofGravity

New to the programming field, started course in the Fall of 2012. Looking forward to collaborating with others and hopeful someday soon having the ability to help those who've helped me.

Updated on July 09, 2022

Comments

  • TargetofGravity
    TargetofGravity almost 2 years

    I’m working on a self directed simple program to practice concepts I’ve learned thus far. My project is related to chess, in this case specifically the board (columns a-h and rows 1-8). The user is asked for the current location of a specific chess piece hopefully entered as a letter for the column followed by a number for the row. To validate this it made sense to me to first check if this value was entered as a string of two characters, otherwise what is entered is already incorrect. I then converted the entered string to lower case characters before comparing it with my list of acceptable array elements.

    From searching this site I get the impression that a string stores its characters as an array and using the char property of string you would be able to pull off the first character thus comparing char to char. I have not yet found anything specific enough in my searches to really give me a good understanding of what is happening. This is the closest option I’ve come across which I didn’t feel was applicable to this case. Any insight would be appreciated.

    The code that follows produces the following error.

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

        private char[] gridColumns = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', };
    
        private void createMoveButton_Click(object sender, RoutedEventArgs e)
        {
            // Assigns text box input to associated private fields
            this.gameId = this.gameIdTextBox.Text;
            this.playerId = this.playerIdTextBox.Text;
            this.gamePiece = this.gamePieceTextBox.Text;
            this.currentLocation = this.currentLocationTextBox.Text;
            this.targetLocation = this.targetLocationTextBox.Text;
    
            // Current location should only ever be 2 characters, ensure from the start this is true.
            if (currentLocationTextBox.Text.Length == 2)
            {
                // Converts contents of currentLocationTextBox to lower case characters for comparison.
                string cl = currentLocation.ToLowerInvariant();
    
                // Iterates through my array of possible column choices
                for (int i = 0; i < gridColumns.Length; i++)
                {
                    Char.ToLowerInvariant(currentLocationTextBox.Text[0]);
                    // Trying to compare the first character of my string to the char element of my array.
                    if (cl[0] == gridColumns[i])
                    {
                        //TODO
                    }
                }
            }
            else
            {
                MessageBox.Show("Check your starting location. It needs to be a lower case character variable (a-h) followed by a number (1-8)");
            }
        }
    
  • TargetofGravity
    TargetofGravity over 10 years
    I assume this converts both to a string for comparisons sake, but by selecting the first character of the string with [0] are you not doing the same thing just comparing char to char? I guess that's the part I'm having troubles with understanding.
  • Nikhil Agrawal
    Nikhil Agrawal over 10 years
    @TargetofGravity: Is your variable gamePieces or gamePiece? Read comment of musical_coder.
  • TargetofGravity
    TargetofGravity over 10 years
    Apologies I had not fully refactored in my trial and error. Actual variable should be gridColumns to reference the array in question, thank you.
  • musical_coder
    musical_coder over 10 years
    @TargetofGravity: so are you still getting the same compiler error?
  • TargetofGravity
    TargetofGravity over 10 years
    I appreciate that suggestion, did not know that.
  • TargetofGravity
    TargetofGravity over 10 years
    No actually. I can't explain it but closing and reopening VS cleared it. Prior to I had tried a rebuild without luck as well as a clean solution and rebuilding. I guess I'm not sure what occurred. I'm not sure if anyone else has experience this but at times with VS some of the short cuts act "funny" for lack of a better term. For instance when you cut something and paste it doesn't always re-paste what you cut out and undo will act equally sporadic removing things. Thus far a restart for this issue is my current fix as well.
  • TargetofGravity
    TargetofGravity over 10 years
    I appreciate the explanation and the suggestion. I know there are a lot of people on here just looking for quick answers but sometimes just having someone explain something to you vs trying to understand the concept from a reading is helpful. Thanks.
  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen over 10 years
    This Contains is actually not on the array; it is a Linq extension from System.Linq.Enumerable.
  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen over 10 years
    Actually cl[0] works and is better because it is less code, and because it won't need to copy the entire string over to a new array.