Parsing .NET Enums

I needed the following functionality:
– class MarketSession has property MarketType (options, futures, …)
– this property is an enum, but in the underlying protocol it is actually a number
– in my Spring.NET configuration I wanted to specify a string which would be either a symbolic name or a number; one would use symbolic names for defined market types and numbers for the market types that did not make it yet into the enum

I was pleasantly surprised to find out, that the built-in Enum.Parse() provides exactly what I need. You can give it either a symbolic name, or a numeric value, and it will work fine, even if the value is out of range.

enum MarketType
    Futures = 10,
    Options = 20

public class MyClass
    MarketType _marketType;

    public string MarketType
        get { return _marketType.ToString(); }
        set { _marketType = Parse<MarketType>(value); }

    private static T Parse<T>(string s)
        return (T)Enum.Parse(typeof(T), s);

Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *