Title: Get enum instance given the value of it's custom attribute
Tags: c#;enums;attributes
Question: recently I've tried googling and searching for answer how could I get the enum instance where enum values have custom attributes. I get on input a value of its custom attribute and I want to know which enum value corresponds.
Example:
public enum whatever
[MyCustomAttribute(&quot;foo1&quot;, &quot;foo2&quot;)]
SOMETHING,
[MyCustomAttribute(&quot;foo2&quot;, &quot;foo3&quot;)]
SOMETHING_2
Attribute:
public MyCustomAttribute() : Attribute
string somevalue;
string anothervalue;
public MyCustomAttribute(string f, string f2)
somevalue = f;
anothervalue = f2;
I get &quot;foo1&quot; as an input and I want to return whatever.SOMETHING.
Comment: Nice, I couldn't find this one, I guess I didn't enter the right keywords. It's very similar, it should do.


Here is another answer: I was able to come up with a simple solution which works for me perfectly and I'm very surprised I was not able to find it anywhere.
public whatever GetWhatever(string value)
=&gt; typeof(whatever).GetEnumValues()
.Cast<whatever&gt;().First(val =&gt; val .GetCustomAttributeee<MyCustomAttribute&gt;().somevalue == value);
I'll be glad if u gimme some feedback about my solution and its problems if any.
Comment for this answer: Oh, well, didn't think of that, thanks!
Comment for this answer: You should check the attribute is not null - in the event that the member doesn't have the attribute on it.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2020:00:10/08/20', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c#><enums><attributes>', 'Title': "Get enum instance given the value of it's custom attribute", 'ViewCount': 47, 'id': 64260511, 'user_AboutMe': '', 'user_AccountId': 15511674.0, 'user_DisplayName': 'Richard', 'user_Reputation': 17.0, 'user_Views': 17.0, 'user_id': 11190289.0}}