Skip to main content
GameDev.net gamedev.net
🔒 Locked

Creating enums

Started by EternalNewbie Sep 10, 2007 at 1:11 PM 1 replies 2.1k views
Original Post
EternalNewbie
EternalNewbie
ChooseEnum displays all the elements in a enum and asks the user to choose one (by an associated value which is displayed) Is there any way make the following look nicer? (remove the cast and typeof)
static int ChooseEnum(Type enumerable)

HairColour playerHairColour = (HairColour) ChooseEnum(typeof(HairColour));

Also is there any way to create enums on the fly? e.g. load the haircolours from a file. If not I'll need to use some sort of associative container (like maps in c++), should I use Dictionaries? or can people suggest a better alternative? Using dictionaries would make the above code look neater , But I would lose type safety. Hope that makes sense.
jpetrie
jpetrie
Quote:

Is there any way make the following look nicer? (remove the cast and typeof)

Generics. Unfortunately, generic constraints can't be "enum," but something like
static T ChooseEnum<T>(); // called like ChooseEnum<HairColor>()static void ChooseEnum<T>(out T result); // called like ChooseEnum(out myHairColor);

might work for you.

Quote:

Also is there any way to create enums on the fly? e.g. load the haircolours from a file.

You can achieve the desired result, yes.

Quote:

Using dictionaries would make the above code look neater , But I would lose type safety.

Not neccessarily. What is the implementation you are thinking of?
EternalNewbie
EternalNewbie
Quote:
Original post by jpetrie

Generics. Unfortunately, generic constraints can't be "enum," but something like


I was afraid that was gonna be the case, I didn't want to get into 'advance' stuff like generics till I had a better grasp of the basics. Also enum would've worked so nicely for what I was doing.


Quote:

Using dictionaries would make the above code look neater , But I would lose type safety.

Not neccessarily. What is the implementation you are thinking of?


The idea is to load a number of strings from a file. The user would then choose from one of these strings and a value for this would be stored.
The reason for wanting enums the value would be stored as integers(fast) and when they're displayed I can use strings(slow). They would also be type safe e.g. i couldnt assign a haircolour to an eyecolour.

[Edited by - EternalNewbie on September 11, 2007 11:54:58 AM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.