How to make a write method in the variable in which it extends?

1

I had an idea to apply in loops and wanted to do a bool.toogle() method where the variable is extended, the method would receive the opposite value. Something like this:

bool variavel = true;

variavel.toogle();

//variavel agora possui o valor false
    
asked by anonymous 11.06.2015 / 20:51

2 answers

1

If you want to use Extension Methods it would look something like this:

using System;

public static class ExtensionMethods
{
    public static bool toggle(this bool value)
    {
         return !value;
    }
}

And to use

class Program
{
    static void Main()
    {
        bool variavel = true;
        variavel = variavel.toggle(); // false
    }
}

-

Another solution is passing the object reference.

public static void toggle(ref bool value)
{
    value = !value;
}

public static void Main()
{
    bool variavel = true;
    toggle(ref variavel); // false
}
    
11.06.2015 / 21:05
4

What you can do is simply deny the variable.

bool toggle = true;

toggle != toggle; // toggle = false
toggle != toggle  // toggle = true
    
11.06.2015 / 21:02