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( ) ;
}
}
}
@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