Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in C# what does 'bool = bool != true' mean?

In my hunt for some help to a problem I was having I came across this:

p.Enabled = p.Enabled != true;

What exactly does this mean? Ive never seen it before,

nb: the preceeding line was var p = this.PageRepository.GetPage(id);

like image 475
LenPopLilly Avatar asked Mar 06 '12 18:03

LenPopLilly


2 Answers

When p.Enabled is a normal bool, as Enabled properties usually are,

p.Enabled = p.Enabled != true;

is the same as

p.Enabled = ! p.Enabled;

in other words: it flips or toggles p.Enabled.

Now when Enabled is a bool? , shorthand for Nullable<bool> , the results are different:

! ((bool?) null)           -> null
((bool?) null) != true     -> true 

So p.Enabled = p.Enabled != true will set true when the old value was false or null.

like image 93
Henk Holterman Avatar answered Sep 21 '22 06:09

Henk Holterman


It's an awkwardly written bool toggle switch. Each call toggles the state from true to false. I'd have written it:

p.Enabled = !p.Enabled;

Edit - I suppose I should say, awkwardly written in my opinion only.

like image 38
asawyer Avatar answered Sep 21 '22 06:09

asawyer