Returning in methods

WB1975

Well-known member
Joined
Apr 3, 2020
Messages
87
Programming Experience
Beginner
in this method

C#:
public static string GetLimitedString(string prompt, int min, int max)
{
    string userString;
    bool hasAString = false;
    do
    {
        Console.WriteLine(prompt);
        userString = Console.ReadLine();
        if (userString.Length >= min && userString.Length <= max)
        {
            return userString;
            hasAString = true;
        }

    } while (!hasAString);

    return userString;
}

if im returning in the loop, why does the method require another return?

what should the last return be? i dont really understand this.
 
Last edited by a moderator:
Your code doesn't really make sense. You are looping based on hasAString being false but the only time it gets set to true is after the return statement, so it will never be hit. Either get rid of that condition and use an infinite loop:
C#:
public static string GetLimitedString(string prompt, int min, int max)
{
    do
    {
        Console.WriteLine(prompt);

        var userString = Console.ReadLine();

        if (userString.Length >= min && userString.Length <= max)
        {
            return userString;
        }
    } while (true);
}
or actually use the condition and return only after the loop:
C#:
public static string GetLimitedString(string prompt, int min, int max)
{
    string userString;
    bool hasAString;

    do
    {
        Console.WriteLine(prompt);

        userString = Console.ReadLine();
        hasAString = userString.Length >= min && userString.Length <= max;
    } while (!hasAString);

    return userString;
}
 
Right so a return statement also breaks a loop, interesting didn't know that.
but im still confused to how in your second example you are breaking out of the loop

this is the line that does it right?
hasAString = userString.Length >= min && userString.Length <= max;

does that make it true? i dont really understand this.
 
Do loop continues while expression is true. hasAString is set true when userString.Length is between min and max. Then !hasAString expression will be "not true" = false.
 
hasAString is set true when userString.Length is between min and max. was throwing me off, thanks John
 
Remember that an if statement evaluates an expression of type bool. Any expression you can use in an if statement, you can use anywhere else a bool value is expected. That expression evaluates to true or false, so the hasAString variable will be set to true or false. When it's true, !hasAString will be false and the loop will exit. You may well have already got all that from @JohnH, but I thought I'd explain in my own words in case that added something.
 
Back
Top Bottom