Boolean extension function

You cannot change the value of this, this would break a lot of assumptions, even if you could you would not be able to change the value, as Booleans are immutable.

More generally, there is a fine line between simplifying code, and making it more complex, and in this case that would complicate it. I would agree that adding String.splitByDot() may make sense, but replacing idiomatic code tends to just make the code more complex, as you start to wonder why the code had to be replaced.


Sorry but this does not make sense. Just use myBool=false, it's what anyone understands and cannot get any more readable. Also Boolean is immutable and what you're trying isn't possible anyways.

We have to be careful not to overuse extensions. It's one of the greatest features Kotlin (and others) offers, but in certain examples, e.g. trying to change the way a dead simple Boolean is being assigned, it's getting dangerous IMHO (luckily it's not possible).


Here is an extension method that works in C# 7.2 or later:

public static class Extensions
{
    public static bool Toggle(ref this bool b) => b = !b;
}

Then elsewhere, something like this will work:

bool     b1 = true; // Works for primitive bool type.
Boolean  b2 = true; // Works for Boolean object, too.
b1.Toggle(); 
b2.Toggle();

The only benefit I see to using an extension method is to shorten lines with long bool expressions, such as replacing:

this.SomeObjectWithALongName.SomeVerboselyNamedProperty
   = !this.SomeObjectWithALongName.SomeVerboselyNamedProperty

with

this.SomeObjectWithALongName.SomeVerboselyNamedProperty.Toggle();

I don't know what drawbacks this extension method may have.