The line was not recognized as a valid boolean
I am sending a string representation of a boolean over a socket and reading it on the other end.
void Send(bool value)
{
Socket.Send(value.ToString());
}
void Receive()
{
string message = Socket.Receive();
Console.WriteLine(message) // Always equal to either 'True' or 'False (without quotes)
bool result = bool.Parse(message) // here I get the format exception.
}
but I am getting the following exception when I try to parse mine message
:
String was not recognized as a valid boolean
...
The value in the preparation of exceptions True
. Without spaces.
source to share
At first glance, I would think that this is a raw space problem ... but it is not as it Boolean.Parse
uses TryParse
, and this in turn truncates the space in one of my attempts:
public static Boolean Parse (String value) {
if (value==null) throw new ArgumentNullException("value");
Contract.EndContractBlock();
Boolean result = false;
if (!TryParse(value, out result)) {
throw new FormatException(Environment.GetResourceString("Format_BadBoolean"));
}
else {
return result;
}
}
public static Boolean TryParse (String value, out Boolean result) {
result = false;
if (value==null) {
return false;
}
// For perf reasons, let first see if they're equal, then do the
// trim to get rid of white space, and check again.
if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) {
result = true;
return true;
}
if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) {
result = false;
return true;
}
// Special case: Trim whitespace as well as null characters.
value = TrimWhiteSpaceAndNull(value);
if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) {
result = true;
return true;
}
if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) {
result = false;
return true;
}
return false;
}
Link: http://referencesource.microsoft.com/#mscorlib/system/boolean.cs,e2a8f2e50ecf93c0,references
So, there must be something else. Maybe there is a problem with UTF-8, ANSI, ASCII, etc. One of your requirements is that you want a bool, so you won't have two cases for True
and False
, so why not do something like this:
bool result = message.ToLower().Contains("true"); // true or false
EDIT:
After reading some of the comments, it seems that you are expecting cases out of bounds True
or False
, in which case the result may not be valid. I suggest something like this:
var lMessage = message.ToLower();
bool? result = lMessage.Equals("true") ? true : lMessage.Equals("false") ? false : null;
So, if the message contains True
, it is True
; if False
, it False
; otherwise, it is null
, which indicates an invalid message. Then you can check if there is result
null
and either display an invalid message or do something else. I'm not sure if your program is from there.
source to share