I want to do something like this -
using System;
class MainClass
{
public static void Main ()
{
bool? input;
Console.WriteLine ("Are you Major?");
input = bool.Parse (Console.ReadLine ());
IsMajor (input);
}
public static void IsMajor (bool? Answer)
{
if (Answer == true) {
Console.WriteLine ("You are a major");
} else if (Answer == false) {
Console.WriteLine ("You are not a major");
} else {
Console.WriteLine ("No answer given");
}
}
}
Here if user gives no answer and simply presses enter, the variable input must store the value null
and output must be No answer given
.
In my code, input of true
and false
is working fine.
But if no input is given and enter is pressed the compiler throws the exception
System.FormatExeption has been thrown
String was not recognized as a valid Boolean
So how to get null
value stored in variable input
so that output is No answer given
Here,
the question String was not recognized as a valid boolean C#
is obviosly not a duplicate as it does not want to take null input directly from keyboard. And if such input can't be taken, what is the utility of nullable type, as there would be work around as well?