-1

I have written a simple conditional statement, in which I'm getting a string input from the user, checking if it's equal to something but the nature of my code makes me add a single more operand to operate between

I tried this but it gives an error that you can't operate between two strings, obv there is some logical fallacy but I want a similar solution to this problem

if (Console.ReadLine() == ("s"||"S"))

Now I know this works if I make a separate variable and just check with it for both "S" and "s", but I want to do it inline and within that single statement, If I add another "Readline()" it will just take two inputs and won't do what I want it to do.

If there is anyway to make this work within that line, please let me know.

2 Answers2

1

You have to declare the variable outside the condition, but you can do everything else in one line.

You can use is to make it slightly more readable (but only works for literal comparison).

string input;
if ((input = Console.ReadLine()) is "s" or "S")

Or if you have to use == then

string input;
if ((input = Console.ReadLine()) == "s" || input == "S")

Would I suggest doing this? No. Do the sane thing by not cramming all this logic in one line.

string input = Console.ReadLine();
if (input is "s" or "S")
gunr2171
  • 16,104
  • 25
  • 61
  • 88
-2

What about trying

if (Console.ReadLine().ToLower() == "s")
  • 1
    This solution falls apart as soon as the options are not the same letter with different capitalization. – gunr2171 Feb 08 '23 at 05:01
  • 2
    And `string.Equals` with the appropriate comparer would be better than this solution. – ProgrammingLlama Feb 08 '23 at 05:02
  • 3
    Using `.ToLower()` creates a new `String` instance (and associated memory copy) which adds to the GC heap which is inefficient. Instead of normalizing strings for case-insensitive comparison use `StringComparer.OrdinalIgnoreCase` instead - which will be zero-allocation. (Also, using `ToLower()` is incorrect anyway because it's sensitive to `CurrentCulture` _and_ [it doesn't normalize certain non-Latin characters correctly, such as the Turkish "I"](https://haacked.com/archive/2012/07/05/turkish-i-problem-and-why-you-should-care.aspx/) - use `.ToUpperInvariant()` instead. – Dai Feb 08 '23 at 05:08