Can I 'invert' a bool?

C#Boolean

C# Problem Overview


I have some checks to see if a screen is active. The code looks like this:

if (GUI.Button(new Rect(Screen.width / 2 - 10, 50, 50, 30), "Rules")) //Creates a button
	{
		if (ruleScreenActive == true) //check if the screen is already active
			ruleScreenActive = false; //handle according to that
		else 
			ruleScreenActive = true;
	}

Is there any way to - whenever I click the button - invert the value of ruleScreenActive?

(This is C# in Unity3D)

C# Solutions


Solution 1 - C#

You can get rid of your if/else statements by negating the bool's value:

ruleScreenActive = !ruleScreenActive;

Solution 2 - C#

I think it is better to write:

ruleScreenActive ^= true;

that way you avoid writing the variable name twice ... which can lead to errors

Solution 3 - C#

ruleScreenActive = !ruleScreenActive;

Solution 4 - C#

This would be inlined, so readability increases, runtime costs stays the same:

public static bool Invert(this bool val) { return !val; }

To give:

ruleScreenActive.Invert();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSimon VerbekeView Question on Stackoverflow
Solution 1 - C#Ahmad MageedView Answer on Stackoverflow
Solution 2 - C#JackView Answer on Stackoverflow
Solution 3 - C#MusiGenesisView Answer on Stackoverflow
Solution 4 - C#JackView Answer on Stackoverflow