Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum value from display name

Tags:

I am new with C# and I have some troubles with enum.

I have Enum defined like this:

public enum CustomFields
{
    [Display(Name = "first_name")]
    FirstName = 1,

    [Display(Name = "last_name")]
    LastName = 2,
}

What I need is code which will check does display name exist and if so return enum value.

So if I have display name:

var name = "first_name";

I need something like:

var name = "first_name";
CustomFields.getEnumValue(name);

This should return:

CustomFields.FirstName;
like image 993
carpics Avatar asked Oct 19 '15 23:10

carpics


People also ask

How to get enum value using display name c#?

var name = "first_name"; CustomFields. getEnumValue(name);

How do I get the display name attribute of an enum?

And to get the display name anywhere in a C# project, you can add an enum extension class that returns the display name property. If the property is missing (like it is for the first two enum values above), it falls back to the string equivalent.

How do you find the value of an enum?

Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

How do I display an enum name?

An enumeration is a great way to define a set of constant values in a single data type. If you want to display an enum's element name on your UI directly by calling its ToString() method, it will be displayed as it has been defined.


1 Answers

You could use generics:

    public class Program
    {
        private static void Main(string[] args)
        {
            var name = "first_name";
            CustomFields customFields = name.GetValueFromName<CustomFields>();
        }
    }

    public enum CustomFields
    {
        [Display(Name = "first_name")]
        FirstName = 1,

        [Display(Name = "last_name")]
        LastName = 2,
    }


    public static T GetValueFromName<T>(this string name) where T : Enum
    {
        var type = typeof(T);

        foreach (var field in type.GetFields())
        {
            if (Attribute.GetCustomAttribute(field, typeof(DisplayAttribute)) is DisplayAttribute attribute)
            {
                if (attribute.Name == name)
                {
                    return (T)field.GetValue(null);
                }
            }

            if (field.Name == name)
            {
                return (T)field.GetValue(null);
            }
        }

        throw new ArgumentOutOfRangeException(nameof(name));
    }
like image 166
openshac Avatar answered Oct 11 '22 16:10

openshac