how to compare string with enum in C#

Viewed 102985
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??

7 Answers

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.

Related