3

I'm writing an enum value with an XmlWriter, and it look something like this in the xml:

<Tile>Plain</Tile>

writer.WriteValue(tile.ID.ToString()); // ID's type is the enum

Plain being one of the enum values. Now when I try to read this, though it won't work.

(TileID)reader.ReadElementContentAs(typeof(TileID), null);

I do this when my reader.Name == "Tile", which should work, though it apparently can't convert the string to my enum. Is there any way to either fix the writing, so I don't have to do the .ToString() (since if I don't I get an error: "TileID cannot be cast to string".) or fix the reading?

Thanks.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
The Oddler
  • 6,314
  • 7
  • 51
  • 94

2 Answers2

4

I would suggest using Enum.TryParse

var enumStr = reader.ReadString();
TitleID id;
if (!Enum.TryParse<TitleID>(enumStr, out id)
{
    // whatever you need to do when the XML isn't in the expected format
    //  such as throwing an exception or setting the ID to a default value
}
JG in SD
  • 5,427
  • 3
  • 34
  • 46
  • Thanks! This is such a simple thing, learning new stuff every day :D – The Oddler Nov 26 '12 at 21:52
  • @TheOddler FYI - if you are going to set the ID enumeration to a default value if the parsing fails, do not initialize the variable to it, set it after the `TryParse` call tells you the parsing fails, as the `TryParse` function will set the value to some default – JG in SD Nov 26 '12 at 22:00
3

You will probably have to use Enum.Parse. I threw this together for a project at work recently:

public static T ParseTo<T>(string value) {
    return (T)Enum.Parse(typeof(T), value);
}

It just makes the casting a bit cleaner. I don't need any error checking because of the very strict XML generation tests we have.. you may want to add some.

Usage for you:

var idString = reader.ReadString();
TileID tileId = StaticClassYouPutItIn.ParseTo<TileID>(idString);
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138