
You need to count the total number of bytes stored in all elements in an array in your C# program. Although you could find the size by using sizeof with the element count, the Buffer.ByteLength static method provides an easier way to do this.

Initially here, we see a program text that introduces the Main entry point. There are two arrays—an integer array and a byte array—that are allocated on the managed heap. Then, we use the Buffer.ByteLength method to count the total number of bytes in each array. Each int is four bytes, and each byte is a single byte, and thee sizes of the total arrays reflect this.
Program that uses Buffer.ByteLength method [C#]
using System;
class Program
{
static void Main()
{
// Example arrays for program.
// ... Each array has three elements.
int[] array1 = { 1, 2, 3 };
byte[] array2 = { 1, 2, 3 };
// Get lengths of arrays.
// ... This counts the bytes in all elements.
int length1 = Buffer.ByteLength(array1);
int length2 = Buffer.ByteLength(array2);
// Write results.
Console.WriteLine(length1);
Console.WriteLine(length2);
}
}
Output
12
3Internal implementation. Internally, the Buffer.ByteLength method accesses external code in the .NET Framework. However, the Buffer class overall uses lower-level methods such as memcpy which can provide performance advantages, so the Buffer.ByteLength method likely uses some lower-level functions in native code to compute the byte length.

Uses. In earlier releases of the .NET Framework, the sizeof operator was not available except in unsafe code contexts. For these .NET programs, Buffer.ByteLength could provide a way for element sizes to be computed without using sizeof. However, in current .NET releases, the sizeof operator is available in all contexts for value types, and it evaluates to a constant.
The C# Programming Language: SpecificationWe looked at how you can call the Buffer.ByteLength method to count the total number of bytes in an array. This method is part of the Buffer class and it is a static parameterful method. It could be useful if you want to encode an array of value types as an array of bytes directly. Please see the BitConverter class for information about how you can change representations of value types.
BitConverter Examples Array Types