I got a weird problem. I create an object(inside that object i call readline..) then the program quits despite I called ReadLine() at the end.
Why it doesn't stop? How to make it stops?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Funkcjonalnosc {
class MainClass {
static void Main(string[] args) {
new MainMenu();
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Funkcjonalnosc {
public class MainMenu {
int selection;
public MainMenu() {
showMenu();
selection = getSelection();
Console.WriteLine("Wybrano "+ selection);
switch (selection) {
case 1: break; //strojenie
case 2: break; //pobieranie stroju
}
}
void showMenu() {
String menu = "1. Nastrój\n2. Dodaj strój";
Console.WriteLine(menu);
}
int getSelection() {//pobiera wybrana opcje z menu{
try {
return Console.Read();
} catch (Exception e) { Console.WriteLine("Zly wybor"); getSelection(); }
return -1;
}
}
}
From MSDN on Console.Read
:
The Read method blocks its return while you type input characters; it terminates when you press the Enter key
So if I type, say, 1 it doesn't do anything - until I type enter. When I do that, Console.Read
returns the 1, but the enter is still buffered. When you use Console.ReadLine
, it fetches this buffered enter so exits immediately. You can see this by typing 123enter - the Read
fetches the 1 - and the ReadLine
fetches the remaining 23.
To avoid this buffering behavior, you might want to try Console.ReadKey
instead.