Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Enum Mapper in C#
public class EnumMapper : IDisposable
{
readonly Dictionary<Type, Dictionary<string, object>> _stringsToEnums =
new Dictionary<Type, Dictionary<string, object>>( ) ;
readonly Dictionary<Type, Dictionary<int, string>> _enumNumbersToStrings =
new Dictionary<Type, Dictionary<int, string>>( ) ;
readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim( ) ;
public object EnumFromString( Type type, string value )
{
populateIfNotPresent( type ) ;
return _stringsToEnums[ type ][ value ] ;
}
public string StringFromEnum( object theEnum )
{
Type typeOfEnum = theEnum.GetType( ) ;
populateIfNotPresent( typeOfEnum ) ;
return _enumNumbersToStrings[ typeOfEnum ][ (int) theEnum ] ;
}
void populateIfNotPresent( Type type )
{
_lock.EnterUpgradeableReadLock( ) ;
try
{
if( !_stringsToEnums.ContainsKey( type ) )
{
_lock.EnterWriteLock( ) ;
try
{
populate( type ) ;
}
finally
{
_lock.ExitWriteLock( ) ;
}
}
}
finally
{
_lock.ExitUpgradeableReadLock( ) ;
}
}
void populate( Type type )
{
Array values = Enum.GetValues( type ) ;
_stringsToEnums[ type ] = new Dictionary<string, object>( values.Length ) ;
_enumNumbersToStrings[ type ] = new Dictionary<int, string>( values.Length ) ;
for( int i = 0; i < values.Length; i++ )
{
object value = values.GetValue( i ) ;
_stringsToEnums[ type ].Add( value.ToString( ), value ) ;
_enumNumbersToStrings[ type ].Add( (int) value, value.ToString( ) ) ;
}
}
public void Dispose( )
{
_lock.Dispose( ) ;
}
}
}
@SteveDunn
Owner

A fast (faster than reflection (Enum.Parse)) way to map enums to strings and vice-versa. Useful if you need to map between lots of enums or need to do it very quickly (or both!). Compatible with .NET 3.5 (no use of ConcurrentDictionary)

Released by Steve under the WTFPL license: http://sam.zoy.org/wtfpl/COPYING

@hummerpj

Hey Steve,

Is there any license associated with your enum mapping code? I would like to use it as-is in a project of mine.

Thanks,
Patrick

@hummerpj
hummerpj commented Jul 1, 2014

Hi Steve,

Any word on if you would be open to licensing this something like MIT? According to GitHub if there is no license posted then it is assumed copyright. I can respect if you want to leave it this way.

Thanks,
Patrick

@SteveDunn
Owner

Sorry for the delay in putting the license info there - I didn't see the e-mail alerts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment