C#idiomatic C#
ca2018fundamentals/code-analysis/quality-rules

Code analysis

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

Learn about code analysis rule CA2018: The count argument to Buffer.BlockCopy should specify the number of bytes to copy

CA2018 Reliability enabled by default in .NET 10: As warning
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

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:

csharp
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.

csharp
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