0

I have a enum that has multiple values (I have kept only one below inside the enum). I am being passed this string "Online System" from the UI. Is there a way I can make use of this enum to do the condition rather than hardcoding like below.

if( types.type == "Online System" )

  public enum Type
        {
            [EnumMember]
            Windows
            ,[EnumMember]
            OnlineSystem
        }

Update

Also, when I number the enum values to Windows = 1, OnlineSystem = 2, will there be any problem? This code is already there, but I am gona number like this, will this create any side effect for codes that might use this already without numbering?

Jasmine
  • 5,186
  • 16
  • 62
  • 114

1 Answers1

1

First you can decorate your Enum with Description Attribute

  public enum Type
  {
    [Description("Windows")]
    Windows,
    [Description("Online System")]
    OnlineSystem
  }

Then You could write a method to use reflection to fetch the description of given Enum Value (Value to compare to).

public static string GetEnumDescription(Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes =
        (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute),
        false);

    if (attributes != null &&
        attributes.Length > 0)
        return attributes[0].Description;
    else
        return value.ToString();
}

This would enable you to check

var type = "Online System";
if(  type == GetEnumDescription(Type.OnlineSystem))
{
}
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
  • Anu, thank you so much, just a quick question, the parameter to GetEnumDescription shouldn't start with "this" keyword? – Jasmine Jan 10 '19 at 10:50
  • 1
    @Learner 'this' keyword is associated with Extension method. The method in the example not an extension method, which is why it is missing. You can read more on extension methods here https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods – Anu Viswan Jan 10 '19 at 11:55