Label Cloud

Thursday, June 14, 2007

Alternatives to Enum(s)

I had the need to provide an enumerated value to in my code, and be able to easily convert the value to a string representation. .NET Enum can only be numeric and did not provide the functionality needed. A coworker showed me very nice way to create the same functionality with a simple class

//Using this instead of an ENum - beeing fancy internal sealed class ActionType { private readonly string _action; private ActionType(string action) { this._action = action; } public override string ToString() { return _action; } public static readonly ActionType Update = new ActionType("U"); public static readonly ActionType Delete = new ActionType("D"); }

What the class allows me to do is the following:

main() { ActionType action = ActionType.Update; action = ActionType.Delete; string sAction = action.ToString(); }

sAction will have "D" as the string representation for the Delete action.


Share/Save/Bookmark

4 comments:

Anonymous said...

hey Tim its Raf.. didn't have your email :)
but um.. what exact problems did you have with enum.ToString() because by default it should use the string value.
i just tested it here, and
TransactionType t = TransactionType.SL;
Console.WriteLine( t.ToString() );
'SL'


i personally run into some issues serializing enums to javascript using atlas and other serialization framework, that were actually using the int for which i had to create a custom serializers.. so this would also be helpful in that case..

Timur said...

This works if the string value is what I want to be in the result.
What if what I really want is this:


TransactionType t = TransactionType.SellLong;
Console.WriteLine( t.ToString() );


'SL' != 'SellLong'

Anonymous said...

i see..
but than as a developer writing code.. how will you know what ToString() returns if that value is different from your actual enum key? you could memorize, guess or look at enum definition every time you use it.. kind of non intuitive

Timur said...

The idea is to have the value be the key defined by the business rules. As a developer, you shouldn't be relying on the ToString() output since that functionality for the user or business process. The enum itself is the only thing you should be going by.