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.

2

3 Answers 3

5

You can parse it using Enum.TryParse:

InventoryType inventoryType;
if(Enum.TryParse(reader.GetString("type"), out inventoryType))
{
    //use inventoryType
}
else
{
    //not valid
}
Sign up to request clarification or add additional context in comments.

1 Comment

You should be able to leave out <InventoryType>, since it can be inferred from the inventoryType variable.
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.

3 Comments

@RohitVats you also missed the ) after InventoryType.
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 - Indeed. That's how it works. Hope that's obvious. Although mentioned in the answer.
0

Try this:-

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

1 Comment

can't I use at the end of the enum delcartion : string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.