Menu

Using the string value of a C# enum value in a case statement

I prefer to use enums instead of string in my projects, I think it’s better way rather than hard coding the string.

I can define the enums as below

public enum QuestionTypes
{
    Text,
    MultipleChoice,
    Essay
};

If you want to shorten the namespace you can use this

using ParentTypes = Models.Question.QuestionTypes;

Then you can use the switch statement like this

switch ((QuestionTypes)Enum.Parse(typeof(QuestionTypes), inputModel.QuestionType))
{
     case QuestionTypes.Text:

       break;
     case QuestionTypes.MultipleChoice:

       break;
     case QuestionTypes.Essay:

       break;
}

if you also want to validate the enum you can wrap it with a Enum.IsDefined check

if (Enum.IsDefined(typeof(QuestionTypes), inputModel.QuestionType))
{
     switch ((QuestionTypes)Enum.Parse(typeof(QuestionTypes), inputModel.QuestionType))
     {
          case QuestionTypes.Text:

            break;
          case QuestionTypes.MultipleChoice:

            break;
          case QuestionTypes.Essay:

            break;
     }
}else{
     // this is where to do you validation logic
}

Sweet.

Leave a comment