There are better ways to go about creating what you are looking for, if you're interested in binding enums to controls or fields, and having the system display the name of the enum, rather than the underlying value. The important thing that makes this complicated is that under the hood, the system isn't handling an enum
as a string
that gets picked from the developer-defined list; rather, it's handled by default as an Int32
.
I found some other answers on Stack Overflow that might help you to see some better possible solutions. This answer explains how you can create your own type-safe class that handles like an enum, but returns the string value that you're looking for. This answer is possibly a duplicate of the same question, but adds more perspectives to the topic. I used code samples from the first question to help you see that what you're looking for can be found, but might not be simple.
public class Survey
{
[Display(Name = "Have you ever been told by a medical professional not to take hormones?")]
public AnswerYND? ToldNotToTakeHormones { get; set; }
}
public enum AnswerYND
{
Yes = 1,
No = 2,
[Display(Name = "Don't Know")]
DontKnow = 3
}
class Program
{
static void Main(string[] args)
{
var survey = new Survey();
Console.WriteLine(survey);
var options = Enum.GetValues(typeof(AnswerYND));
for (int i = 0; i < options.Length; i++)
{
Console.WriteLine($"Option {i + 1}: {options.GetValue(i)}");
}
var choice = Console.ReadLine();
if (int.TryParse(choice, out int intChoice) && Enum.IsDefined(typeof(AnswerYND), intChoice))
{
AnswerYND enumChoice = (AnswerYND)intChoice;
var name = (enumChoice
.GetType()
.GetField(enumChoice.ToString())
.GetCustomAttributes(typeof(DisplayAttribute), false)
as DisplayAttribute[])
.FirstOrDefault()?
.Name;
Console.WriteLine($"You selected: {name}");
}
}