Today I faced one issue with Enum.TryParse or Enum.Parse method. I was trying to parse string value to Enum but Enum.TryParse/Enum.Parse method was giving always true value for string which is not member of enum.
public enum FieldAccessType
ReadOnly = 1,
Add = 2,
Modify = 4,
AddModify = 6
I want to convert string value say “30″ to enum type that is not member of enum and conversion shoule be fails but I am always getting true value return enum.TryParse method which is surprising. I don’t know why it is not behaving as per expectation.
bool res=Enum.TryParse("20",out type );
I found msdn documentation for Enum.TryParse/Enum.Parse and found following lines:
“If value is the string representation of an integer that does not represent an underlying value of the TEnum enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of TEnum.”
Below is code which I corrected after:
if (Int32.TryParse(Value, out intEnumValue))
if (Enum.IsDefined(typeof (FieldAccessType), intEnumValue))
return (FieldAccessType) intEnumValue;
Enum.IsDefined to veryify that the value you parsed actually exists in this particular enum.
I hope this trick will help you.
• Technical Architect with 9 years of Application development experience
• Good knowledge and expertise on multiple areas of technologies and their business applications
• Strong experience in high performance and business critical applications.
• Experience in creating framework, Code generators, and UML diagrams.
• Developed messaging framework for Algo Trading, technical analysis tool, market feed client Api, Payment Solutions for SWIFT, Internationalization for Core Banking Solution product etc.
• Practical knowledge of building and practicing agile delivery methodologies (SCRUM & TDD).
• Proven ability in producing technical documentation and presentation to clients.
• Active participation in trainings, article writing & taking initiatives.
• Passion to get knowledge from various resources acquires best practices.
• Good understanding of financial domain especially in investment banking and banking domain.
Technical Architectures, Multi-threading Architecture, Algo Trading systems, Messaging Framework, FIX Implementation, Technical Analysis & Charting, ActiveMQ, MSMQ, C#, WinForms, ASP.NET MVC, Jquery, WCF, Sql Server 2008, Oracle, TFS, TDD, QuickFix, Open Source Tools & Framework.