0

I have to: 1. Write an information to user. 2. Read the typed message. 3. If message is empty then close application.

It is very simple to just read the user input in following way and process it:

    static void Main(string[] args)
    {
        string line;
        Console.WriteLine(message);

        while ((line = Console.ReadLine()).Length > 0)
        {
            // process line here and return output to console

            Console.WriteLine(message);
        }
    }

But as I am a purist I want to omit all repeated statements (like "Console.WriteLine(message);" in this example). I have already tried the do{..}while(..) loop with no success (repeated Console.ReadLine() statements).

Do you have any smart idea how to accomplish this task?

2 Answers 2

1
while (true)
{
     Console.WriteLine(message);
     var line = Console.ReadLine();
     if (line == "") break;
     else DoStuff();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is it OK to use infinite loops and a break? I was taught that it's "undesirable coding".
IMO, it is OK since C# doesn't have any more suitable constructions for that. I would prefer while (true) than moving some to condition and hence duplicating it. I think this topic is pretty subjective.
0

Create lazily evaluated IEnumerable<string> (let's say I can get this IEnumerable from method ReadAllLines in sample below) which will return lines read from Console. Then you can do something like this with LINQ:

var lines = ReadAllLines()
                .TakeWhile(line => line != "");
foreach (var line in lines) DoStuff();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.