Simple string comparison failing with gender check

Viewed 503

I am asking input for user gender and valid values are only

  • Male
  • Female

Code :

        string gender = Console.ReadLine();
        if(gender!="Male" || gender !="Female")
        {
            Console.WriteLine("Invalid gender");
        }

Problem here is even If I enter Male or Female it goes in if logic and shows "Invalid Gender". I just don't understand why this is happening with this simple string comparision

2 Answers

You need to make sure the gender is not Male AND not Female.

string gender = Console.ReadLine();
if (gender != "Male" && gender != "Female")
{
    Console.WriteLine("Invalid gender");
}

I think this is a simple mistranslation of the verbal logic to c# logic. If you were to say to another human "if gender is not [equal to] male or female show an error" they'd know what you wanted and this is a very natural way to say this.

Humans probably see this as a list of valid options, mentally take the input and search the list and if not found they say it's an error. This cannot be expressed directly in c# like it is verbally, using just simple comparison operators

I.e you cannot say:

if(gender != "Male" || "Female")

Because you have to test gender against both. I think you then extended the incorrect c# above so that it is syntactically valid:

if(gender != "Male" || gender != "Female")

This is syntactically valid but not logically valid; now one side of the OR is always true, no matter what you type.


So my assertion is that thing went wrong quite early on. Think back to how the verbal was turned to c#

//"if gender is not equal to male or female show an error"
if(gender != "Male" || "Female")

If we read the English reasoning from left to right we can incorrectly seize upon the first phrase and make it a condition - "if gender is not equal to Male". Really, for successful translation this needs to be read backwards, so that we seize onto the "Male or female" part first. This expression is logically correct:

//"if gender is not equal to (male or female) show an error"
if( !(gender == "Male" || "Female") )

Then we can just expand it to make it syntactically valid:

if( !(gender == "Male" || gender == "Female") )

This final form is a lot closer to how we talk about the logical things. This form is also valid:

if( (gender != "Male" && gender == "Female") )

You can memorize this as a rule - to rewrite a logic of NOT(x EQUALS y OR x EQUALS z) you can remove the not and invert the equals and also swap or for and, and vice versa thus (x NOTEQUALS y AND x NOTEQUALS z)

This letter form is also valid but you're less likely to say to another human "if gender equals not male and not female"


ps: in a case of more than maybe two or three items it may be clearer to have a list of valid options and say:

if(!validOptions.Contains(gender))

Which also is an expression of how humans might mentally approach the task for longer lists

Related