I have been trying to do error handling so that if someone just hit enter and didnt input a value it would ask for a proper value. It appears that just pressing enter returns a value via readline although i cant determine what value here is my code which is supposed to handle null values
public static string StringTester(string? input)
{
string output;
if (input != null)
{
Console.WriteLine("Not null nani");
}
if (input == null)
{
Console.WriteLine("Please input valid value");
output = StringTester(Console.ReadLine());
} else if (input.Contains('\n') ^ input.Contains(' ') ^ input.Contains('\r'))
{
Console.WriteLine("Please input valid value");
output = StringTester(Console.ReadLine());
}
else
{
output = input;
}
return output;
}
I tried to find the return value on google and through the documentation by microsoft on readline however none came up. I thought maybe it is reading a new line so i added a new line into the error handling.
CodePudding user response:
Console.ReadLine
will return a string
containing the characters that the user typed before hitting Enter. If they didn't type any characters then that string
will be empty, i.e. Console.ReadLine
will return string.Empty
.
CodePudding user response:
You can try using String.IsNullOrEmpty(String) for situations like this.
It will check if the string is null, or empty ("")
CodePudding user response:
Console.ReadLine
will return an empty string, if the user doesn't enters anything. To check for null, you can use the string.IsNullOrEmpty`
CodePudding user response:
For check an empty value from input you have to use:
if(string.IsNullOrEmpty(*yourString*)){//error handling}