Posted By

paragjagdale on 04/08/08


Tagged

String enum member


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


Convert a string to its respective Enum member


 / Published in: C#
 

This snippet accepts a string which is assumed to be the string version of one of the members and returns an enum object with the respective member selected.*

*Thanks to user: mcbutterbuns for improving upon my version of this snippet

  1. public enum PayTypeList
  2. {
  3.  
  4. Unknown,
  5.  
  6. Hourly,
  7.  
  8. Salary,
  9. }
  10.  
  11. PayTypeList payType = (PayTypeList)Enum.Parse(typeof(PayTypeList), "Hourly");
  12.  
  13. // Throws an ArgumentException if the string is found not to be one of the members of the enum (in this case, if you pass in a string "Weekly" instead of "Hourly", it will throw an ArgumentException)

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: mcbutterbuns on April 8, 2008

There is a simpler way than this snip:

(PayTypeList)Enum.Parse(typeof(PayTypeList), "Hourly");

Will through an ArgumentException (I believe) if the string is cannot be parsed into the type of enum requested.

Posted By: paragjagdale on April 8, 2008

cool! it works and throws the ArgumentException as you said. Thanks for the tip!

You need to login to post a comment.