Skip to content

Commit 967fc11

Browse files
committed
add CA2022
1 parent 533033d commit 967fc11

File tree

16 files changed

+200
-29
lines changed

16 files changed

+200
-29
lines changed

docs/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,3 +123,7 @@ In general, code should:
123123
- <xref:System.Security.Cryptography.CryptoStream.Read%2A?displayProperty=fullName>
124124
- <xref:System.Security.Cryptography.CryptoStream.ReadAsync%2A?displayProperty=fullName>
125125
- <xref:System.Security.Cryptography.CryptoStream.BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object)?displayProperty=fullName>
126+
127+
## See also
128+
129+
- [CA2022: Avoid inexact read with Stream.Read](../../../../fundamentals/code-analysis/quality-rules/ca2022.md)

docs/core/whats-new/dotnet-8/sdk.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -174,16 +174,16 @@ You can opt out of verification by setting the environment variable `DOTNET_NUGE
174174
.NET 8 includes several new code analyzers and fixers to help verify that you're using .NET library APIs correctly and efficiently. The following table summarizes the new analyzers.
175175

176176
| Rule ID | Category | Description |
177-
|--|--|--|
178-
| CA1856 | Performance | Fires when the <xref:System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute> attribute is not applied correctly on a parameter. |
179-
| CA1857 | Performance | Fires when a parameter is annotated with <xref:System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute> but the provided argument isn't a constant. |
177+
|---------|----------|-------------|
178+
| [CA1856](../../../fundamentals/code-analysis/quality-rules/ca1856.md) | Performance | Fires when the <xref:System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute> attribute is not applied correctly on a parameter. |
179+
| [CA1857](../../../fundamentals/code-analysis/quality-rules/ca1857.md) | Performance | Fires when a parameter is annotated with <xref:System.Diagnostics.CodeAnalysis.ConstantExpectedAttribute> but the provided argument isn't a constant. |
180180
| [CA1858](../../../fundamentals/code-analysis/quality-rules/ca1858.md) | Performance | To determine whether a string starts with a given prefix, it's better to call <xref:System.String.StartsWith%2A?displayProperty=nameWithType> than to call <xref:System.String.IndexOf%2A?displayProperty=nameWithType> and then compare the result with zero. |
181181
| [CA1859](../../../fundamentals/code-analysis/quality-rules/ca1859.md) | Performance | This rule recommends upgrading the type of specific local variables, fields, properties, method parameters, and method return types from interface or abstract types to concrete types when possible. Using concrete types leads to higher quality generated code. |
182182
| [CA1860](../../../fundamentals/code-analysis/quality-rules/ca1860.md) | Performance | To determine whether a collection type has any elements, it's better to use `Length`, `Count`, or `IsEmpty` than to call <xref:System.Linq.Enumerable.Any%2A?displayProperty=nameWithType>. |
183183
| [CA1861](../../../fundamentals/code-analysis/quality-rules/ca1861.md) | Performance | Constant arrays passed as arguments aren't reused when called repeatedly, which implies a new array is created each time. To improve performance, consider extracting the array to a static readonly field. |
184184
| [CA1865-CA1867](../../../fundamentals/code-analysis/quality-rules/ca1865-ca1867.md) | Performance | The char overload is a better-performing overload for a string with a single char. |
185-
| CA2021 | Reliability | <xref:System.Linq.Enumerable.Cast%60%601(System.Collections.IEnumerable)?displayProperty=nameWithType> and <xref:System.Linq.Enumerable.OfType%60%601(System.Collections.IEnumerable)?displayProperty=nameWithType> require compatible types to function correctly. Widening and user-defined conversions aren't supported with generic types. |
186-
| CA1510-CA1513 | Maintainability | Throw helpers are simpler and more efficient than an `if` block constructing a new exception instance. These four analyzers were created for the following exceptions: <xref:System.ArgumentNullException>, <xref:System.ArgumentException>, <xref:System.ArgumentOutOfRangeException> and <xref:System.ObjectDisposedException>. |
185+
| [CA2021](../../../fundamentals/code-analysis/quality-rules/ca2021.md) | Reliability | <xref:System.Linq.Enumerable.Cast%60%601(System.Collections.IEnumerable)?displayProperty=nameWithType> and <xref:System.Linq.Enumerable.OfType%60%601(System.Collections.IEnumerable)?displayProperty=nameWithType> require compatible types to function correctly. Widening and user-defined conversions aren't supported with generic types. |
186+
| [CA1510-CA1513](../../../fundamentals/code-analysis/quality-rules/ca1510.md) | Maintainability | Throw helpers are simpler and more efficient than an `if` block constructing a new exception instance. These four analyzers were created for the following exceptions: <xref:System.ArgumentNullException>, <xref:System.ArgumentException>, <xref:System.ArgumentOutOfRangeException> and <xref:System.ObjectDisposedException>. |
187187

188188
## Diagnostics
189189

docs/core/whats-new/dotnet-9/sdk.md

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
---
2-
title: What's new in the SDK for .NET 9
2+
title: What's new in the SDK and tooling for .NET 9
33
description: Learn about the new .NET SDK features introduced in .NET 9, including for unit testing, terminal logger, tool roll-forward, and build script analyzers.
44
titleSuffix: ""
5-
ms.date: 10/08/2024
5+
ms.date: 10/26/2024
66
ms.topic: whats-new
77
---
88

9-
# What's new in the SDK for .NET 9
9+
# What's new in the SDK and tooling for .NET 9
1010

11-
This article describes new features in the .NET SDK for .NET 9. It's been updated for .NET RC 2.
11+
This article describes new features in the .NET SDK and tooling for .NET 9. It's been updated for .NET RC 2.
1212

1313
## Unit testing
1414

@@ -200,3 +200,19 @@ Requirements (depending on your environment):
200200
### Environment variable naming
201201

202202
Environment variables that the container publish tooling uses to control some of the finer aspects of registry communication and security now start with the prefix `DOTNET` instead of `SDK`. The `SDK` prefix will continue to be supported in the near term.
203+
204+
## Code analysis
205+
206+
.NET 9 includes several new code analyzers and fixers to help verify that you're using .NET library APIs correctly and efficiently. The following table summarizes the new analyzers.
207+
208+
| Rule ID | Category | Description |
209+
|---------|----------|-------------|
210+
| [CA1514: Avoid redundant length argument](../../../fundamentals/code-analysis/quality-rules/ca1514.md) | Maintainability | An explicitly calculated length argument can be error-prone and is unnecessary when you're slicing to the end of a string or buffer. |
211+
| [CA1515: Consider making public types internal](../../../fundamentals/code-analysis/quality-rules/ca1515.md) | Maintainability | Types inside an executable assembly should be declared as `internal`. |
212+
| [CA1871: Do not pass a nullable struct to 'ArgumentNullException.ThrowIfNull'](../../../fundamentals/code-analysis/quality-rules/ca1871.md) | Performance | For improved performance, it's better to check the `HasValue` property and manually throw an exception than to pass a nullable struct to `ArgumentNullException.ThrowIfNull`. |
213+
| [CA1872: Prefer 'Convert.ToHexString' and 'Convert.ToHexStringLower' over call chains based on 'BitConverter.ToString'](../../../fundamentals/code-analysis/quality-rules/ca1872.md) | Performance | Use <xref:System.Convert.ToHexString*?displayProperty=nameWithType> or <xref:System.Convert.ToHexStringLower*?displayProperty=nameWithType> when encoding bytes to a hexadecimal string representation. |
214+
| [CA2022: Avoid inexact read with Stream.Read](../../../fundamentals/code-analysis/quality-rules/ca2022.md) | Reliability | A call to `Stream.Read` might return fewer bytes than requested, resulting in unreliable code if the return value isn't checked. |
215+
| [CA2262: Set 'MaxResponseHeadersLength' properly](../../../fundamentals/code-analysis/quality-rules/ca2262.md) | Usage | The <xref:System.Net.Http.HttpClientHandler.MaxResponseHeadersLength?displayProperty=nameWithType> property is measured in kilobytes, not bytes. |
216+
| [CA2263: Prefer generic overload when type is known](../../../fundamentals/code-analysis/quality-rules/ca2263.md) | Usage | Generic overloads are preferable to overloads that accept an argument of type <xref:System.Type?displayProperty=fullName> when the type is known at compile time. |
217+
| [CA2264: Do not pass a non-nullable value to 'ArgumentNullException.ThrowIfNull'](../../../fundamentals/code-analysis/quality-rules/ca2264.md) | Usage | Certain constructs like non-nullable structs (except for <xref:System.Nullable%601>), 'nameof()' expressions, and 'new' expressions are known to never be null, so `ArgumentNullException.ThrowIfNull` will never throw. |
218+
| CA2265 | Usage | Comparing a span to `null` or `default` might not do what you intended. `default` and the `null` literal are implicitly converted to <xref:System.Span`1.Empty?displayProperty=nameWithType>. Remove the redundant comparison or make the code more explicit by using `IsEmpty`. |

docs/fundamentals/code-analysis/overview.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ The following rules are enabled, by default, as errors or warnings in .NET 8. Ad
4949
| [CA2017](quality-rules/ca2017.md) | Reliability | Warning | .NET 6 | Parameter count mismatch |
5050
| [CA2018](quality-rules/ca2018.md) | Reliability | Warning | .NET 6 | The `count` argument to `Buffer.BlockCopy` should specify the number of bytes to copy |
5151
| [CA2021](quality-rules/ca2021.md) | Reliability | Warning | .NET 8 | Do not call `Enumerable.Cast<T>` or `Enumerable.OfType<T>` with incompatible types |
52+
| [CA2022](quality-rules/ca2022.md) | Reliability | Warning | .NET 9 | Avoid inexact read with `Stream.Read` |
5253
| [CA2200](quality-rules/ca2200.md) | Usage | Warning | .NET 5 | Rethrow to preserve stack details |
5354
| [CA2247](quality-rules/ca2247.md) | Usage | Warning | .NET 5 | Argument passed to `TaskCompletionSource` constructor should be <xref:System.Threading.Tasks.TaskCreationOptions> enum instead of <xref:System.Threading.Tasks.TaskContinuationOptions> |
5455
| [CA2252](quality-rules/ca2252.md) | Usage | Error | .NET 6 | Opt in to preview features |

docs/fundamentals/code-analysis/quality-rules/ca1872.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,13 @@ dev_langs:
1616

1717
# CA1872: Prefer 'Convert.ToHexString' and 'Convert.ToHexStringLower' over call chains based on 'BitConverter.ToString'
1818

19-
| | Value |
20-
| ----------------------------------- |---------------------------------------------------------------------------------------------------------------|
21-
| **Rule ID** | CA1872 |
22-
| **Title** | Prefer 'Convert.ToHexString' and 'Convert.ToHexStringLower' over call chains based on 'BitConverter.ToString' |
23-
| **Category** | [Performance](performance-warnings.md) |
24-
| **Fix is breaking or non-breaking** | Non-breaking |
25-
| **Enabled by default in .NET 9** | As suggestion |
19+
| | Value |
20+
|-------------------------------------|----------------------------------------|
21+
| **Rule ID** | CA1872 |
22+
| **Title** | Prefer `Convert.ToHexString` and `Convert.ToHexStringLower` over call chains based on `BitConverter.ToString` |
23+
| **Category** | [Performance](performance-warnings.md) |
24+
| **Fix is breaking or non-breaking** | Non-breaking |
25+
| **Enabled by default in .NET 9** | As suggestion |
2626

2727
## Cause
2828

docs/fundamentals/code-analysis/quality-rules/ca2002.md

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,21 +35,13 @@ An object is said to have a weak identity when it can be directly accessed acros
3535
The following types have a weak identity and are flagged by the rule:
3636

3737
- <xref:System.String>
38-
3938
- Arrays of value types, including [integral types](../../../csharp/language-reference/builtin-types/integral-numeric-types.md), [floating-point types](../../../csharp/language-reference/builtin-types/floating-point-numeric-types.md), and <xref:System.Boolean>.
40-
4139
- <xref:System.MarshalByRefObject>
42-
4340
- <xref:System.ExecutionEngineException>
44-
4541
- <xref:System.OutOfMemoryException>
46-
4742
- <xref:System.StackOverflowException>
48-
4943
- <xref:System.Reflection.MemberInfo>
50-
5144
- <xref:System.Reflection.ParameterInfo>
52-
5345
- <xref:System.Threading.Thread>
5446

5547
- [this](../../../csharp/language-reference/keywords/this.md) or [Me](../../../visual-basic/programming-guide/program-structure/me-my-mybase-and-myclass.md) object
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
---
2+
title: "CA2022: Avoid inexact read with Stream.Read"
3+
description: "Learn about code analysis rule CA2022 - Avoid inexact read with Stream.Read"
4+
ms.date: 10/26/2024
5+
f1_keywords:
6+
- CA2022
7+
helpviewer_keywords:
8+
- CA2022
9+
dev_langs:
10+
- CSharp
11+
- VB
12+
---
13+
# CA2022: Avoid inexact read with Stream.Read
14+
15+
| Property | Value |
16+
|-------------------------------------|----------------------------------------|
17+
| **Rule ID** | CA2022 |
18+
| **Title** | Avoid inexact read with Stream.Read |
19+
| **Category** | [Reliability](reliability-warnings.md) |
20+
| **Fix is breaking or non-breaking** | Non-breaking |
21+
| **Enabled by default in .NET 9** | As warning |
22+
23+
## Cause
24+
25+
A call to <xref:System.IO.Stream.Read*?displayProperty=nameWithType> or <xref:System.IO.Stream.ReadAsync*?displayProperty=nameWithType> is made and the return value isn't checked.
26+
27+
## Rule description
28+
29+
<xref:System.IO.Stream.Read*?displayProperty=nameWithType> and <xref:System.IO.Stream.ReadAsync*?displayProperty=nameWithType> might return fewer bytes than requested, resulting in unreliable code if the return value isn't checked.
30+
31+
## How to fix violations
32+
33+
To fix a violation, either check the return value (which is the total number of bytes read into the buffer) or call <xref:System.IO.Stream.ReadExactly*?displayProperty=nameWithType> or <xref:System.IO.Stream.ReadExactlyAsync*?displayProperty=nameWithType> instead.
34+
35+
## Example
36+
37+
The following code snippet shows a violation of CA2022 and the fix for the violation.
38+
39+
:::code language="csharp" source="snippets/csharp/all-rules/ca2022.cs" id="1":::
40+
:::code language="csharp" source="snippets/vb/all-rules/ca2022.vb" id="1":::
41+
42+
## When to suppress warnings
43+
44+
You shouldn't suppress warnings from this rule, as your app might hang if you don't fix the violations.
45+
46+
## See also
47+
48+
- [Partial and zero-byte reads in DeflateStream, GZipStream, and CryptoStream](../../../core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams.md)

docs/fundamentals/code-analysis/quality-rules/ca2264.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ When a value that's known to never be null is passed to `ArgumentNullException.T
2626

2727
## Rule description
2828

29-
`ArgumentNullException.ThrowIfNull` throws when the passed argument is `null`. Certain constructs like non-nullable structs (except for <xref:System.Nullable%601>), 'nameof()' expressions and 'new' expressions are known to never be null, so `ArgumentNullException.ThrowIfNull` will never throw.
29+
`ArgumentNullException.ThrowIfNull` throws when the passed argument is `null`. Certain constructs like non-nullable structs (except for <xref:System.Nullable%601>), 'nameof()' expressions, and 'new' expressions are known to never be null, so `ArgumentNullException.ThrowIfNull` will never throw.
3030

3131
In the case of a struct, since `ArgumentNullException.ThrowIfNull` accepts an `object?`, the struct is boxed, which causes an additional performance penalty.
3232

docs/fundamentals/code-analysis/quality-rules/index.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ The following table lists code quality analysis rules.
1313

1414
> [!div class="mx-tdCol2BreakAll"]
1515
> | Rule ID and warning | Description |
16-
> | - | - |
16+
> | ------------------- | ----------- |
1717
> | [CA1000: Do not declare static members on generic types](ca1000.md) | When a static member of a generic type is called, the type argument must be specified for the type. When a generic instance member that does not support inference is called, the type argument must be specified for the member. In these two cases, the syntax for specifying the type argument is different and easily confused. |
1818
> | [CA1001: Types that own disposable fields should be disposable](ca1001.md) | A class declares and implements an instance field that is a System.IDisposable type, and the class does not implement IDisposable. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface. |
1919
> | [CA1002: Do not expose generic lists](ca1002.md) | System.Collections.Generic.List<(Of \<(T>)>) is a generic collection that is designed for performance, not inheritance. Therefore, List does not contain any virtual members. The generic collections that are designed for inheritance should be exposed instead. |
@@ -187,6 +187,7 @@ The following table lists code quality analysis rules.
187187
> | [CA2019: `ThreadStatic` fields should not use inline initialization](ca2019.md) | A field that's annotated with <xref:System.ThreadStaticAttribute> is initialized inline or explicitly in a `static` (`Shared` in Visual Basic) constructor. |
188188
> | [CA2020: Prevent behavioral change caused by built-in operators of IntPtr/UIntPtr](ca2020.md) | Some built-in operators added in .NET 7 behave differently than the user-defined operators in .NET 6 and earlier versions. Some operators that used to throw in unchecked context while overflowing don't throw anymore unless wrapped within checked context. Some operators that previously didn't throw in checked context now throw unless wrapped within unchecked context. |
189189
> | [CA2021: Don't call Enumerable.Cast\<T> or Enumerable.OfType\<T> with incompatible types](ca2021.md) | A call to <xref:System.Linq.Enumerable.Cast%60%601(System.Collections.IEnumerable)?displayProperty=nameWithType> or <xref:System.Linq.Enumerable.OfType%60%601(System.Collections.IEnumerable)?displayProperty=nameWithType> specifies a type parameter that's incompatible with the type of the input collection. |
190+
> | [CA2022: Avoid inexact read with Stream.Read](ca2022.md) | A call to `Stream.Read` might return fewer bytes than requested, resulting in unreliable code if the return value isn't checked. |
190191
> | [CA2100: Review SQL queries for security vulnerabilities](ca2100.md) | A method sets the System.Data.IDbCommand.CommandText property by using a string that is built from a string argument to the method. This rule assumes that the string argument contains user input. A SQL command string that is built from user input is vulnerable to SQL injection attacks. |
191192
> | [CA2101: Specify marshalling for P/Invoke string arguments](ca2101.md) | A platform invoke member allows partially trusted callers, has a string parameter, and does not explicitly marshal the string. This can cause a potential security vulnerability. |
192193
> | [CA2109: Review visible event handlers](ca2109.md) | A public or protected event-handling method was detected. Event-handling methods should not be exposed unless absolutely necessary. |

0 commit comments

Comments
 (0)