Wednesday, August 17, 2011

A fast way of converting C# enums to strings–and back again.

I recently needed a fast way of converting lots of enums to strings (and back again).  I needed to do it very quickly.  ‘Enum.Parse’ just wasn’t fast enough.

I discovered there was no ‘enum mapper’ in C#, so I knocked up this little class.  It uses reflection just once when it comes across a new enum.

It’s compatible with .NET 3.5 too.

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).