Skip to content

Commit

Permalink
Modify S2328: Exclude value types (#3670)
Browse files Browse the repository at this point in the history
  • Loading branch information
gregory-paidis-sonarsource authored Feb 21, 2024
1 parent b4774f0 commit f9b1bd8
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions rules/S2328/csharp/rule.adoc
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
== Why is this an issue?

``++GetHashCode++`` is used to file an object in a ``++Dictionary++`` or ``++Hashtable++``. If ``++GetHashCode++`` uses non-``++readonly++`` fields and those fields change after the object is stored, the object immediately becomes mis-filed in the ``++Hashtable++``. Any subsequent test to see if the object is in the ``++Hashtable++`` will return a false negative.
`GetHashCode` is used to file an object in a `Dictionary` or `Hashtable`. If `GetHashCode` uses non-`readonly` fields and those fields change after the object is stored, the object immediately becomes mis-filed in the `Hashtable`. Any subsequent test to see if the object is in the `Hashtable` will return a false negative.

=== Exceptions

=== Noncompliant code example
This rule does not raise if the type implementing `GetHashCode` is a value type, for example a `struct` or a `record struct`, since when a value type is stored in a `Dictionary` or `Hashtable`, a copy of the value is stored, not a reference to the value.

[source,csharp]
== How to fix it

=== Code examples

==== Noncompliant code example

[source,csharp,diff-id=1,diff-type=noncompliant]
----
public class Person
public class Person
{
public int age;
public string name;
public override int GetHashCode()
public override int GetHashCode()
{
int hash = 12;
hash += this.age.GetHashCode(); // Noncompliant
Expand All @@ -22,16 +29,16 @@ public class Person
----


=== Compliant solution
==== Compliant solution

[source,csharp]
[source,csharp,diff-id=1,diff-type=compliant]
----
public class Person
public class Person
{
public readonly DateTime birthday;
public string name;
public override int GetHashCode()
public override int GetHashCode()
{
int hash = 12;
hash += this.birthday.GetHashCode();
Expand Down

0 comments on commit f9b1bd8

Please sign in to comment.