views:

278

answers:

7

Hi all,

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 ((Boolean.Parse(staff.getValue("Male")) | Boolean.Parse(staff.getValue("Female")))    
{   
   // is true
}

Is this correct?

Thanks

+4  A: 
bool isMale = Boolean.Parse(staff.getValue("Male");
bool isFemale = Boolean.Parse(staff.getValue("Female");
if (isMale || isFemale) // note double pipe ||
{
   // do something if true
}
sshow
+6  A: 

Sounds like you're looking for the logical OR.

if(condition1 || condition2)
{
}
p.campbell
The code given in the question already uses *one* of the logical OR operators -- `|` -- although I agree that it's almost always preferable to use the short-circuiting `||` version instead.
LukeH
@LukeH `|` is not logical OR operator. It is bitwise OR operator.
Markos
@Markos: Not in C#. For type `Boolean`, operator `|` is a non-shortcircuiting logical OR operator.
Gorpik
@Markos: From the MSDN docs: *"For `bool` operands, `|` computes the logical OR of its operands"* http://msdn.microsoft.com/en-us/library/kxszd0kx.aspx
LukeH
@Gorpik of course, bitwise operation on one bit is in fact non-shortcirtuiting logical operation.
Markos
@Markos: But it happens that in C# this operator is specifically defined as a non-shortcircuiting logical operator, as explained in LukeH's link. It is a question of concept. So your first comment is wrong.
Gorpik
+2  A: 

The conditional OR operator || is what you need

if ((Boolean.Parse(staff.getValue("Male")) || Boolean.Parse(staff.getValue("Female")))
{
   //is true
}

If the first condition is TRUE, then the second condition isn't checked since the outcome is obviously going to return TRUE.

Eton B.
The `|` operator, as used by the example code in the question, is also a logical OR operator, although I agree that it's almost always preferable to use the short-circuiting `||` version instead.
LukeH
My bad - I edited it to 'conditional' as that's how I've seen it being called.
Eton B.
A: 

A little exception checking is needed anyway. The Boolean.Parse() method gets a string as argument and returns either true or false only if the argument, once stripped out of whitespace, is equal to "True" or "False" (note capitalization). In ANY other case the function returns an exception.

Supposing that the possible values of staff.getValue("Male") and staff.getValue("Female") are exactly those two, then the simple disjunction (||) is sufficient. If any other return value is possible, including null and the empty string, then you have to check for exceptions

bool isMale;
try {
    isMale = Boolean.Parse(staff.getValue("Male"));
} catch(Exception e) {
    isMale = Boolean.False;
}
try {
    isFemale = Boolean.Parse(staff.getValue("Female"));
} catch(Exception e) {
    isFemale = Boolean.False;
}
if (isMale || isFemale) // note double pipe ||
{
    // do something if true
}

or compare manually

bool isMale = Boolean.TrueValue == staff.getValue("Male");
bool isFemale = Boolean.TrueValue == staff.getValue("Female");
if (isMale || isFemale) // note double pipe ||
{
    // do something if true
}
saverio
According to MSDN Boolean.Parse is case-insensitive. And this would be a good place to use Boolean.TryParse instead of Boolean.Parse to avoid having to do exception handling.
Phil Lamb
What is Boolean.True and even if it were valid, what is the virtue of comparing it again to a boolean? This could go on for ever: `= Boolean.True == staff.getValue("Female") == true == true == true...... == true`. Whats the point?
Michael Shimmins
You aren't "checking for exceptions." You are "swallowing exceptions and making people who inherit your code tear their hair out." This is exactly what NOT to do with exceptions; if parsing the booleans might fail, use `TryParse()` as Phil Lamb suggested. If finding a null return value will just mean you assign `false` to isMale or isFemale anyway, just use the null-coalescing operator, "??". http://msdn.microsoft.com/en-us/library/ms173224.aspx. i.e. `isMale = staff.getValue() ?? false;`
jloubert
Phil: Completely agree!!!!Michael: Typo, it was meant to be: `isMale = Boolean.TrueString == staff.getValue("Male")` and not `isMale = Boolean.True == staff.getValue("Male")`.jloubert: Rather `Boolean.Parse(staff.getValue() ?? Boolean.FalseString)` (or with TryParse).
saverio
+9  A: 

If EXACTLY ONE should be true then it is:

var male = bool.Parse(staff.getValue("Male"));
var female = bool.Parse(staff.getValue("Female"));

if (male ^ female)    
{
   //is true
}
lasseespeholt
A: 

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")); 
stimpy77
+1  A: 

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"
}
abatishchev