Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return type of "return" C# [closed]

I am making a console application and I have a "Menu" where the user can enter information to create a new Person object. The following is inside a method.

        Write("Please enter the first name: ", false);
        string fName = Console.ReadLine().ToUpper();
        Write("Please enter the middle initial: ", false);
        string mInitial = Console.ReadLine().ToUpper();
        Write("Please enter the last name: ", false);
        string lName = Console.ReadLine().ToUpper();

like so. I want the user to be able to exit the method at anytime if they decide they don't want to be making a new person. So I'd like to make a new method called "CheckExit" and if they type "EXIT" it will leave the "CreatePerson" method. So I want the "CheckExit" to return a return. Otherwise I have to add an "if" statement after every input and that gets clutter-y.

Is this possible? Does return have a return type? What would be the proper way to do this?

like image 270
Arkyris Avatar asked Feb 04 '20 05:02

Arkyris


1 Answers

return is not a type that you can return, it's a keyword for returning a result. So unfortunately what you are trying to do is not possible. However, you can make your code much more readable and extendable by using an array of queries and getting the results for each inside of a loop. This has the bonus effect of being able to add more queries with ease.

// you can put these queries somewhere outside the function
string[] queries = {"Please enter the first name: ", ...}
var results = new List<string>();

foreach (string query in queries) {
    Write(query, false);
    var result = Console.ReadLine().ToUpper();
    if (result.Equals("EXIT") {
        return;
    }
    results.Add(result);
}

// handle your inputs from the results list here ...
like image 95
Jan Schultke Avatar answered Oct 05 '22 17:10

Jan Schultke