Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Reading enums from text file

Tags:

c#

stream

enums

xna

I'm making a 2D game with C# & XNA. I'm working on saving and loading currently, all of the data is stored in text files.

Each sprite has a state:

public enum SpriteState
{
    Alive,
    Dead,
    Chasing,
    Sleeping,
    Waiting 
}

When saving i'm simply executing this line of code:

StreamWriter.WriteLine(gameState); 

Now when i'm loading a game i'm having to read that line of the text file store it in a string variable and perform near enough the following:

string inType = StreamReader.ReadLine();

if(inType == "Alive")
   //Set the sprites state to alive
else if(inType == "Dead")
   //Set the sprites state to alive

And so on... So my question is: Is there a better way of reading a enum type from a text file and assigning it?

Many thanks

like image 364
Lee Brindley Avatar asked Dec 18 '25 19:12

Lee Brindley


1 Answers

You're looking for

(SpriteState) Enum.Parse(typeof(SpriteState), inType)

This will parse a string into an enum value.

You may also want to have a Dictionary<SpriteState, Action<...>> mapping states to delegates (lambda expressions) that take the appropriate action.

like image 173
SLaks Avatar answered Dec 20 '25 08:12

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!