Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading