Wednesday, May 11, 2011

Handy use of extension method on a bool

I don’t like to overuse if/else statements.  I really dislike seeing code like this:

if(somethingIsTrue) { DoSomethingWhenTrue( ) ; } else { DoSomethingElse( ) ; }

I just had an idea about using extension methods so I can write this instead:

somethingIsTrue.Branch( ( ) => DoSomethingWhenTrue( ), ( ) => DoSomethingElse( ) ) ;

… and here’s the extension method:

public static void Branch(this bool @bool, Action left, Action right) { if( @bool ) { left( ) ; } else { right( ) ; } }

Nice or not? I think it reads a bit better (for single line expressions anyway).

3 comments:

Unknown said...

How about ...

somethingIsTrue ? DoSomethingWhenTrue( ) ; : DoSomethingElse( ) ;

... ? (it's faster than delegating)

Steve Dunn said...

True, the unary operator is more terse but I'm not sure any more expressive.

Valid point. re. speed. I certainly wouldn't use it in a tight loop!

Anonymous said...

Not! Branch looks like a function, so a naive user would expect both arguments to be evaluated. Sure, if all of your team eats, drinks and breathes LINQ nothing will ever go wrong, but to me it smacks of obfuscation

DC