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

Asked

Viewed 92 times

1

I had an idea to apply in loops and wanted to make a method bool.toogle() where the variable extends the same value will receive the opposite value. Something like this:

bool variavel = true;

variavel.toogle();

//variavel agora possui o valor false
  • That is not possible. bool is a value type, logo is passed by value and not by reference. Any change within the method is not effected at the original value.

  • I discovered in my tests that this is really impossible in C#, but in VB.NET works using Byref

  • In C# there is also the possibility to pass value type by reference, declaring these parameters with ref or out, however, in extension methods, it is not allowed to do so in the first parameter, the one that is preceded by this.

2 answers

4

What you can do is just deny the variable.

bool toggle = true;

toggle != toggle; // toggle = false
toggle != toggle  // toggle = true
  • I did this, I saw that it works perfectly. the goal of creating a bool.toogle() was to make the language more friendly.

  • Since no one answered the question, if an answer was accepted it should be this.

1


If you want to use Extension Methods it would be something like that:

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
}
  • This was the closest solution I found, but run away from what I really wanted to do was not having to repeat the variable name (variable = variable.toggle();)

  • @Kaizonaro I made another solution, not exactly with Extension Methods, but does without assigning directly.

  • What would be the other solution

  • @Kaizonaro I updated in my reply

  • Thanks, that already simplifies a lot

Browser other questions tagged

You are not signed in. Login or sign up in order to post.