views:

136

answers:

2

Hi :)

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 functionaily. But before doing like the example above, i tried out some different ways.

Mostly about using a extension method. Which in my opinon would make it even simplier, 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 isnt applied to the original..

I tried putting the ref keyword infront of "boolean", but that didn't compile. And i still haven't found a reason for that not compiling, wouldnt 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 its possible to make a extension pass back changes, or another way to make it even simplier than it already is?

I know it quite possible won't get any simplier or more logical than the top example, but you never know :)

Thanks in advance.

+7  A: 

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.

Joel Coehoorn
maybe IsVisible = Boolean.Toggle() ?
abatishchev
No - how would "Boolean" as a type know about the state contained the "IsVisible" instance? The right-hand expression _must_ include the variable somewhere.
Joel Coehoorn
structs are value types but unfortunately they are not immutable by default.
Brian Rasmussen
Oops: yeah, I meant "primitive type", editing.
Joel Coehoorn
Thought so, thanks for great answers :)
Moulde
+1  A: 

as an aside: wouldn't an extension method be an incredible overhead for something as simple as toggling a bool?

obelix
Yes it would. It's not encapsulating a combination of steps, it's leading you to avoid using a built-in operator. I try to stick with idiomatically sensible code and do my best to avoid writing DSLs (until it makes sense to).
48klocs