A few days ago I needed to toggle a bool
, and I ended up doing like so:
IsVisible = !IsVisible;
I found that to be the simplest way to archive that functionality. But before doing like the example above, I tried out some different ways.
Mostly about using a extension method. Which in my opinion would make it even simpler, or at least less chars to write.
IsVisible.toggle();
But as a boolean
is a value type, the bool
that is sent though to the extension method is a copy of the original bool
, and not a reference type.
public static void Toggle(this boolean value)
{
value = !value;
}
Which would do what I needed, but as the boolean
getting toggled is a copy of the original boolean
the change isn't applied to the original...
I tried putting the ref keyword in front of boolean
, but that didn't compile.
And I still haven't found a reason for that not compiling, wouldn't that be the perfect functionality for extension methods?
public static void Toggle(this ref boolean value)
I even tried casting the boolean
into a object, which in my head would make it into a reference type, and then it would no longer be a copy and the change would get passed back. That didn't work either.
So my question is if it's possible to make a extension pass back changes, or another way to make it even simpler than it already is?
I know it quite possible won't get any simpler or more logical than the top example, but you never know :)
Extension methods cannot be overridden the way classes and instance methods are. They are overridden by a slight trick in how the compiler selects which extension method to use by using "closeness" of the method to the caller via namespaces.
You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called.
The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.
Actually I'm answering the question of why extension methods cannot work with static classes. The answer is because extension methods are compiled into static methods that cannot recieve a reference to a static class.
Primitive types are immutable. You'll have to write your calling code like this:
IsVisible = IsVisible.Toggle();
That's the best you can do with extension methods. No way around it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With