2

I had this set of Enums for currency purpose

[DataContract]
public enum PaymentCurrency
{

    /// <summary>
    /// Canadian dollar.
    /// </summary>
    [EnumMember(Value = "CA$")]
    CAD = 1,
}

When I want to display the particular item , for example CAD , I want it to show as "CA$" string . I tried it by assigning a value to it , it is not working and I haven't got much clue . Any ideas ? Thanks .

1 Answer 1

2

The value argument of the EnumMember attribute is there for serialization. Not display purposes. See MSDN Documentation.

To get at that value you'd have to serialize it then parse the XML.

Another way is to write your own helper method and take advantage of C# built-in DescriptionAttribute:

public enum PaymentCurrency
{
  [DescriptionAttribute("CA$")]
  CAD,
  [DescriptionAttribute("US$")]
  USD,
  EURO
}

Then using your own helper methods in an EnumUtils class you could do this:

public class EnumUtils
{
  public static string stringValueOf(Enum value)
  {
    var fi = value.GetType().GetField(value.ToString());
    var attributes = (DescriptionAttribute[]) fi.GetCustomAttributes( typeof(DescriptionAttribute), false);
    if (attributes.Length > 0)
    {
        return attributes[0].Description;
    }
    else
    {
        return value.ToString();
    }
  }

  public static object enumValueOf(string value, Type enumType)
  {
    string[] names = Enum.GetNames(enumType);
    foreach (string name in names)
    {
      if (stringValueOf((Enum)Enum.Parse(enumType, name)).Equals(value))
      {
          return Enum.Parse(enumType, name);
      }
    }

    throw new ArgumentException("The string is not a description or value of the specified enum.");
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.