Skip to content

Instantly share code, notes, and snippets.

@SteveDunn
Created August 17, 2011 21:25
Show Gist options
  • Save SteveDunn/1152680 to your computer and use it in GitHub Desktop.
Save SteveDunn/1152680 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link

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
Copy link

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
Copy link
Author

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