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;
var name = "first_name"; CustomFields. getEnumValue(name);
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.
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.
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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With