Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum and string match

Tags:

c#

enums

I'm essentially trying to read an xml file. One of the values has a suffix, e.g. "30d". This is meant to mean '30 days'. So I'm trying to convert this to a DateTime.Now.AddDays(30). To read this field in the XML, i decided to use an Enum:

enum DurationType { Min = "m", Hours = "h", Days = "d" }

Now I'm not exactly sure how exactly to approach this efficiently (I'm a little daft when it comes to enums). Should I separate the suffix, in this case "d", out of the string first, then try and match it in the enum using a switch statement?

I guess if you dumb down my question, it'd be: What's the best way to get from 30d, to DateTime.Now.AddDays(30) ?

like image 341
mnsr Avatar asked Feb 26 '13 00:02

mnsr


People also ask

Can I compare enum with string?

For comparing String to Enum type you should convert enum to string and then compare them. For that you can use toString() method or name() method. toString()- Returns the name of this enum constant, as contained in the declaration.

How do you find the enum value of a string?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

Can we use .equals for enum?

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.


1 Answers

You could make an ExtensionMethod to parse the string and return the DateTime you want

Something like:

    public static DateTime AddDuration(this DateTime datetime, string str)
    {
        int value = 0;
        int mutiplier = str.EndsWith("d") ? 1440 : str.EndsWith("h") ?  60 : 1;
        if (int.TryParse(str.TrimEnd(new char[]{'m','h','d'}), out value))
        {
            return datetime.AddMinutes(value * mutiplier);
        }
        return datetime;
    }

Usage:

 var date = DateTime.Now.AddDuration("2d");
like image 197
sa_ddam213 Avatar answered Sep 30 '22 01:09

sa_ddam213