David,
Because I have made so many samples for the bytearray in this situation, I
want to turn it around, give me one practical sample where adding a byte to
an arraylist would be a right solution.
So not that you can add a byte to an arraylist, I know I can do that (you
can add any object to a arraylist), however for what situation would it be a
practical solution?
OK, you've got some kind of code reader that sends a stream of bytes to
you, but the verification program (named Foo, naturally) you have only
wants bytes with the upper bit unset.
Private Sub VerifyWithList(ByVal stm As Stream)
Dim list As New ArrayList
Dim input As Integer
Do
input = stm.ReadByte()
If input = -1 Then Exit Do
If input >= 0 AndAlso input <= 127 Then
list.Add(CByte(input))
End If
Loop
Foo(DirectCast(list.ToArray(GetType(Byte)), Byte()))
End Sub
Now, as I mentioned, I tend to use typed collections, so the cast at the
end would go away (which is by far the most complex line), but otherwise
this is probably my first implementation. The two things that leap out
are (a) I'm not thrilled about the way I'm reading the stream here, and
(b) the infinite loop might throw some programmers for a moment, but I
think it's the cleanest implementation (see McConnell's Code Complete
for reams of discussion about formatting this type of loop), but if
someone in code review insisted I be more explicit here I wouldn't
argue.
Here's the function I wouldn't write:
Private Sub Verify(ByVal stm As Stream)
Dim bytes(ESTIMATED) As Byte
Dim index As Integer = 0
Dim input As Integer
Do
input = stm.ReadByte()
If input = -1 Then Exit Do
If input >= 0 AndAlso input <= 127 Then
If index > bytes.Length Then
ReDim Preserve bytes(bytes.Length + ESTIMATED)
End If
bytes(index) = CByte(input)
index += 1
End If
Loop
ReDim Preserve bytes(index - 1)
Foo(bytes)
End Sub
Just to be honest here, I'm posting this as I really did first write it.
And sure enough, it has a bug. The first function is trivial to write
and easy to read. The second function is much trickier. A bug in the
first function would leap out at you at a glance, the bug in the second
function isn't easy to see without looking fairly closely at the code.
And what I absolutely would never do is finish the above like this:
Foo(bytes, index-1)
' while I define Foo as
Public Sub Foo(bytes() as Byte, validBytes as Integer)
One additional point. Jay pretty much had me convinced that I should
worry about boxing much earlier than I tend to. But I can't even
measure the different in timespans that the above two functions take to
run (not with a DateTime object anyway, the noise overwhelms the
difference), even as the array grows to thousands of bytes. That
surprised me, I admit.