Capn Jack Capn Jack - 1 month ago 5
C# Question

How to make false of a concise if statement do nothing

If I have:

logicBeingTested.isItTrue ? (doSomeStuffIfItsTrue) : (doSomeNothingIfFalse);


how do I make it so if my argument is true it only does the true half of that statement and not false. I tried doing this:

logicBeingTested.isItTrue ? (status = true) : ();


but that doesn't work. I know I can get around this by just doing an if statement but for curiosity's sake is it possible to give an answer of do nothing to an argument?

EDIT: my bool value 'status' from the OP was kinda misleading, I clarified what I want in the new edit

Answer

I'd say best to read is also best to write:

status |= logicBeingTested.isItTrue;

Just assigning a value (even if it's useless) may be as fast as a conditional instruction (which will probably involve CMOV and it's such minor optimization that should be probably ignored) and much more readable (IMO?).

If status is Nullable<bool> then simply go back to a plain if (edit: from comments it seems that it's not clear but it works with bool?, I just consider if more clear in this case. Jeroen also noted that if status is a property it will involve a different behavior but we all have trivial property getters, right?).

if (logicBeingTested.isItTrue)
    status = true;

Note that status |= logicBeingTested.isItTrue is - on contrary to what it may be thought at first sight - equivalent to that if block, if logicBeingTested.isItTrue is false then status is unchanged (not false) then if it was null it's still null. This is (IMO) a good reason to use the if if you're working with bool?.

A note about your original code: ternary operator ?: is usually used as a function and not because of side effects of its operands evaluation. It may be pretty misleading when reading that code.


Addendum for edited question: if you're not just assigning a value to a variable but you need to perform an action then nothing is more clear than an old if:

if (logicBeingTested.isItTrue)
    DoSomething();

Note that if logicBeingTested may be null then you may rewrite it as:

if (logicBeingTested?.isItTrue ?? false)
    DoSomething();

In this case if logicBeingTested you behave as logicBeingTested.isItTrue was false, to do the opposite just use ?? true.

Comments