1

I have defined an enum as following.

public enum Month
{
    January,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December
}

I am getting and sending it back to client.

public List<Month> GetMonths()
{
    return Enum.GetValues(typeof(Month)).Cast<Month>().ToList();
}

However, I am receiving 0,1,2,3,....11 values at client end instead of actual string values i.e. month names.

How i can send actual month name as values?

3 Answers 3

3

You can use the GetNames method on Enum:

public string[] GetMonths()
{
    return Enum.GetNames(typeof(Month));
}
Sign up to request clarification or add additional context in comments.

2 Comments

You're not converting it to list? why?
Well, you are not saying what is your client, but seems like you are serializing to JSON later, for JSON there is no List everythin is an array so you don't need to convert it. If you want you can do a ToList and return a List<string>
1

Newtonsoft.Json.Converters provides StringEnumConverter.

Usage:

[JsonConverter(typeof(StringEnumConverter))]
public Enum SomeProperty { get; set; }

Comments

1

Use this code to get list of string.

using Enum static method method GeNames.

List<string> monthsName =Enum.GetNames(typeof(Month)).ToList();

3 Comments

Dont you require to cast it to Month i..e return Enum.GetNames(typeof(Month)).Cast<Month>().ToList();
@simbada: why do I need to cast . It will correctly return List<string>. I have tested It.
My mistale u dont need to since you are doing List<string>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.