Efficient way to compare a string to a particular enum value (not just any value in the enum).

I have a class whose ToString() should return a value that's in an enum. I know I can easily check if the string is one of the enum values using Enum.TryParse(), however checking if it is one particular value in that enum requires an extra step. I've figured out two ways to do this, my question is which is more efficient?

1) Uses TryParse, but requires an extra variable and if statement.

GeneralSkills skillName; if (Enum.TryParse<GeneralSkills>(skill.ToString(), out skillName)) { if (skillName == GeneralSkills.Tactics) // use == or .Equals()? { // do stuff } } 

2) Compares string literals, but simpler code

if (skill.ToString().Equals(GeneralSkills.Tactics.ToString)) { // do stuff } 

by StingyWithUpvotes via /r/csharp

Leave a Reply