Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare string with enum in C#

Tags:

c#

.net

string strName = "John"; public enum Name { John,Peter }  private void DoSomething(string myname) { case1:      if(myname.Equals(Name.John) //returns false      {       }  case2:      if(myname == Name.John) //compilation error      {       }  case3:      if(myname.Equals(Name.John.ToString()) //returns true (correct comparision)      {       } } 

when I use .Equals it is reference compare and when I use == it means value compare.

Is there a better code instead of converting the enum value to ToString() for comparison? because it destroys the purpose of value type enum and also, ToString() on enum is deprecated??

like image 269
Gururaj Avatar asked Jul 16 '12 16:07

Gururaj


People also ask

Can we compare String and enum?

For comparing String to Enum type you should convert enum to string and then compare them. For that you can use toString() method or name() method. toString()- Returns the name of this enum constant, as contained in the declaration.

Can we compare enum values in C?

So remember enum are used to define a list of named integer constants which we can do using #define also. This is the correct way to compare as it replaces Hello3 by the value 3 (which is nothing but int ) at compile time.

Is enum better than String?

I would consider Enums to be a better approach than Strings. They are type safe and comparing them is faster than comparing Strings. Show activity on this post. If your set of parameters is limited and known at compile time, use enum .


2 Answers

You can use the Enum.TryParse() method to convert a string to the equivalent enumerated value (assuming it exists):

Name myName; if (Enum.TryParse(nameString, out myName)) {     switch (myName) { case John: ... } } 
like image 143
dlev Avatar answered Sep 23 '22 06:09

dlev


You can parse the string value and do enum comparisons.

Enum.TryParse: See http://msdn.microsoft.com/en-us/library/dd783499.aspx

Name result; if (Enum.TryParse(myname, out result)) {     switch (result)     {         case Name.John:             /* do 'John' logic */             break;         default:             /* unexpected/unspecialized enum value, do general logic */             break;     } } else  {     /* invalid enum value, handle */ } 

If you are just comparing a single value:

Name result; if (Enum.TryParse(myname, out result) && result == Name.John) {      /* do 'John' logic */ } else  {     /* do non-'John' logic */ } 
like image 38
Paul Fleming Avatar answered Sep 24 '22 06:09

Paul Fleming