Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

get enum value from display name c#

// You have to create a helper to get what you need
public class Program
    {
        private static void Main(string[] args)
        {
            var name = "first_name";
            CustomFields customFields = EnumHelper<CustomFields>.GetValueFromName(name);
        }
    }

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

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

    public static class EnumHelper<T>
    {
        public static T GetValueFromName(string name)
        {
            var type = typeof (T);
            if (!type.IsEnum) throw new InvalidOperationException();

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

            throw new ArgumentOutOfRangeException("name");
        }
    }
Comment

PREVIOUS NEXT
Code Example
Csharp :: system.io.directorynotfoundexception c# 
Csharp :: difference two list c# 
Csharp :: unity icons 
Csharp :: c# add char to string 
Csharp :: unity editor dropdown 
Csharp :: c# jobject to string 
Csharp :: rotate player unity 2d left and right 
Csharp :: vscode not showing errors c# 
Csharp :: c-sharp - get current page url/path/host 
Csharp :: capitalize first letter c# 
Csharp :: asp.net c# set session timeout 
Csharp :: decimal c# 2 digits 
Csharp :: add all elements in a list c# 
Csharp :: process.start web 
Csharp :: joystock movement 
Csharp :: callback function on animation end unity 
Csharp :: c# sort array of objects 
Csharp :: c# add to array 
Csharp :: merge xml files into one c# 
Csharp :: item switch unity 
Csharp :: c# get application root path directory 
Csharp :: null coalescing operator c# 
Csharp :: multithreading in c# 
Csharp :: switch expression c# 
Csharp :: c# dictionary keys to list 
Csharp :: array of strings by splitting lines c# 
Csharp :: unity text custom color 
Csharp :: orElseThrow 
Csharp :: c# array of class 
Csharp :: how to append something to a string in c# 
ADD CONTENT
Topic
Content
Source link
Name
7+2 =