Error in GetString behavior

  • Thread starter Thread starter Trapulo
  • Start date Start date
T

Trapulo

If I execute this code, with realString as array of zeros, execution goes
always in "then" code:
If Not System.Text.ASCIIEncoding.ASCII.GetString(realString).Length = 0 Then

out.Append(System.Text.ASCIIEncoding.ASCII.GetString(realString))

End If



If I debug I have:

? System.Text.ASCIIEncoding.ASCII.GetString(realString).Length = 0

True



So I've two problems:

1 - the if is not evaualted as required

2 - if the out.append (out is a stringbuilder) is executed, no other strings
can be added to the stringbuilder. It stops responding.

Is this a bug? What can I do?

thanks
 
I don't think this is a bug. If you look at an ASCII table of characters
you'll see that "0" is null. You're basically evaluating a string of zeros
as ASCII text which is a null value. Therefore the length (of a null value)
is zero. You then append this to the stringbuilder which is essentially
appending a terminating null character. Therefore, you can't add any more
text...
 
Ok, so if I append a zero to a stringbuilder, it defines the end of the
string and I may avoid to convert byte arrays containing zeros to string if
I want to append it. That's reasonable..

Anyway, why the "if" is evaulated as true? As you said, "the lenght is
zero". So GetString(realString).Length = 0 may be true, and "not
GetString(realString).Length = 0" may be false. Instead, my out.append code
is still executed...

thanks
 
Well, I did a little testing on this to see why the "If" statement was being
evaluated this way. It seems that when using the ASCIIEncoding.GetString()
method to convert a byte array to a String it actually allocates space for
each of the bytes giving a length equal to the size of the array. However,
since the characters are all null characters (zeros) the value of the string
is shown as "" in the debugger. It isn't really empty though because neither
"Is String.Empty" nor '= ""' evaluates to True. The only way to catch
something like this would be to see if the ASCII code of the first character
was zero (null)...

Scott
 
Back
Top