2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
``++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.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== 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
----
public class Person
{
public int age;
public string name;
public override int GetHashCode()
{
int hash = 12;
hash += this.age.GetHashCode(); // Noncompliant
hash += this.name.GetHashCode(); // Noncompliant
return hash;
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== 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
----
public class Person
{
public readonly DateTime birthday;
public string name;
public override int GetHashCode()
{
int hash = 12;
hash += this.birthday.GetHashCode();
return hash;
}
----
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Refactor 'GetHashCode' to not reference mutable fields.
=== Highlighting
* primary: method name
* secondary: uses of mutable fields
** message: Remove this use of "xxx" or make it "readonly".
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]