Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
How to refactor these switch cases to handle user choice in natural language?

I'm writing several nested switch statements with quite a few cases in some spots.

I'm trying to figure out a way to create a list of cases to then be referenced in later switch statements.

Is there a way to do this?

It would certainly clean up my code.

For example, I have four separate cases for a "yes" answer.

I am looking for a way to store these four cases in a variable and call on that variable each time I want to use them in a switch.

Console.Write("\nWere you feeling exhausted? ");
response = Console.ReadLine().ToLower();
Console.Clear();
switch (response)
{
    case "yes":
    case "y":
    case "yep":
    case "yeah":
        {
            goto ThreeTwo;
        }
    case "no":
    case "n":
    case "nope":
    case "nah":
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

A nice clean way to do this is first to declare an enum to represent the answer values. It will need "Yes", "No" and "Undefined" (the latter to represent an answer which is neither "Yes" nor "No"):

public enum YesOrNo
{
    Undefined,
    Yes,
    No
}

Then you can wrap the yes/no detection logic in a class. There are many ways to do this; here's a simple one (you could use a dictionary instead, but for such a small number of strings it's not really necessary, and I'm trying to keep this as simple as possible):

public static class YesOrNoDetector
{
    static readonly string[] _yesAnswers = { "yes", "y", "yep", "yeah", "affirmative" };
    static readonly string[] _noAnswers  = { "no",  "n", "nah", "nope", "negative"    };

    public static YesOrNo Detect(string answer)
    {
        if (_yesAnswers.Contains(answer.ToLower()))
            return YesOrNo.Yes;

        if (_noAnswers.Contains(answer.ToLower()))
            return YesOrNo.No;

        return YesOrNo.Undefined;
    }
}

(Note how it also handles uppercase answers by converting the string to lowercase before comparing.)

Then your original code becomes something like:

switch (YesOrNoDetector.Detect(response))
{
    case YesOrNo.Yes:
    {
        goto ThreeTwo;  // Please get rid of this goto!
    }

    case YesOrNo.No:
    {
        // Handle "No".
        break;
    }

    case YesOrNo.Undefined:
    {
        // Handle incorrect answer.
        break;
    }
}
over 4 years ago · Santiago Trujillo Report

0

Having this enum:

public enum Answers
{
  Other,
  Yes,
  No
}

Any expected possibility can be added.

Also several enums can be created for various use cases.

Here Other means not defined, not predicted, unknown, etc.

We can define this allotment/distribution/dispatch table:

using System;
using System.Collections.Generic;

readonly Dictionary<Answers, List<string>> AcceptedAnswers
  = new Dictionary<Answers, List<string>>
  {
    { Answers.Yes, new List<string> { "yes", "y", "yep", "yeah" } },
    { Answers.No, new List<string> { "no", "n", "nope", "nah" } }
  };

Thus we can easily define synonyms for each enum value.

And we'll use it by defining this verification method:

Answers GetAnswer(string input)
{
  foreach ( Answers item in Enum.GetValues(typeof(Answers)) )
    if ( AcceptedAnswers.ContainsKey(item) )
      if ( AcceptedAnswers[item].Contains(input) )
        return item;
  return Answers.Other;
}

Test

Console.WriteLine("Do you agree?");
var answer = GetAnswer(Console.ReadLine());
Console.WriteLine();
Console.WriteLine($"Your answer is: {answer}.");

Output

Do you agree?
yep

Your answer is: Yes.

Advanced usage

bool retry;
do
{
  retry = false;
  Console.WriteLine("Do you agree?");
  var answer = GetAnswer(Console.ReadLine());
  Console.WriteLine();
  Console.WriteLine($"Your answer is: {answer}.");
  switch ( answer )
  {
    case Answers.Yes:
      // ...
      break;
    case Answers.No:
      // ...
      break;
    default:
      Console.WriteLine();
      Console.WriteLine("I don't understand :(");
      Console.WriteLine();
      retry = true;
      break;
  }
}
while ( retry );
Do you agree?
I don't know

Your answer is: Other.

I don't understand :(

Do you agree?
yeah

Your answer is: Yes.

Please do not use goto more than once per century.

How to resolve this compilation error "Using unassigned local variable 'hak'" when using goto?

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!