Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
709 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...