Reputation: 1155
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??
Upvotes: 69
Views: 129923
Reputation: 24526
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 */
}
Upvotes: 43
Reputation: 429
A slightly more elegant solution would be an string extension method:
public static bool Equals(this string enumString, Name value)
{
if(Enum.TryParse<Name>(enumString, out var v))
{
return value == v;
}
return false;
}
This way you can directly use .Equals() on the string as in the OPs first example.
Upvotes: 3
Reputation: 4534
For some reason, the given solutions didn't workout for me. I had to do in a slighly different way:
Name myName;
if (Enum.TryParse<Name>(nameString, out myName))
{
switch (myName) { case John: ... }
}
Hope it helps someone :)
Upvotes: 3
Reputation: 10367
If you using .NET4 or later you can use Enum.TryParse
. and Enum.Parse
is available for .NET2 and later
// .NET2 and later
try
{
switch (Enum.Parse(typeof(Names), myName))
{
case John: ...
case Peter: ...
}
}
// .NET4 and later
Name name;
if (Enum.TryParse(myName, out name))
switch (name)
{
case John: ...
case Peter: ...
}
Upvotes: 9
Reputation: 3930
One solution could be to get the type of the enum, and then the types name.
myname.Equals(Enum.GetName(typeof(Name)))
http://msdn.microsoft.com/en-us/library/system.enum.getname.aspx
Upvotes: 3
Reputation: 12245
I think you're looking for the Enum.Parse()
method.
if(myname.Equals(Enum.Parse(Name.John)) //returns false
{
}
Upvotes: 1
Reputation: 48596
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: ... }
}
Upvotes: 76