How to use enum item name which contains space?

beginer
beginer
Member
1328 Points
43 Posts

I want to define following enum

public enum OrderStatus 
{
  Pending,
  Completed,
  Cancelled,
  Refunded,
  Partial Refund
}

Some time we need to show description.  I want to show 'Partial Refund' not 'PartialRefund'. Is there any solution for this?

Views: 10572
Total Answered: 3
Total Marked As Answer: 2
Posted On: 23-Jan-2018 01:25

Share:   fb twitter linkedin
Answers
nik
nik
Member
166 Points
6 Posts
         

Yes, the EnumMemberAttribute is designed exactly you want.

public enum OrderStatus 
{
  Pending,
  Completed,
  Cancelled,
  Refunded,
  [EnumMember(Value = "Partial Refund")]
  PartialRefund
}

Need to import package

using System.Runtime.Serialization;

 

Posted On: 23-Jan-2018 02:47
beginer
beginer
Member
1328 Points
43 Posts
         

Thanks nik,

When I get json response through action method we get the attribute value as I wish, but when I need enum member value in C# code for server side report generation i.e. csv, excel, html etc.

I am trying following code

var pr = OrderStatus.PartialRefund.ToString()
//output "PartialRefund"

I want output as

"Partial Refund"
Posted On: 31-Jan-2018 04:05
Smith
Smith
None
2568 Points
74 Posts
         

Use following extension method

public static class Extensions
    {
        public static string GetName<T>(this Enum enumVal) where T : System.Attribute
        {
            var type = enumVal.GetType();
            var memInfo = type.GetMember(enumVal.ToString());
            var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
            return (attributes.Length > 0) ? ((System.Runtime.Serialization.EnumMemberAttribute)attributes[0]).Value : enumVal.ToString();
        }      
    }

Use it as

var pr = OrderStatus.PartialRefund.GetName<EnumMemberAttribute>();
Posted On: 31-Jan-2018 04:51
 Log In to Chat