Convert a string to its respective Enum member


/ Published in: C#
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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

You need to login to post a comment.