So I have a simple method called Invert:
public static void Invert(this bool value)
{
value = !value;
}
It is inside of a static class in a .dll file. Now when I go to a new Winforms project, I add the .dll as a reference and everything is good so far. Now when I do this:
bool test = true;
test.Invert();
I get no errors, but when I do:
MessageBox.Show(test.ToString());
It outputs true, as if nothing has changed. I am not sure if it because of what I am doing in the method or something else. But if I go:
MessageBox.Show((!test).ToString());
It outputs false.
Thanks.
That’s working correctly. Because
boolis a value type, it’s passed as a value and the original variable (test) is not ever being changed.Instead you should do something like:
However, creating a method that does what the language does itself is a bit of a waste of time.
I don’t think extension methods will let you take a
thisparameter by reference, so you would have to use a regular static method, and call it the long way:In the end, it’s going to be a lot cleaner and easier (not to mention more obvious to other developers) to just do it this way: