rspec/rules/S2291/csharp/rule.adoc

100 lines
2.0 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
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.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
void Add(List<int> list)
{
int d = unchecked(list.Sum()); // Noncompliant
unchecked
{
int e = list.Sum(); // Noncompliant
}
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
void Add(List<int> list)
{
int d = list.Sum();
try
{
int e = list.Sum();
}
catch (System.OverflowException e)
{
// exception handling...
}
}
----
=== Exceptions
2021-04-28 16:49:39 +02:00
When the ``++Sum()++`` call is inside a ``++try-catch++`` block, no issues are reported.
[source,csharp]
2021-04-28 16:49:39 +02:00
----
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)
=== Message
Refactor this code to handle "OverflowException".
'''
== Comments And Links
(visible only on this page)
=== on 13 Apr 2015, 10:44:27 Freddy Mallet wrote:
@Tamas, according to you, does this rule makes sense ? Thanks
=== on 29 Jun 2015, 14:58:19 Tamas Vajk wrote:
\[~ann.campbell.2] I've modified the description to be more specific. Also, I've changed the examples to use ``++List<int>++`` because for ``++double++``s it won't throw the ``++OverflowException++``.
\[~freddy.mallet] Yes, the rule makes sense.
=== on 30 Jun 2015, 14:45:28 Ann Campbell wrote:
Double-check my edits please [~tamas.vajk]
=== on 6 Jul 2015, 09:33:41 Tamas Vajk wrote:
\[~ann.campbell.2] Looks good.
endif::env-github,rspecator-view[]