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?

6
  • Whats the datatype of types.type? Its the enum or string? Commented Jan 10, 2019 at 5:28
  • @er-mfahhgk: Apparently its a string thats why I have put string value there in quotes Commented Jan 10, 2019 at 5:31
  • Please refer this stackoverflow.com/a/11508909/795683 Commented Jan 10, 2019 at 5:33
  • @Learner, I added my answer below, You need to pass string value like OnlineSystem. Commented Jan 10, 2019 at 5:55
  • @Learner , check this => stackoverflow.com/questions/4367723/… Commented Jan 10, 2019 at 6:42

1 Answer 1

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))
{
}
Sign up to request clarification or add additional context in comments.

2 Comments

Anu, thank you so much, just a quick question, the parameter to GetEnumDescription shouldn't start with "this" keyword?
@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 learn.microsoft.com/en-us/dotnet/csharp/programming-guide/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.