How to convert string to enum? [CS/C#]

Shaitan00

Junior Contributor
Joined
Aug 11, 2003
Messages
358
Location
Hell
Okay, little background information - I am reading information from a text file (level.txt) and it contains details such as:
[0,7] = ExtWall;
This indicates that at location 0,7 on my map I should place an "Exterior Wall", therefore I need to create an object (of class Wall) to put there.
Now the fun part is the constructor of class "Wall" looks like "public Wall(ObjectType _objectType)" (and this cannot be changed)...

So finally "ObjectType" is an ENUM that I made to maintain a list of the different allowed object types, it looks like:
Code:
public enum ObjectType
{
	Wall,
	ExtWall,
	Brick,
	Floor,
}

So, now to the problem - the information I read from the text file is a STRING value "ExtWall" (sObject) and I want to use that to create a Wall object of ObjectType.ExtWall so I need a way to CAST (or something) my string as an ObjectType...

Currently if I do something like the following (which is where I am stuck) it complains about being unable to convert it, I have tried a few different approaches (like trying to make the string "ObjectType."+sObject but that didn’t work as expected...) but nothing works...

Code:
[0, 0] = new Wall(sObject);	// Where sObject is the string taken from the text file
Error: The best overloaded method match for 'Wall(ObjectType)' has some invalid arguments
Error: Argument '1': cannot convert from 'string' to 'ObjectType'

Now I know I could use a SWITCH statement or something simplistic like that - but I don't want to have to maintain this code, I want to be able to add a value to my ObjectType enum and trust that the value taken from the file matches, that way I don't have to keep adding to a switch statement every time I add a different type of wall (just add it to the enum and ensure my text file is perfect).

So how can I cast my string as an ObjectType enum? Or does anyone know of a nicer more conventional (or non-) approach?
Any ideas, hints, and help would be greatly appreciated, thanks
 
Personally I've found the easiest way to serialise an Enum is by converting it to it's integer value. This is helpfull becaue C# allows us to cast enums too and fron their integer value.
C#:
TestEnum myTestEnum = TestEnum.Two;
int enumAsInt = (int)myTestEnum;
TestEnum backAsEnum = (TestEnum)enumAsInt;

public enum TestEnum
{
	One,
	Two,
	Three
}
EDIT:-There is a built in function for doing this, I often work with the .Net CF which doesn't support it though so I nearly forgot about it. Check out the System.Enum.Parse() method.
 
Back
Top