DotNet/Answer Detail

How to use enum item name which contains space?

beginer
beginer
48 Points
19 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?

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

Share:   fb twitter linkedin
Answers
nik
nik
Member
40 Points
10 Posts
Marked as answer      

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
48 Points
19 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
Participant
332 Points
101 Posts
Marked as answer      

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

Blog

Active User (2)

 Log In to Chat