Solved

Get the enum value from enum

Posted on 2014-03-05
13
286 Views
Last Modified: 2014-03-06
I have an enum

 enum CommodityCalendar
        {
            January = 'F',
            February = 'G',
            March = 'H',
            April = 'J',
            May = 'K',
            June = 'M',
            July = 'N',
            August = 'Q',
            September = 'U',
            October = 'V',
            November = 'X',
            December = 'Z'
        }

I need to get the values , F, G depending on a string passed to some method

I tried the following, but it retuns the value such as January if I pass 01/10/2014, I need the value F to be returned

 public static void GetLetterCode(string monthName)
        {
           CommodityCalendar calendar = new CommodityCalendar();
           string test = (string)Enum.Parse(typeof(CommodityCalendar), monthName);
        }
0
Comment
Question by:countrymeister
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 2
  • +2
13 Comments
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 39906574
http://msdn.microsoft.com/en-us/library/sbbt4032.aspx

enum should not be used with a string (F, G....) value.  You might be better coding a small class/function to do what you want
0
 
LVL 1

Author Comment

by:countrymeister
ID: 39906599
Andy

Thanks for your comments

Take a look a this

        enum CommodityCalendar
        {
         
            [StringValue("F")]
            January = 'F',
            [StringValue("G")]
            February = 'G',
            [StringValue("H")]
            March = 'H',
            [StringValue("J")]
            April = 'J',
            [StringValue("K")]
            May = 'K',
            [StringValue("M")]
            June = 'M',
            [StringValue("N")]
            July = 'N',
            [StringValue("Q")]
            August = 'Q',
            [StringValue("U")]
            September = 'U',
            [StringValue("V")]
            October = 'V',
            [StringValue("X")]
            November = 'X',
            [StringValue("Z")]
            December = 'Z'
        }

and here is the helpful link

http://www.codeproject.com/Articles/11130/String-Enumerations-in-C which helped me
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 39906627
Interesting - but I notice that is using a helper class to extract the attribute.  Have you followed the example in the link  rather than attempting to code it yourself ?
0
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 
LVL 19

Accepted Solution

by:
Ken Butters earned 350 total points
ID: 39906863
Don't know if this is the best way or not... but it worked:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

enum CommodityCalendar
{
    January = 'F',
    February = 'G',
    March = 'H',
    April = 'J',
    May = 'K',
    June = 'M',
    July = 'N',
    August = 'Q',
    September = 'U',
    October = 'V',
    November = 'X',
    December = 'Z'
}

namespace ConsoleApplication1
{
    public class EnumTest
    {

        public Char GetLetterCode(String monthName)
        {
            Enum myEnum = new CommodityCalendar();

            myEnum = (CommodityCalendar)Enum.Parse(typeof(CommodityCalendar), monthName);

            return (Char) Convert.ToDecimal(Enum.Format(typeof(CommodityCalendar), myEnum, "d"));
        }

        static void Main()
        {
            EnumTest myEnumTest = new EnumTest();
            Char myLetter;

            myLetter = myEnumTest.GetLetterCode("January");

        } 
    }
}

Open in new window

0
 
LVL 40
ID: 39907314
When you define the values of an enum as a character, the numeric value of the character is recorded.

Simply cast it to a char to get back the letter:

(char) CommodityCalendar.January
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39908001
I agree with JamesBurger. Another approach you might take, though, is to create a string-typed enum by way of a class instead. For example:

public class CommodityCalendar 
{
    private CommodityCalendar(string value)
    {
        this.Value = value;
    }

    public string Value { get; private set; }
    
    public static readonly January = new CommodityCalendar("F");
    public static readonly February =  new CommodityCalendar("G");
    public static readonly March =  new CommodityCalendar("H");
    public static readonly April =  new CommodityCalendar("J");
    public static readonly May =  new CommodityCalendar("K");
    public static readonly June =  new CommodityCalendar("M");
    public static readonly July =  new CommodityCalendar("N");
    public static readonly August =  new CommodityCalendar("Q");
    public static readonly September =  new CommodityCalendar("U");
    public static readonly October =  new CommodityCalendar("V");
    public static readonly November =  new CommodityCalendar("X");
    public static readonly December =  new CommodityCalendar("Z");
    
    public static CommodityCalendar Parse(string value)
    {
        if (string.Equals(value, CommodityCalendar.January.Value, StringComparison.OrdinalIgnoreCase)) return CommodityCalendar.January;
        if (string.Equals(value, CommodityCalendar.February.Value, StringComparison.OrdinalIgnoreCase)) return CommodityCalendar.February;
        if (string.Equals(value, CommodityCalendar.March.Value, StringComparison.OrdinalIgnoreCase)) return CommodityCalendar.March;
        if (string.Equals(value, CommodityCalendar.April.Value, StringComparison.OrdinalIgnoreCase)) return CommodityCalendar.April;
        if (string.Equals(value, CommodityCalendar.May.Value, StringComparison.OrdinalIgnoreCase)) return CommodityCalendar.May;
        if (string.Equals(value, CommodityCalendar.June.Value, StringComparison.OrdinalIgnoreCase)) return CommodityCalendar.June;
        if (string.Equals(value, CommodityCalendar.July.Value, StringComparison.OrdinalIgnoreCase)) return CommodityCalendar.July;
        if (string.Equals(value, CommodityCalendar.August.Value, StringComparison.OrdinalIgnoreCase)) return CommodityCalendar.August;
        if (string.Equals(value, CommodityCalendar.September.Value, StringComparison.OrdinalIgnoreCase)) return CommodityCalendar.September;
        if (string.Equals(value, CommodityCalendar.November.Value, StringComparison.OrdinalIgnoreCase)) return CommodityCalendar.November;
        if (string.Equals(value, CommodityCalendar.December.Value, StringComparison.OrdinalIgnoreCase)) return CommodityCalendar.December;
        
        throw new ArgumentException("Unrecognized value.", "value");
    }
}

Open in new window


So what you have above is a class that cannot be instaniated externally from the class itself, and you have a number of static instances that cannot be modified--the references themselves are marked readonly and the set is private, so it can only be called from within the class itself. It doesn't use the enum keyword, but it works effectively the same:

CommodityCalendar month = CommodityCalendar.January;

Open in new window


When you want to get the underlying value, you simply grab it from the Value property:

public static void GetLetterCode(string monthName)
{
    CommodityCalendar month = CommodityCalendar.Parse(monthName)
    string test = month.Value;
}

Open in new window

0
 
LVL 40
ID: 39908116
What is the advantage of creating a class with 40 lines of code when you can simply do it with a cast?

(char) CommodityCalendar.January
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39908176
In this case, yes, it may be overkill. But if the requirement ever changes, and the code becomes two letters instead of one, then char goes out the window. It was intended simply to show another way. [Anyway, it's only 40 lines of code because I included the Parse method  ; )  ]
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 39908471
cough, cough.  From the first comment:
You might be better coding a small class/function to do what you want

Not only does that method cope with returning strings but one can also build in support for various things - supply a date, month name as string, month as number (1..12) ....
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39908545
Sorry Andy. I completely glossed over that part of your comment. I just saw the link to the enum documentation  : \

The only differentiation I could make would be that my suggested code is by design intended to emulate an enum, whereas "create a class" could be interpreted in a bit more of an open-ended manner.
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 39908575
Agreed, but it could be used in a single line of code (like an enum can be used simply)
String s1 = Foo.MonthCode("January");
String s2 = Foo.MonthCode(25.12.2000);
rather than with all sorts of casts, parses, converts etc in multiple places
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 39908585
ps.  Don't forget the original usage (from the question) is the month name is a variable
so it isn't required like:
Foo.January
but rather like:
Foo.s where s is "January"
0
 
LVL 1

Author Closing Comment

by:countrymeister
ID: 39910033
I had a solution even before the experts posted their comments, and Ken Butters was another way of doing it.
0

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question