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.


Steven Mortimer said...

For a while now i have been using TypeConverters to do this, pretty much the same implementation as you have here but in a TypeConverter. Theres not enough Type Converters in the world...

Adam Ralph said...

Interesting. I've been using a similar caching approach for a couple of things I've been playing about with recently.

One of these is equality of DDD Value Object types (commercial but plan to re-write as OSS soon).

The other is the beginnings of a general object pool to reduce LOH fragmentation - It's still quite trivial in its current form and does rely on 4.0 but I plan to downgrade to 3.5 using exactly the same technique as you with ReaderWriterLockSlim. This was, in fact, the method I originally used for the DDD work, but then we took a dependency on System.Threading from ReactiveExtensions which gave me ConcurrentDictionary.