1

I have 1 string variable, have Enums and need to compare incoming string variable to Enum Values, and if it finds compares, I need to take compared Enum Key and assign to some int variable. How can I do this? I need Only Enum Key.

For Example I have :

public class Enums
{
  Admin = 0,
  Seller = 1,
  Member = 2,
  Unknown = 3
}

And Some base class:

string tech = “Member”;

foreach(string value in Enum.GetNames(typesof(Enums)))
{
  If(tech == value)
{
  int enumValueKey =  And here I need '2'. 
}}}

In Base class, I have only string type variable for example (string Admin, string Seller, string Member, string Unknown). If It finds 1 comparison , then should write Key in int value , the same value as was found in Enums.

Thanks a lot

2
  • Have a look at Enum.Parse, Enum.TryParse Commented Dec 24, 2021 at 20:30
  • 1
    int key = (int) (Enum.Parse<Enums>(tech)); - just Parse and then cast to int if you want Commented Dec 24, 2021 at 21:45

1 Answer 1

2

You can achieve this via Enum.Parse and typeof

public enum Enums
{
  Admin = 0,
  Seller = 1,
  Member = 2,
  Unknown = 3
}

int myEnum = (int)(Enums)Enum.Parse(typeof(Enums), "Seller");
Console.WriteLine(myEnum); // 1
Sign up to request clarification or add additional context in comments.

3 Comments

It is important to mention that nameof is evaluated at compile time so something like Enums enumValue = Enums.Seller; string enumName = nameof(enumValue); would result in "enumValue" not "Seller".
Thank you , but i need in the end take int. Exp: i have string a = "Member" and need to take his Key (number 2)
I updated my answer for your request @LevanAmashukeli

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.