-1

I am using an enumerator in my script, and at the moment it has a very simple enum:

public enum Item
{
    Wood,
    Stone
}

With this enum, I am able to do stuff that you are normally able to do with an enum, such as int foo = (int)Item.Wood, which sets foo equal to 0. However, there is a point in my script where I want to set an int variable using the enum, but I don't know what the item will be. For example:

public enum Item
{
    Wood,
    Stone
}

string ItemString = "Stone";

int foo = (int)Item.ItemString

However, this doesn't work because now the script is looking for an enumeration called ItemString, instead of looking at the value of ItemString and finding the enumeration of that. Anybody know what I can do in this situation? If necessary I can provide more details and clarification.

Edit: This post partially answers my question, but the accepted answer better shows how to implement the answer from the linked post.

Aaron Miller
  • 167
  • 4
  • 13
  • It isn't fully clear, why do you need to cast `string` to `int` here, if you asking about `enum` actually – Pavel Anikhouski Jan 04 '20 at 16:27
  • Just make a method that compares a string with the ToString of each Item inside the enumerate.. – Greggz Jan 04 '20 at 16:27
  • 1
    Does this answer your question? https://stackoverflow.com/questions/16100/convert-a-string-to-an-enum-in-c-sharp – timur Jan 04 '20 at 16:27
  • When you use the dot notation, you access the elements/methods of the variable. Item only has wood and stone, you cant call item. but you can parse variable value to get enum, as described in the link above – Jawad Jan 04 '20 at 16:44

1 Answers1

2

You can do TryParse

        string ItemString = "Stone";
        Item enumItem;
        Item.TryParse(ItemString, out enumItem);
        int foo = (int)enumItem;
        Console.WriteLine(foo);

public enum Item
{
    Wood,
    Stone
}

you can check the sample code here

Ranjit Singh
  • 3,715
  • 1
  • 21
  • 35