Question

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.

Was it helpful?

Solution

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
}

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top