Char Array "Unexpected Results"
I just spent a few hours of debugging effort and at the end, I discovered something that might be of use to someone else. It's not a bug. That is, if you took the time to report it to Microsoft, they wouldn't admit it's a bug. But after reading a lot of pages at MSDN, I happened to discover this on one of them:
"Null characters (equivalent to Chr(0)) in the string lead to unexpected results when using the string. The null character will be included with the string, but characters following the null character will not be displayed in some situations."
"Some situations" ??? What situations? Isn't programming supposed to be a precise activity. We're not supposed to have to guess about what will happen.
Here's the code I was working on. To code along with me, create a standard Windows application with two TextBox components (InputString and OutputString - set Multiline to True) and a Button to kick off the code.
Private Sub ReformatString_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles ReformatString.Click
Dim InCharArray() As Char = _
CType(InputString.Text, Char())
Dim OutCharArray(19) As Char
Dim OutStringBuilder As New StringBuilder
Dim InIndex As Integer = 0
Do While InIndex < InCharArray.Length - 20
Array.Copy( _
InCharArray, InIndex, OutCharArray, 0, 20)
OutStringBuilder.AppendLine( _
New String(OutCharArray))
InIndex += 20
Loop
OutputString.Text = OutStringBuilder.ToString
End Sub
This works. It reformats the string as a 20 character column. (The last few chars are skipped, but that's not the point here.)
My error (Yes, I did create the problem with a coding error initially.) was to code:
Array.Copy( _
InCharArray, InIndex, OutCharArray, 0, 19)
The effect of this was to leave a null character in the last element of OutCharArray. And the effect of that was to break:
- StringBuilder - VB reported the correct length but not the content of the resulting StringBuilder object. Nothing after the null character could be accessed or displayed.
But more surprising ...
- Debug.Write and Console.Write - I even found that single step mode gave different results than running the code with breakpoints! With no code changes! This added hours to my debugging effort!
All for getting one index number wrong.


Comments
I wonder what other “not bugs” would be discovered from a global search for “some ” in Microsoft’s programming documentation?
What a great idea!
I tried it. There are a grundle of them. Maybe two grundles.
Thanks for this. I’m going to do a new blog about it.