Search code examples
c#booleanextension-methods

Is it possible to alter a bool value by calling an extension method on the same variable in c#?


In swift, it is possible to toggle a Boolean by simply calling .toggle() on the var.

var isVisible = false
isVisible.toggle()  // true

I wanted to create the same functionality in C#, so I wrote an extension method on bool

public static class Utilities {
    public static void Toggle(this bool variable) {
        variable = !variable;
        //bool temp = variable;
        //variable = !temp;
    }
} 

However, it does not work, and I suspect that it has to do with bool in C# being value types, where as they are reference types in swift.

Is there a way to implement the same toggle function in C#?


Solution

  • You can do it by accepting the this bool object by reference:

    public static class Utilities
    {
        //-----------------------------vvv
        public static void Toggle(this ref bool variable)
        {
            variable = !variable;
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            bool b1 = true;
            Console.WriteLine("before: " + b1);
            b1.Toggle();
            Console.WriteLine("after: " + b1);
        }
    }
    

    Output:

    before: True
    after: False
    

    Note: this feature is available only from C# 7.2. See here.