I've got
public enum Als
{
[StringValue("Beantwoord")] Beantwoord = 0,
[StringValue("Niet beantwoord")] NietBeantwoord = 1,
[StringValue("Geselecteerd")] Geselecteerd = 2,
[StringValue("Niet geselecteerd")] NietGeselecteerd = 3,
}
with
public class StringValueAttribute : Attribute
{
private string _value;
public StringValueAttribute(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
}
And I would like to put the value from the item I selected of a combobox into a int:
int i = (int)(Als)Enum.Parse(typeof(Als), (string)cboAls.SelectedValue); //<- WRONG
Is this possible, and if so, how? (the StringValue
matches the value selected from the combobox).
To parse a string value based on attribute values applied to enum members I'd recommend you use my Enums.NET open source library.
For a custom attribute like the
StringValueAttribute
you would do this.Register and store a custom
EnumFormat
forStringValueAttribute.Value
.Then use the custom
EnumFormat
.If you were instead using a built-in attribute such as the
DescriptionAttribute
you could just do this.In case you're interested, this is how you'd get the string value associated with an enum value.
I'm using the DescriptionAttribute from Microsoft and the following extension method:
Not sure if I am missing something here, can you not do this,
Coming here from duplicate links of this highly upvoted question and answer, here is a method that works with C# 7.3's new
Enum
type constraint. Note that you also need to specify that it is also astruct
so that you can make it the nullableTEnum?
or else you will get an error.Here are a couple extension methods that I use for this exact purpose, I've rewritten these to use your
StringValueAttribute
, but like Oliver I use the DescriptionAttribute in my code.This can be made slightly more simple in .NET 4.5:
And to call it, just do the following:
Conversely, here's a function to get the string from an enum value:
And to call it:
Here's a helper method that should point you in the right direction.
And to call it, just do the following:
This probably isn't the best solution though as it's tied to
Als
and you'll probably want to make this code re-usable. What you'll probably want to strip out the code from my solution to return you the attribute value and then just useEnum.Parse
as you are doing in your question.