84 lines
2.5 KiB
Plaintext
84 lines
2.5 KiB
Plaintext
== Why is this an issue?
|
|
|
|
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sum[Enumerable.Sum()] always executes addition in a `checked` context, so an https://learn.microsoft.com/en-us/dotnet/api/system.overflowexception[OverflowException] will be thrown if the value exceeds `MaxValue`, even if an `unchecked` context was specified. Therefore, using this method inside an `unchecked` context will only make the code more confusing, since the behavior will still be `checked`.
|
|
|
|
This rule raises an issue when an `unchecked` context is specified for a `Sum` on integer types.
|
|
|
|
=== Exceptions
|
|
|
|
When the `Sum` call is inside a https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/exceptions/[try-catch block], no issues are reported, since the exception is properly handled.
|
|
|
|
[source,csharp]
|
|
----
|
|
void Add(List<int> list)
|
|
{
|
|
unchecked
|
|
{
|
|
try
|
|
{
|
|
int total = list.Sum();
|
|
}
|
|
catch (System.OverflowException e)
|
|
{
|
|
// Exception handling
|
|
}
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
== How to fix it
|
|
|
|
Remove the `unchecked` operator/statement, and optionally add some exception handling for the `OverflowException`.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,csharp,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
void Add(List<int> list)
|
|
{
|
|
int total1 = unchecked(list.Sum()); // Noncompliant
|
|
|
|
unchecked
|
|
{
|
|
int total2 = list.Sum(); // Noncompliant
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
==== Compliant solution
|
|
|
|
[source,csharp,diff-id=1,diff-type=compliant]
|
|
----
|
|
void Add(List<int> list)
|
|
{
|
|
int total1 = list.Sum();
|
|
|
|
try
|
|
{
|
|
int total2 = list.Sum();
|
|
}
|
|
catch (System.OverflowException e)
|
|
{
|
|
// Exception handling
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sum[`Enumerable.Sum` Method]
|
|
* https://github.com/microsoft/referencesource/blob/51cf7850defa8a17d815b4700b67116e3fa283c2/System.Core/System/Linq/Enumerable.cs#L1408-L1415[`Enumerable.Sum` implementation]
|
|
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/checked-and-unchecked[`checked` and `unchecked` statements]
|
|
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#12819-the-checked-and-unchecked-operators[`checked` and `unchecked` operators]
|
|
* https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/exceptions/[Exceptions and Exception Handling]
|
|
* https://learn.microsoft.com/en-us/dotnet/api/system.overflowexception[`OverflowException` Class]
|
|
* https://en.wikipedia.org/wiki/Integer_overflow[Integer overflow]
|
|
|
|
include::../rspecator.adoc[]
|