Click here to Skip to main content
15,795,581 members
Articles / Programming Languages / C#

Problem in Parsing String Value to Enum Type

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
2 May 2012CPOL 14K   1   2
Problem in parsing string value in enum type

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 always giving 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 should fail, but I always get true value return enum.TryParse method which is surprising. I don’t know why it does not behave as per expectation.

FieldAccessType type;
bool res=Enum.TryParse("20",out type );
Assert.IsFalse(res); //test is failing bcoz res is true

I found the MSDN documentation for Enum.TryParse/Enum.Parse and found the 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 later:

FieldAccessType fieldAccessType;
                    int intEnumValue;
                    if (Int32.TryParse(Value, out intEnumValue))
                        if (Enum.IsDefined(typeof (FieldAccessType), intEnumValue))
                            return (FieldAccessType) intEnumValue;

Enum.IsDefined to verify that the value you parsed actually exists in this particular enum.

I hope this trick will help you.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Architect Saxo Bank A/S
Denmark Denmark
• Solution Architect /Principle Lead Developer with 12 years of IT experience with more emphasize on Capital Domain and Investment banking domain.
• Strong experience in Continuous Integration, Delivery and DevOps solutions.
• Strong experience in drafting solutions, stakeholder communications and risk management.
• Proved strong coding and designing skills with agile approaches (TDD, XP framework, Pair Programming).
• Delivered many projects with involvement from inception to delivery phase.
• Strong experience in high performance, multithreaded, low latency applications.
• Ability to communicate with the business and technical stake holders effectively.
• Have extensive experience in Capital Market Domain: Front Office & BackOffice (Algorithm Trading tools, messaging framework, Enterprise bus, integration of FIX APIs and many trading APIs).
• Functional knowledge of Portfolio/Wealth Management, Equities, Fixed Income, Derivatives, Forex.
• Practical knowledge of building and practicing agile delivery methodologies (SCRUM, TDD, Kanban).

Technical Skills

• Architectural: Solution Design, Architectural Presentations (Logical, Component, Physical, UML diagrams)
• Languages: C#, C++
• Server Technologies: WCF, Web API,
• Middle Ware: ActiveMQ, RabbitMQ, Enterprise Service Bus
• UI Technologies: Winforms and WPF
• Web Technologies: Asp.Net Mvc, KnockOutJS, JQuery, Advance Java Scripts Concepts
• Databases: Sql Server 2008 +, MySQL
• Tools/Frameworks: TFS, SVN, NUnit, Rhino Mocks, Unity, NAnt, QuickFix/n, Nhibernate, LINQ, JIRA,

Functional Skills

• Wealth Management System, Trade Life Cycle, Trading Components and their integrations
• Working knowledge of Stocks, Bonds, CFDs,Forex, Futures and Options
• Pricing Systems, Market Data Management,
• BackOffice Processes : Settlement Processes, Netting, Tax, Commissions, Corporate Actions Handling,
• Reporting Solutions : OLTP and OLAP Data model designing
• FIX Engine implementation and integration

Comments and Discussions

Questiondoes not always work that way Pin
Mark Kruger29-May-12 4:07
Mark Kruger29-May-12 4:07 
if the enum is defined as flaggable iow [System.Flags] then if the combination of enum value
will form the supplied number it will restore it correctly.

private enum tryme
try1 = 1,
try2 = 2

public void Tester()
tryme test = tryme.try1;
Enum.TryParse("3", out test);
bool defined = Enum.IsDefined(typeof(tryme), test);

while in above example the value is correct, it's a combination of 1 and 2 isdefined will fire
the value does not exists.

Though if u convert the enum value to a string, in case it's a valid value it will convert to enumeration values, if it doesn't it will convert to the string conversion of the number u've placed in it

iow "3" will result in "try1, try2" while "4" will result in "4"
I hope this gave some extra insight.
AnswerRe: does not always work that way Pin
Neeraj Kaushik198029-May-12 5:06
Neeraj Kaushik198029-May-12 5:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.