2

I have the following enum in my class:

  public enum InventoryType
    {
        EQUIP = 1,
        USE = 2,
        SETUP = 3,
        ETC = 4,
        CASH = 5,
        EVAN = 6,
        TOTEMS = 7,
        ANDROID = 8,
        BITS = 9,
        MECHANIC = 10,
        HAKU = 11,
        EQUIPPED = -1
    }

Now, I have a field:

    public InventoryType InventoryType { get; private set; }

I load the data from MySql. MySql's column of type has the string that is the InventoryType. How can I convert the string I get to the enum InventoryType?

I tried:

this.InventoryType = reader.GetString("type");

But of course, that doesn't work, because it's getting a string and required an InventoryType. What can I do to convert it? Thanks.

user2714359
  • 117
  • 1
  • 3
  • 9

3 Answers3

5

You can parse it using Enum.TryParse:

InventoryType inventoryType;
if(Enum.TryParse(reader.GetString("type"), out inventoryType))
{
    //use inventoryType
}
else
{
    //not valid
}
Lee
  • 142,018
  • 20
  • 234
  • 287
  • 2
    You should be able to leave out ``, since it can be inferred from the `inventoryType` variable. – nmclean Aug 25 '13 at 15:40
3

You can use Enum.Parse to parse your string back to Enum value -

this.InventoryType = (InventoryType)Enum.Parse(typeof(InventoryType),
                                                 reader.GetString("type"));

Also, use Parse if you are sure the value will be valid; otherwise use TryParse.

Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • 1
    @RohitVats you also missed the `)` after `InventoryType`. – King King Aug 25 '13 at 15:39
  • It may be obvious from the samples, but just in case: Parse will throw an exception if there isn't a match. TryParse takes an out parameter and returns a bool indicating success or failure. – Rob Aug 25 '13 at 15:47
  • @Rob - Indeed. That's how it works. Hope that's obvious. Although mentioned in the answer. – Rohit Vats Aug 25 '13 at 15:52
0

Try this:-

this.InventoryType= (InventoryType) Enum.Parse( typeof(InventoryType), reader.GetString("type") );
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331