I know I could have done it in a different way to yield the result but for the sake of learning:
If I dobool test = IsDefined(null), the following method returnstrue. Why? Isn't it supposed to befalse && true yieldsfalse?
private bool IsDefined(object obj)Yes false && true = false.
{
bool n = (obj != null);
bool a = (obj is string);
bool b = (obj is string) ? ((string)obj != string.Empty) : true;// Make sure the object is not null and if it is a string it is not string.Empty
return (obj != null &&
(obj is string) ? ((string)obj != string.Empty) : true);
}
If you pass null your vars (n,a,b) are:
n: False, a: False, b: True.
This is right, No it isn't NOT null, No it isn't a string, and lastly yes it is NOT NOT a string. your logic is a little backwards. it should be:
bool b = (obj is string) ? ((string)obj != string.Empty) : false;
which would return false now.
with shorthand conditional it's (condition) ? true : false;
I disagree.
First please read the comments I put before I do a return. It is exactly what I wanted. I want this method to return True if the input is not null, or if it is a string it must not be an empty string.
For the callIsDefined(null);:
bool n checks if the input is null. It returns as expectedfalse because (null != null) yields false.
bool a checks if the input is a string. It returns as expectedfalse because(null is string) yields false.
bool b checksif (a == true) then whatever else true. It returnstrue as expected because we just said bool a is false.
Now. Think again. My return statement should be equivalent to:
return (n && b);as infalse && true, right? But the return value of this method is not the same asreturn (n && b); ie.(false && true). Meaning,IsDefined(null) returns me true!
Here's the exact same code above for convenience:
private bool IsDefined(object obj)
{
bool n = (obj != null);
bool a = (obj is string);
bool b = (obj is string) ? ((string)obj != string.Empty) : true;// Make sure the object is not null and if it is a string it is not string.Empty
return (obj != null &&
(obj is string) ? ((string)obj != string.Empty) : true);}
I think I found the answer:
return (false && false ? true : true);gives me respectivelytrue andfalse!return (false && (false ? true : true));
Parenthesises make a difference... =P
yep, parens.
0 comments:
Post a Comment