Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

C# get enum value by DescriptionAttribute

public static class EnumEx
{
    public static T GetValueFromDescription<T>(string description) where T : Enum
    {
        foreach(var field in typeof(T).GetFields())
        {
            if (Attribute.GetCustomAttribute(field,
            typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
            {
                if (attribute.Description == description)
                    return (T)field.GetValue(null);
            }
            else
            {
                if (field.Name == description)
                    return (T)field.GetValue(null);
            }
        }

        throw new ArgumentException("Not found.", nameof(description));
        // Or return default(T);
    }
}
var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");
Comment

PREVIOUS NEXT
Code Example
Csharp :: c# request run as administrator 
Csharp :: c# transparent label 
Csharp :: cinemachine namespace not working 
Csharp :: coroutine not eaffected by time.timescale unity 
Csharp :: how to set a objects position to the mouse unity 
Csharp :: blazor button onclick parameter 
Csharp :: How to add a label programatically in c# 
Csharp :: c# 2-dimensional array sort 
Csharp :: how to draw gizmos unity 
Csharp :: .net core add header to soap request 
Csharp :: js invoke async function blazor 
Csharp :: text split 
Csharp :: dictionary to string c# 
Csharp :: c# check if array is empty 
Csharp :: c# choose first n elements from list 
Csharp :: check distance to gameobject 
Csharp :: blazor oninitializedasync 
Csharp :: generate random string c# 
Csharp :: insert new item listview c# 
Csharp :: Comapre Binary Trees 
Csharp :: how to use file watcher in c# 
Csharp :: create char array c# 
Csharp :: how to pass class type to method c# 
Csharp :: c# shuffle list 
Csharp :: unity ignore collision between two objects 
Csharp :: wpf set color in code 
Csharp :: c# create folder 
Csharp :: linux command line switch statement 
Csharp :: find-text-in-string-with-c-sharp 
Csharp :: c# make request to rest api 
ADD CONTENT
Topic
Content
Source link
Name
3+4 =