
You want to read or modify individual bytes in an array of many values using the C# language. The Buffer.GetByte and Buffer.SetByte methods in the System namespace provide a way to change bytes in an array, such as an array of integers or bytes.

You can use the Buffer.GetByte and Buffer.SetByte methods on an array of three integer values. Note that integers in C# code are represented by four bytes; by using GetByte and SetByte, you can read and assign the individual bytes in each integer directly. This changes the decimal representation of the integer by changing the bytes in the integer. This can be used to treat an integer array as a bitmask or other structure.
This C# example shows the Buffer.GetByte and Buffer.SetByte methods.
Program that uses Buffer.GetByte and Buffer.SetByte [C#]
using System;
class Program
{
static void Main()
{
// Use an array of three integers for testing.
// ... Loop through the bytes in the array and write their values.
int[] array1 = { 1, 1, 256 };
for (int i = 0; i < Buffer.ByteLength(array1); i++)
{
Console.WriteLine(Buffer.GetByte(array1, i));
}
// Set certain byte values at indexes in the array.
Buffer.SetByte(array1, 0, 55);
Buffer.SetByte(array1, 4, 55);
Buffer.SetByte(array1, 8, 55);
// Render the modified array.
Console.WriteLine("---");
for (int i = 0; i < Buffer.ByteLength(array1); i++)
{
Console.WriteLine(Buffer.GetByte(array1, i));
}
}
}
Output
1
0
0
0
1
0
0
0
0
1
0
0
---
55
0
0
0
55
0
0
0
55
1
0
0Treating arrays as blocks of memory. In the .NET Framework, arrays are stored in a single memory region and this is on the managed heap. The Buffer methods here, GetByte and SetByte, act upon this region. You can read and manipulate data in an array memory region just by indexes. Next, we note the implementation of these methods in the .NET Framework.

The Buffer.GetByte and Buffer.SetByte method calls are not written in C# code in the .NET Framework mscorlib library. Presumably, they are implemented in C or C++, and this can provide more performance for cases where large arrays or frequent operations upon them are necessary. Other benchmarks show that Buffer class methods are very fast.
Buffer.BlockCopy Method
We looked at how you can use the Buffer.GetByte and Buffer.SetByte methods in the .NET Framework and C# language. These methods allow you to treat an array of value types as a region of bytes; they work with all value types, not just ints or bytes. These are essentially convenience methods, but provide a good way to manipulate low-level data in the C# language.
Array Types