0

I'm trying to determine if a string value read-in from a file is found within an enum in my code.

The enum:

internal enum Difficulty { None, Easy, Medium, Hard }

At this point in my code header[i] = "EASY". I want to compare this value to any of the values found in my Difficulty enum but am encountering issues.

The code:

Each time the following code is executed, the if statement returns false because "Easy" != "EASY".

Difficulty dif = Difficulty.None;
if (Difficulty.TryParse(header[i], out dif)) {      // RETURNS FALSE
    MyLog.Write("It's in the Enum!");
}

I've tried comparing the header[i] value to the Difficulty value in the TryParse statement, but it results in a compiler error.

Is there anything I can do besides changing all the Difficulty values to uppercase ones?

2
  • Please do not add answers to the question in the question itself. If you have found a solution, either mark one of the answers as correct or add an answer yourself. Commented Aug 5, 2016 at 10:36
  • 1
    @progy_rock My apologies, I had forgotten. I merely added the solution to my question for easy accessibility for anyone that reads this later on Commented Aug 5, 2016 at 10:50

3 Answers 3

2

Use the version of TryParse that supports ignoring case: https://msdn.microsoft.com/en-us/library/dd991317(v=vs.110).aspx

Your code becomes:

Difficulty dif = Difficulty.None;
if (Enum.TryParse<Difficulty>(header[i], true, out dif))
{      
    MyLog.Write("It's in the Enum!");
}
Sign up to request clarification or add additional context in comments.

Comments

1

The .ToString value for any Enum returns just the name your provide for it. So if you're gonna be doing this in a loop i suggest getting all the names to a local list and search in that which would result in better performance:

string[] enumNames = Enum.GetNames(typeof(Difficulty));

bool found = enumNames.Any(x => x.Equals(header[i], StringComparison.OrdinalIgnoreCase));

Comments

1

Yes there is!

Use the overload for Enum.TryParse that allows you to ignore the case:

if (Enum.TryParse("EASY", true, out dif))
{      
    Console.WriteLine("It's in the Enum!");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.