rspec/rules/S2328/csharp/rule.adoc

69 lines
1.6 KiB
Plaintext
Raw Normal View History

== 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.
2021-04-28 16:49:39 +02:00
=== Exceptions
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.
2021-04-28 16:49:39 +02:00
== How to fix it
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
public class Person
2021-04-28 16:49:39 +02:00
{
public int age;
public string name;
public override int GetHashCode()
2021-04-28 16:49:39 +02:00
{
int hash = 12;
hash += this.age.GetHashCode(); // Noncompliant
hash += this.name.GetHashCode(); // Noncompliant
return hash;
}
----
==== Compliant solution
2021-04-28 16:49:39 +02:00
[source,csharp,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
public class Person
2021-04-28 16:49:39 +02:00
{
public readonly DateTime birthday;
public string name;
public override int GetHashCode()
2021-04-28 16:49:39 +02:00
{
int hash = 12;
hash += this.birthday.GetHashCode();
return hash;
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== 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".
endif::env-github,rspecator-view[]