CA2018: The count argument to Buffer.BlockCopy should specify the number of bytes to copy

Property Value
Rule ID CA2018
Title The count argument to Buffer.BlockCopy should specify the number of bytes to copy
Category Reliability
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 As warning

Cause

This rule fires when Array.Length is used for the count argument of Buffer.BlockCopy on arrays whose elements are larger than one byte in size.

Rule description

When using Buffer.BlockCopy, the count argument specifies the number of bytes to copy. You should only use Array.Length for the count argument on arrays whose elements are exactly one byte in size. byte, sbyte, and bool arrays have elements that are one byte in size.

How to fix violations

Specify the number of bytes that you intend to copy for the count argument.

Example

Violation:

using System;
class Program
{
    static void Main()
    {
        int[] src = new int[] {1, 2, 3, 4};
        int[] dst = new int[] {0, 0, 0, 0};

        Buffer.BlockCopy(src, 0, dst, 0, src.Length);
    }
}

Fix:

If your array's elements are larger than one byte in size, you can multiply the length of the array by the element size to get the number of bytes.

using System;
class Program
{
    static void Main()
    {
        int[] src = new int[] {1, 2, 3, 4};
        int[] dst = new int[] {0, 0, 0, 0};

        Buffer.BlockCopy(src, 0, dst, 0, src.Length * sizeof(int));
    }
}

When to suppress warnings

It is generally NOT safe to suppress a warning from this rule.

See also