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??
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.
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.
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 .
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: ... } }
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 */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With