Better way to exit do-while loop?

93 views Asked by At

I have a pop for a user to enter a username and then what group to be added to in AD. I can't think of another way to exit my loop other than doing two separate if-statements. Is there a different way to exit the loop other than this? or I am overthinking this?

bool isExit = false;
 do
 {
     Console.Write("Enter the username(Type 'exit' to go back to menu): ");
     string username = Console.ReadLine();
     if(username.ToLower() == "exit")
     {
         isExit = true;
     }
     Console.Write("Enter the group name (Type 'exit' to go back to menu): ");
     string groupName = Console.ReadLine();
     
     if(groupName.ToLower() == "exit")
     {
         isExit = true;
     }
}while(!IsExit);
3

There are 3 answers

0
Dai On

Unfortunately C# doesn't support non-local returns (so I'm envious of Kotlin users), but you can refactor your logic down to a single reusable loop that you can move into its own function - just reserve null as a special-value for the quit/exit case:

If you're using a semi-recent version of C#, you can refactor it into a static-local function which is handy - but a class-level static method is fine too.

public static void Main()
{
    static String? Prompt( String msg, Func<String,Boolean> isValid )
    {
        while( true )
        {
            Console.WriteLine( msg );
            String input = Console.ReadLine()?.Trim() ?? String.Empty;
            if( "q".Equals( input, StringComparison.OrdinalIgnoreCase ) ) return null;
            else if( isValid( input ) ) return input;
        }
    }

    // 

    String? userName = Prompt( "Enter the username - or enter 'q' to quit", str => !String.IsNullOrWhitespace( str ) );
    if( userName is null ) return;

    String? groupName = Prompt( "Enter the group-name - or enter 'q' to quit", str => !String.IsNullOrWhitespace( str ) );
    if( groupName is null ) return;

    //

    DoStuff( userName, groupName );
}
3
user23459013 On

Another way you can try using is a label that essentially works as a break; command but for do-while loops.

bool isExit = false;
    do
    {
        Console.Write("Enter the username(Type 'exit' to go back to menu): ");
        string username = Console.ReadLine();
        if (username.ToLower() == "exit") {
            goto exitLoop;
        }
        Console.Write("Enter the group name (Type 'exit' to go back to menu): ");
        string groupName = Console.ReadLine();

        if (groupName.ToLower() == "exit") {
            goto exitLoop;
        }
    } while (!IsExit);
exitLoop:
isExist = true;
//continue rest of your code.
6
sss On

This is a fine way to do it. You definitely don't want to use the break keyword because that is considered bad practice and I'm guessing this is for school so you would get points taken off for literally breaking your code.