Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, quick way to invert a nullable bool?

Tags:

c#

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.

like image 209
JL. Avatar asked Mar 17 '10 13:03

JL.


2 Answers

myBool = !myBool;

Edit: OK, based on a refined understanding of the question (i.e. myBool says null if it was null), the above is the simplest answer.

like image 109
Adam Wright Avatar answered Oct 12 '22 22:10

Adam Wright


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   |
|---------|-----------|
like image 37
Allen Rice Avatar answered Oct 12 '22 22:10

Allen Rice