I have a nullable bool. What is a quick way to invert it. In otherwords if value is TRUE make it FALSE, otherwise make it TRUE.
To clarify (from the comments):
Expected behavior is: if the nullable bool has a value, then invert, otherwise should return null.
myBool = !myBool;
编辑:好的,基于对问题的精确理解(即,如果myBool
为null,则myBool
说null),以上是最简单的答案。
Edit, drblaise is right, !
works just fine
bool? a = null;
bool? b = false;
bool? c = true;
a = !a;
b = !b;
c = !c;
Assert.AreEqual(a, null);
Assert.AreEqual(b, true);
Assert.AreEqual(c, false);
here is the truth table, I know, it's boring but I wanted to see how SO handled "tables"
value !value
|---------|-----------|
| null | null |
|---------|-----------|
| false | true |
|---------|-----------|
| true | false |
|---------|-----------|
x =!(x ?? false)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.