1

I know there is a question similar to this one but the naswers there didnt help me that much it was compicated so i asked this new one

i was trying to convert char into upper case by .ToUpper method

but it is give me this issue

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

here is the code

char UserChoice = Convert.ToChar(Console.ReadLine());
char upperCaseChoice = Char.ToUpperInvariant(UserChoice);

if (UserChoice == "Y" || upperCaseChoice == "YES")
{
    TotalCoffeeCost = askForCoffee(TotalCoffeeCost); //Note here that we did not set invalidChoice to false, meaning it will loop again
}
else if (upperCaseChoice == "N" || upperCaseChoice == "NO")
{
    invalidChoice = false;
}
else
{
    Console.WriteLine("");
    Console.WriteLine(" Please enter a valid choice");
}
13
  • 1
    You're explicitly converting a line of input to a single character, and then comparing that character to strings. It looks like you actually want your input as a string, and convert the string to uppercase. Commented Jul 21, 2022 at 5:16
  • no i want a char only , can i give the input as a string and then convert into char an then pass the argument, will it work Commented Jul 21, 2022 at 5:19
  • 2
    " denotes a string, ' denotes a character. Clearly upperCaseChoice == "YES" is impossible (a single character cannot match 3 characters). You seem to want UserChoice == 'Y'. Also note that common convention dictates that local variables should be camelCase not PascalCase. Commented Jul 21, 2022 at 5:20
  • 2
    as you need to store yes or no, using string is reasonable here. Commented Jul 21, 2022 at 5:35
  • 1
    "why not use a lower byte datatype to just store 2 or 3 char" - OK, let's assume that you're just storing one char. You're currently calling Console.ReadLine(), this returns a string. You're then calling Convert.ToChar to get the first character from that string. So you have multiple pieces of data in memory: the length of the string, its characters, and this new single character. Now, with .NET's garbage collection, it will still be a while before the data from the original string gets expunged. Therefore, you're actually using more memory in the time until that gets GC'd. Commented Jul 21, 2022 at 5:38

3 Answers 3

1

You are setting the type of the variable to a character, set it to a string.

string UserChoice = Console.ReadLine();

if (UserChoice == "y")
{
    Console.WriteLine("test");
}
Sign up to request clarification or add additional context in comments.

4 Comments

im doing char intentionally , i was using string before and it was working fine , but as i thought if i have to get only yes or no or y and n why not to use char instead of string
@Indie "only yes or no or y or n" - yes is a string composed of 3 chars, no is a string composed of 2 chars.
By definition, "yes" and "no" are not individual characters -- they are strings made up of individual characters.
Single-character string is still a string, an immutable reference type with instance properties such as Length and an array of characters. A char is a 16-bit integer. The .NET designers probably felt that comparing the two is most probably an issue with the code and so they did not introduce such comparison. There's only handful of strings that can ever compare to a single character, it's similar as if single-element arrays of int would support comparing to ints. You can easily fix this by doing 'y' (char literal) instead of "y" (string literal).
1

Why don't you use the following method?

    // original string
    string UserChoice = Console.ReadLine();

    // string converted to Upper case
    string upperCaseChoice = UserChoice.ToUpper();



    if (UserChoice == "Y" || upperCaseChoice == "YES")
    {
        //Do Somthing

    }
    else if (upperCaseChoice == "N" || upperCaseChoice == "NO")
    {
        //Do Somthing
    }
    else
    {
        Console.WriteLine("");
        Console.WriteLine(" Please enter a valid choice");
    }

In the first step you cannot convert the string to a character because Character refers to a single character value You must convert the value to an array of characters

    var userChoice = Console.ReadLine().ToCharArray();

    var userChoiceFirstChar = Convert.ToString(userChoice.First()).ToUpperInvariant();
    var userChoiceJoin = string.Join("", userChoice).ToUpper();

    
    if (userChoiceFirstChar == "Y" || userChoiceJoin == "YES")
    {
    }
    else if (userChoiceFirstChar == "N" || userChoiceJoin == "NO")
    {
    }
    else
    {
        Console.WriteLine("");
        Console.WriteLine(" Please enter a valid choice");
    }

1 Comment

What if the user typed a lower case "y"? - just ignore "UserChoice" and only check "upperCaseChoice"
0

Well, string is a collection of characters and that's why the fragment below doesn't compile:

char upperCaseChoice = ... // single character

...
// how come can compiler compare single character with a collection?

if ( ... upperCaseChoice == "YES" ...)

I suggest to extract method, let it be ReadBool which takes the title (the question we'll put for users) and returns bool (true or false) user's answer:

private static readonly IReadOnlyDictionary<string, bool> s_Bools = 
  new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase) {
    //TODO: add more synonyms, like `{"true", true}`, `{"OK", true}` etc.
    {"y",   true},
    {"yes", true},
    {"n",   false},
    {"no",  false}, 
};

private static bool ReadBool(string title) {
  // keep asking user until known response is provided
  while (true) {
    if (!string.IsNullOrWhiteSpace(title)) 
      Console.WriteLine(title);

    // if we know the response for user's input, return it
    // .Trim() - let's be nice and tolerate leading and trailing spaces
    if (s_Bools.TryGetValue(Console.ReadLine().Trim(), out bool result))
      return result;

    Console.WriteLine("");
    Console.WriteLine(" Please enter a valid choice"); 
  }
}

Then you can use it as simple as

if (ReadBool("Please, make your choice (yes/no)")) {
  //TODO: Relevant code for "Yes"
}
else {
  //TODO: Relevant code for "No"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.