Search code examples
c#enumsenum-flags

Enum Flags conversions for Decimal values/names


I have few enum flags that represent a version of an external system. I want to ensure, that every time the external system upgrades its version, my functionality should be able to support it (I will know in advance that version will be upgraded, so its a proactive action). Also my communication has to be in both directions with this system, which means internal and external communication can have different version sets.

I have created an enum flag, to represent these versions.

[Flags]
public enum ExternalSystemVersionEnum
{
    System1 = 1,
    System2 = 2,
    System3 = 4,
    All = 7
}

This works okay for a formal major upgrades. Sadly I can't name those as System1.0 or so on. Also, as its decimals, I can't use generic enum parser.

(T) Enum.Parse(typeof (T), Convert.ToString(enumValue));

Of course I can still achieve the above by using switch/if statements instead, but I really want to avoid any hard coding at all (even Resources/Contants if I can), as one version of external system may get completely discarded, and I don't want to be bothered about having to chase down all strings.

Also I need Flags or equivalent functionality, as I may still receive communication that has no System version Identification, which by default goes to applicable to all versions. Another communication may just apply to some select versions, eg. only for 2.0 onward etc.

Please note, I can easily achieve this by using Switch/If, but I don't wish to have any hard coding, unless there's no other (simple) way. My main concern here is having a functionality that acts like flags, yet can easily identifies values with decimal places, say 1.0 or 1.2 or 1.3.1 for that matter (though in history they've never had double decimal points), and provides compile time failures. I am open to suggestions of other mechanisms, but I would really prefer it to be a simple logic, as its a very trivial part of the entire process.


Solution

  • What about

    [Flags]
    public enum ExternalSystemVersionEnum
    {
        System1_1 = 1,
        System2_1 = 2,
        System3_2 = 4,
        All = 7
    }
    
    var enumString = decimalValue.ToString("0.0", 
        CultureInfo.InvarantCulture).Replace('.', "_");
    
    var enumValue = (ExternalSystemVersionEnum)Enum.Parse(
        typeof(ExternalSystemVersionEnum), enumString);