How to use the Buffer class in C#

Take advantage of the Buffer class in .NET to improve application performance through faster access to data in memory

A buffer is a sequence of bytes in memory and buffering is the manipulation of data residing in memory. In .NET buffering refers to the manipulation of the unmanaged memory, which is represented as an array of bytes. 

You might want to take advantage of the System.Buffer class in .NET whenever you need to write data to memory directly or whenever you want to manipulate data stored in unmanaged memory. This article talks about how we can work with the Buffer class in C#. 

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create a .NET Core console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.

This will create a new .NET Core console application project in Visual Studio 2019. We’ll use this project in the subsequent sections of this article.

Methods of the Buffer class in .NET

The Buffer class contains the following methods:

  • BlockCopy(Array, Int32, Array, Int32) is used to copy a source array from a specified offset to a target array at a specified offset.
  • ByteLength(Array) returns the total number of bytes in an array, i.e., the length of the array.
  • GetByte(Array, Int32) is used to retrieve a byte at a specified location in an array.
  • SetByte(Array, Int32, Byte) is used to set a byte at a given location in the array.
  • MemoryCopy(Void*, Void*, Int64, Int64) and MemoryCopy(Void*, Void*, UInt64, UInt64) are used to copy a number of bytes from a source address in the memory to another address.

Using arrays and buffers in C#

Before we starting working with the Buffer class and its members, let’s explore the Array class pertaining to the System namespace. The Array class contains a method named Copy() that can be used to copy the contents of one array to another.

The Buffer class in the System namespace contains a method named BlockCopy() that does the same thing. You can use BlockCopy() to copy the contents of a source array to a destination array. It should be noted that the Buffer.BlockCopy method is much faster than the Array.Copy method. The Buffer class also contains other methods such as ByteLength, GetByte, and SetByte.

Note that the BlockCopy method doesn’t copy the elements of a source array. Rather, BlockCopy copies a sequence of bytes from the source array to the destination array.

Copy bytes between two arrays in C#

You can take advantage of the Buffer.BlockCopy method to copy bytes between a source array and a destination array—as shown in the code snippet given below.

static void Main()
{
  short [] arr1 = new short[] { 1, 2, 3, 4, 5};
  short [] arr2 = new short[10];
  int sourceOffset = 0;
  int destinationOffset = 0;
  int count = 2 * sizeof(short);
  Buffer.BlockCopy(arr1, sourceOffset, arr2, destinationOffset, count);
  for (int i = 0; i < arr2.Length; i++)
  {
      Console.WriteLine(arr2[i]);
  }
  Console.ReadKey();
}

When you execute the above program, here’s how the output would look at the console window.

buffer class in csharp 01 IDG

Figure 1

Find the byte length of an array in C#

To find out the length of an array you can take advantage of the ByteLength method of the Buffer class as shown in the code example given below.

static void Main()
{
  short [] arr1 = new short[] { 1, 2, 3, 4, 5};
  short [] arr2 = new short[10];
  Console.WriteLine("The length of the arr1 is: {0}",
  Buffer.ByteLength(arr1));
  Console.WriteLine("The length of the arr2 is: {0}",
  Buffer.ByteLength(arr2));
  Console.ReadKey();
}

When you run the above program here's how the output would look:

buffer class in csharp 02 IDG

Figure 2

The SetByte and GetByte methods of the Buffer class can be used to set or read individual bytes to and from an array respectively. The following code snipet illustrates how the SetByte and GetByte methods can be used.

static void Main()
{
short[] arr1 = { 5, 25};
int length = Buffer.ByteLength(arr1);
Console.WriteLine("\nThe original array is as follows:-");
for (int i = 0; i < length; i++)
{
      byte b = Buffer.GetByte(arr1, i);
      Console.WriteLine(b);
}
Buffer.SetByte(arr1, 0, 100);
Buffer.SetByte(arr1, 1, 100);
Console.WriteLine("\nThe modified array is as follows:-");
for (int i = 0; i < Buffer.ByteLength(arr1); i++)
{
      byte b = Buffer.GetByte(arr1, i);
      Console.WriteLine(b);
}
    Console.ReadKey();
}

When you execute the above program, here’s how the output would appear.

buffer class in csharp 03 IDG

Figure 3

The Buffer class provides much better performance when manipulating a region of memory that contains primitive types. You should take advantage of the Buffer class whenever you need to manipulate data in memory and whenever you need fast access to data stored in the memory as well.

How to do more in C#:

Copyright © 2020 IDG Communications, Inc.

How to choose a low-code development platform