Notes, handling. Data in a Byte array is sometimes harder to manipulate and read. Often strings or string arrays are a better storage format.
First example. We measure byte array memory use. We allocate a Byte array. The reference to the Byte array requires 4 or 8 bytes on the stack.
And The 3 million elements, bytes, of the array require a bit less than 3 megabytes of memory.
Important In an array, each byte element requires exactly 1 byte. But there are additional costs involved.
Program This example uses a Byte array but not in a useful way. Byte arrays are useful as storage regions for images or binary data.
Dim value1 As Long = GC.GetTotalMemory(False)
' Create an array of 3 million bytes.' ... We specify the last index to create an array.
Dim bytes(1000 * 1000 * 3 - 1) As Byte
bytes(0) = 0
' Get memory and print the change.
Dim value2 As Long = GC.GetTotalMemory(False)
Console.WriteLine(value2 - value1)
' Ensure we have exactly 3 million bytes.
Example 2. The BinaryReader and BinaryWriter types are often used with Byte arrays. It is possible to use a Byte array, wrapped in a MemoryStream, with these types as a backing store.
Info This is an efficient approach to reading bytes, as it does not access the hard disk more than once.
' Byte array stores a JPG.
Dim array() As Byte = File.ReadAllBytes("C:\athlete.jpg")
Using memory As MemoryStream = New MemoryStream(array)
Using reader As BinaryReader = New BinaryReader(memory)
' Display values of first two bytes of JPG in memory.
Note, size. To create an array of 3 million elements, we must specify the last required element index, which is 3 million minus one. This is a key difference between VB.NET and C#.
A summary. A Byte array is a versatile type. It stores a direct, accurate representation of binary data. This includes images (JPG, PNG) as well as many different file formats.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 17, 2022 (simplify).