A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2018 below:

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

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 9 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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4