Using String-Based Enums in C#

Introduction

In many applications, it is necessary to represent enumerations with string values rather than their default integer values. This can be particularly useful when working with JSON, XML, or other data formats where string representations are more meaningful or required. This article will guide you through defining, using, and converting string-based enums in C#.

Defining String-Based Enums

To define an enumeration in C# where the values are represented as strings, you can use the EnumMember attribute in combination with the DataContract attribute. This method allows you to specify custom string values for each enum member.

using System.Runtime.Serialization;

[DataContract]
public enum Roles
{
    [EnumMember(Value = "Admin")]
    Admin,
    
    [EnumMember(Value = "Developer")]
    Developer,
    
    [EnumMember(Value = "Manager")]
    Manager,
    
    [EnumMember(Value = "TeamLead")]
    TeamLead
}

Converting Enums to Strings

To convert an enum value to its string representation, you can use reflection to read the EnumMember attribute value.

public static string GetEnumValue<T>(T enumValue) where T : Enum
{
    var type = enumValue.GetType();
    var memInfo = type.GetMember(enumValue.ToString());
    var attributes = memInfo[0].GetCustomAttributes(typeof(EnumMemberAttribute), false);
    return ((EnumMemberAttribute)attributes[0]).Value;
}

Converting Strings to Enums

Similarly, you can convert a string value back to its corresponding enum value using reflection.

public static T GetEnumFromString<T>(string value) where T : Enum
{
    var type = typeof(T);
    foreach (var field in type.GetFields())
    {
        var attribute = Attribute.GetCustomAttribute(field, typeof(EnumMemberAttribute)) as EnumMemberAttribute;
        if (attribute != null && attribute.Value == value)
        {
            return (T)field.GetValue(null);
        }
    }
    throw new ArgumentException($"Unknown value: {value}");
}

Complete Example

using System.Runtime.Serialization;

namespace String_Based_Enums_InCSharp
{
    public class Program
    {
        public static void Main(string[] args)
        {
           var  Role = Roles.Admin; 
           Console.WriteLine("Role Before Conversion to string: "+Role.ToString());

           // Conversion Enum to string 
           var RoleString = Role.ToString();
           var EnumToStringValue = GetEnumValue(Role);
           Console.WriteLine("Role After Conversion to string: "+RoleString);

           // Conversion string to Enum
           var RoleEnum = GetEnumFromString<Roles>(EnumToStringValue);
           Console.WriteLine("Role After Conversion to Enum: "+RoleEnum);
          
        }

        // Conversion string to Enum
        public static string GetEnumValue<T>(T enumValue) where T : Enum
        {
            var type = enumValue.GetType();
            var memInfo = type.GetMember(enumValue.ToString());
            var attributes = memInfo[0].GetCustomAttributes(typeof(EnumMemberAttribute), false);
            return ((EnumMemberAttribute)attributes[0]).Value;
        }

        // Conversion Enum to string
        public static T GetEnumFromString<T>(string value) where T : Enum
        {
            var type = typeof(T);
            foreach (var field in type.GetFields())
            {
                var attribute = Attribute.GetCustomAttribute(field, typeof(EnumMemberAttribute)) as EnumMemberAttribute;
                if (attribute != null && attribute.Value == value)
                {
                    return (T)field.GetValue(null);
                }
            }
            throw new ArgumentException($"Unknown value: {value}");
        }
    }
}

Benefits of Using String-Based Enums

  1. Readability: String values are often more meaningful and readable than integer values.
  2. Interoperability: String-based enums can be easily serialized and deserialized in JSON or XML formats.
  3. Ease of Use: String representations are more intuitive when working with data bindings or user interfaces.

GitHub Project URL: https://github.com/SardarMudassarAliKhan/String-Based-Enums-InCSharp

Output

Output

Conclusion

String-based enums provide a powerful way to handle enumerations in C#. By using the EnumMember attribute along with custom methods for conversion, you can easily switch between enum values and their string representations. This approach enhances code readability and interoperability, making it a valuable technique for many C# applications.


Similar Articles