3

I am sending the string representation of a boolean through a socket and reading it 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 get the following exception when I try and parse my message:

String was not recognized as a valid boolean.

The value when I get the exception is: True. With NO whitespace.

Cheetah
  • 13,785
  • 31
  • 106
  • 190
  • 1
    Are you absolutely sure that is what is what is received? I'd be stunned if you had found a genuine bug in the framework - http://msdn.microsoft.com/en-us/library/system.boolean.parse.aspx – Daniel Kelley Jan 24 '13 at 11:14
  • 1
    What is the value of message _when you get the exception?_ – Eren Ersönmez Jan 24 '13 at 11:15
  • Do you have any special characters in your message? – Ravi Y Jan 24 '13 at 11:15
  • No I print it out, along with the length of the message. Literally all I am sending is `True` or `False`...I check both before and after the Socket the length of the string and the string itself. – Cheetah Jan 24 '13 at 11:17
  • @ErenErsönmez: Look at the question (code comment) – jAC Jan 24 '13 at 11:18
  • Try to check with `String.Compare(message, Boolean.TrueString, StringComparison.CurrentCultureIgnoreCase);` and `String.Compare(message, Boolean.FalseString, StringComparison.CurrentCultureIgnoreCase);`. If both return false, check char by char to find differences. – default locale Jan 24 '13 at 11:18
  • There must be an issue with your message string. Are you sure that it is definitely "true" or "false"?? – Azhar Khorasany Jan 24 '13 at 11:20
  • What about Convert.ToBool()? – Stefano Altieri Jan 24 '13 at 11:23
  • 2
    Try `bool.Parse("True")` and see if you still get a formatexception? If you don't, then your received message is not exactly "True"... – Eren Ersönmez Jan 24 '13 at 11:23
  • 2
    I would take a look in the debugger at what the receive string contains - or better still in a watch window put message.ToCharArray() and see if there are any "special" characters in there. Sometimes I've seen control chars in strings that don't print out but are still there. – MrPurpleStreak Jan 24 '13 at 11:24
  • @defaultlocale the string compare with Boolean.TrueString returns 0. – Cheetah Jan 24 '13 at 11:25
  • @Ben is there any code in between `String.Compare` and `Boolean.Parse` calls? if the answer is "yes", then comment it out and try again, otherwise, please, tell us .net framework version details. – default locale Jan 24 '13 at 11:31
  • you could do something like this bool result = bool.Parse(message == "True" ? "true" : "false"); – KevDevMan Jan 24 '13 at 11:34
  • @MrPurpleStreak no special characters. – Cheetah Jan 24 '13 at 11:39
  • @defaultlocale There are no calls. .Net 4.0 – Cheetah Jan 24 '13 at 11:39
  • @KevDevMan I could, but that's not the point, I don't want to have to do that! – Cheetah Jan 24 '13 at 11:40
  • @Ben, what does `Boolean.Parse(Boolean.TrueString)` return? – default locale Jan 24 '13 at 11:41
  • @defaultlocale returns a boolean with value true. – Cheetah Jan 24 '13 at 11:58
  • I've narrowed down the problem. When linking to the library external to the solution I am working on I get the problem...but when I create a test bed within the solution I DON'T get an issue. The library I am linking to is ABSOLUTELY unequivocally the latest build - NO DOUBT WHAT SO EVER about that. – Cheetah Jan 24 '13 at 11:59
  • Try converting the String to lower case first. See this post for details [Why does Boolean.ToString output “True” and not “true”](http://stackoverflow.com/questions/491334/why-does-boolean-tostring-output-true-and-not-true) – KevDevMan Jan 24 '13 at 11:16
  • Already tried converting to lowercase, also uppercase. Neither worked. – Cheetah Jan 24 '13 at 11:18
  • Following the MSDN (http://msdn.microsoft.com/de-de/library/system.boolean.parse.aspx) this shouldn't be the problem – jAC Jan 24 '13 at 11:19
  • you said the value for the `message` is `True`,i wanted to know whether it is `true` or `True`. – Kiran1016 Jan 24 '13 at 12:26
  • `bool.Parse` should be able to parse `true`, `True`, `trUe`, or even `trUe `. I would try parsing a constant string that has the same value that you think the variable has, and then compare that string with the variable. Either your `bool.Parse` is not working as expected, or the variable does not have the value that you think it does (or that it appears to have). – Dave Cousineau Mar 28 '15 at 16:18
  • What kind of `Socket` are you using? Is it `System.Net.Sockets.Socket`? – Dave Cousineau Mar 28 '15 at 16:20
  • I didn't realize this was 2 years old... – Dave Cousineau Mar 28 '15 at 16:25

2 Answers2

1

At first glance, I would consider it having an issue with untrimmed space..., but that's not the case, as Boolean.Parse uses TryParse and that, in turn, trims the space in one of its 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's 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;
}

Reference: http://referencesource.microsoft.com/#mscorlib/system/boolean.cs,e2a8f2e50ecf93c0,references

So, there must be something else going on. Perhaps there is an issue with the format, UTF-8, ANSI, ASCII, etc. One of your requirements is that you want a bool, so that 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 you're expecting cases beyond True or False, in which case the result could be invalid. 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's true; if False, it's false; otherwise, it's null, which indicates an invalid message. You can then check to see if result is null and either display the invalid message or do something else. I'm not sure what your routine is from there on.

B.K.
  • 9,982
  • 10
  • 73
  • 105
0

Try This:

void Receive()
{
    string message = Socket.Receive();

    Console.WriteLine(message) // Always equal to either 'True' or 'False (without quotes)

    bool result = message.ToLower().Equals("true");
}
One Man Crew
  • 9,420
  • 2
  • 42
  • 51