We Recommend

Accelerated C# 2008 Accelerated C# 2008
This book is both a rapid tutorial and a permanent reference. You’ll quickly master C# syntax while learning how the CLR simplifies many programming tasks. You’ll also learn best practices that ensure your code will be efficient, reusable, and robust. Why spend months or years discovering the best ways to design and code C# when this book will show you how to do things the right way, right from the start?


Posted By

paragjagdale on 04/08/08


Tagged

String enum member


Versions (?)


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.