Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

Enum to string - is there a convenient way in the MF?

enum

  • Please log in to reply
3 replies to this topic

#1 dustmouse

dustmouse

    Advanced Member

  • Members
  • PipPipPip
  • 31 posts
  • LocationEdgewater, CO

Posted 08 March 2014 - 07:27 PM

Is there a convenient way to convert an enum value to a string?  I'm accustomed to using .ToString() in the regular framework but it looks like it's returning the numeric counterpart in micro.  


Check out my Netduino projects on GitHub.


#2 knut.tveitane

knut.tveitane

    Member

  • Members
  • PipPip
  • 18 posts

Posted 08 March 2014 - 08:16 PM

Seems like converting between string and enum - both ways - is unsupported in micro framework. I ended up using a hashtable for converting string to enum, this could be used the other way as well. Verbose, but it works.



#3 Elizabeth_Keen

Elizabeth_Keen

    New Member

  • Members
  • Pip
  • 1 posts

Posted 03 July 2014 - 04:56 PM

Yes, you can use .ToString() to get a string value for an enum, however you can't use .ToString() in a switch statement. Switch statements need constant expressions, and .ToString() does not evaluate until runtime, so the compiler will throw an error.
To get the behavior you want, with a little change in the approach, you can use enum.Parse() to convert the action string to an enum value, and switch on that enum value instead. As of .NET 4 you can use Enum.TryParse() and do the error checking and handling upfront, rather than in the switch body.

Edited by Chris Walker, 04 July 2014 - 06:34 PM.
Removed tagline advertisement


#4 knut.tveitane

knut.tveitane

    Member

  • Members
  • PipPip
  • 18 posts

Posted 08 July 2014 - 06:57 AM

Elizabeth, did you really try this? I think you didn't, because although this is what the documentation says and how it works in .Net, in my experience it does NOT work like this in .NetMF. That is also the reason this question came up in the first place.

 

.ToString() gives you the string representation of the integer value of the enum element: I.e. if you have an enum

    public enum MyEnum { First, Second, Third }, then MyEnum.First.ToString() will return "0". In .Net, it would be "First".

 

Same the other way around, .NetMF does NOT parse strings to enum values like .Net - the Enum.Parse() method is not supported.
 






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.