The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.

C# - Am I missing a trick here?

I have a bunch of enums like these

enum TYPE {
 TYPE_START,
 SIMPLE,
 COMPLEX,
 CONVOLUTED,
 TYPE_END
}

I have certain situations where I need to get the type using a string.

For e.g.

s = "SIMPLE";
TYPE t = SomeClass.GetTypeFromString(s);

TYPE GetTypeFromString(string s) {
 for(int y = (int)TYPE.TYPE_START; y < (int)TYPE.TYPE_END; y++)
    if((TYPE)y.toString() == s)
      return((TYPE)y)
}

This works - but when I have many enums and need similar functions for all, I think it's sort of ugly. Am I missing any trick so I can get the TYPE variable using the string equivalent without these comparison loops? Duh?
Anil
Thursday, October 13, 2005
 
 
The Enum class has some static methods to help you with this kind of this (Parse in particular):

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemEnumMembersTopic.asp?frame=true
Jeff Mastry Send private email
Thursday, October 13, 2005
 
 
What Jeff said.  You could do something like this...

    String s = "SIMPLE";
    TYPE t = (TYPE) Enum.Parse(typeof(TYPE), s);
N
Thursday, October 13, 2005
 
 
Perfect! Exactly what I wanted..though I needed a small extension to it to take care of boundaries..

  public static TYPE TypeFromString(string s) {
           
            if(s == null || !Enum.IsDefined(typeof(TYPE),s))
                return(TYPE.UNKNOWN);

            else return((TYPE)Enum.Parse(typeof(TYPE),s));
      }

Thank you Jeff and N!
Anil
Thursday, October 13, 2005
 
 
Just note that Enum.Parse uses reflection to do it's trick, so is dog slow (relatively speaking).  So don't use it in any performance critical areas.
Neyah
Friday, October 14, 2005
 
 
How about hashing the string, and then looking up the hash in a list... so when your program fires up, you create the hash "master" list with elements of each type.
Michael Johnson Send private email
Tuesday, October 18, 2005
 
 
I have some stuff like this in C++. We actually get the enum defs in XML (that's outside our control) and generate the enum code with a script, alomg with toString and fromString methods, from that. The implementation for toString is just a static array of strings indexed by the enum value, with bounds checking. It works fine for this app, though it obviously wouldn't suit all cases.
revert my buffer
Tuesday, October 25, 2005
 
 

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
 
Powered by FogBugz