how to compare string with enum in C#
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??
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 */
}