66
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??

3
  • 3
    How come you are comparing strings to enum values? Is there a way to avoid that completely?
    – dlev
    Jul 16, 2012 at 16:51
  • Trying to compare an enumeration to a string is a BAD idea. Jul 16, 2012 at 17:45
  • @SecurityHound often this is unavoidable when working on others codebases. Oct 19, 2018 at 0:37

7 Answers 7

72

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: ... }
}
4
  • 3
    This is far better than comparing the ToString() value of each of the enumerations. :)
    – myermian
    Jul 16, 2012 at 16:55
  • 3
    What's so bad about MyEnumValue.ToString() ?
    – Heinzlmaen
    Dec 15, 2020 at 15:42
  • @Heinzlmaen - ToString() works, but you'd compare 2 strings a bunch of times (for every enum) - nameString.Equals(JohnEnum.ToString()). And you could have uppercase/lowercase, etc. bugs. Using Enum.TryParse allows you to use a switch statement, which is cleaner in my opinion, and if you have to convert to lowercase etc. you'd only need to do it once in Enum.TryParse(nameString.ToLowerInvariant(), out myName)). Feb 2, 2021 at 19:52
  • TryParse also works with 3 parameters, the 2nd one set to true will perform a case-insensitive search over the enum set. I've almost never found case sensitive searches handy, using tricks like .ToLower etc in most compares.
    – dbeasy
    Apr 21 at 2:27
41

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 */
}
0
8

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: ...
    }
3

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

3

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 :)

1

I think you're looking for the Enum.Parse() method.

if(myname.Equals(Enum.Parse(Name.John)) //returns false
 {

 }
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.