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

Time:07-04

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#?

CodePudding user response:

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
  • Related