0

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

1 Answers1

1

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
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
  • 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"`. – Markus Safar Dec 24 '21 at 20:38
  • Thank you , but i need in the end take int. Exp: i have string a = "Member" and need to take his Key (number 2) – Levan Amashukeli Dec 24 '21 at 21:43
  • I updated my answer for your request @LevanAmashukeli – Ran Turner Dec 25 '21 at 08:37