C# How do I check if one of two values is TRUE?

后端 未结 8 1514
梦毁少年i
梦毁少年i 2021-01-12 13:24

Should be a simple question for the C# experts here.

I basically want to check if one value or another is TRUE, a wild stab at the code is below:

if          


        
相关标签:
8条回答
  • 2021-01-12 13:57

    Note that TryParse works more fast and more safe then just Parse because doesn't throw an exception in case of error. TryParse returns bool that indicates was parse successful or was not.

    So both parsing methods should return true and only after that - do the main check

    bool male, female;
    if ((Boolean.TryParse(staff.getValue("Male"), out male) && 
         Boolean.TryParse(staff.getValue("Female"), out female)) &&
        (male || female)) // or ^
    {
        // do stuff
    }
    

    or

    bool male, female;
    if (Boolean.TryParse(staff.getValue("Male"), out male) &&
         Boolean.TryParse(staff.getValue("Female"), out female))        
    {
        if(male) { }
        else if (female) { } // or just else
    }
    else
    {
         // staff contains wrong data. Probably "yeap" instead of "true"
    }
    
    0 讨论(0)
  • 2021-01-12 14:04

    To indicate whether a gender is specified with a value of "true" rather than "false",

    bool genderIsSpecified = staff.getValue("Male") | staff.getValue("Female");
    

    .. will only determine whether it's one of those values, not which of those values the object staff is.

    So, just in case this question is literal and not an abstract example, ...

    Male or Female .. everyone is one or the other. Perhaps in your question you meant to ask which of the two is the case? In that case,

    bool defaultGenderIfNoGenderDocumented = true; // male
    bool MaleIfTrue_FemaleIfFalse = !string.IsNullOrEmpty(staff.getValue("Male"))
        ? bool.Parse(staff.getValue("Male"))
        : string.IsNullOrEmpty(staff.getValue("Female"))
            ? bool.Parse(staff.getValue("Female"))
                ? false
                : defaultGenderIfNoGenderDocumented
            : defaultGenderIfNoGenderDocumented;
    

    Or simply,

    // assume value is properly populated, ignore "Female" value
    bool isMale = bool.Parse(staff.getValue("Male")); 
    
    0 讨论(0)
提交回复
热议问题