rspec/rules/S2291/csharp/rule.adoc

78 lines
1.3 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
``++Enumerable.Sum()++`` always executes addition in a ``++checked++`` context, so an ``++OverflowException++`` will be thrown if the value exceeds ``++MaxValue++`` even if an ``++unchecked++`` context was specified. Using an ``++unchecked++`` context anyway represents a misunderstanding of how ``++Sum++`` works.
This rule raises an issue when an ``++unchecked++`` context is specified for a ``++Sum++`` on integer types.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
void Add(List<int> list)
{
int d = unchecked(list.Sum()); // Noncompliant
unchecked
{
int e = list.Sum(); // Noncompliant
}
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
void Add(List<int> list)
{
int d = list.Sum();
try
{
int e = list.Sum();
}
catch (System.OverflowException e)
{
// exception handling...
}
}
----
2021-04-28 16:49:39 +02:00
== Exceptions
When the ``++Sum()++`` call is inside a ``++try-catch++`` block, no issues are reported.
----
void Add(List<int> list)
{
unchecked
{
try
{
int e = list.Sum();
}
catch (System.OverflowException e)
{
// exception handling...
}
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]