Class CompositeHashCode
Provides a way for types that override GetHashCode() to correctly generate a hash code from the actual status of an instance.
CompositeHashCode
must be used ONLY as a helper when implementing
- two instances having the same hash code are actually
interchangeable, i.e. they represent exactly the same object (for instance,
they should not coexist in a
SortedSet ); - GetHashCode() and
Equals(Object) are BOTH overridden, and the
Equals
override either calls to theIEquatable<T>.Equals (recommended) or performs exactly the same equality checks; - only "standard" equality checks are performed, i.e. by means of the
==
operator,IEquatable<T> interfaces, and the Equals(Object) method (for instance, this excludes case-insensitive and/or culture-dependent string comparisons); - the hash code is constructed (via
Using
calls) from the very same fields and / or properties that are checked for equality.
For hashing to work correctly, all fields and/or properties involved in hashing must either
be immutable, or at least not change while an object is referenced in a hashtable.
This does not refer just to System.Collections.Hashtable
; the .NET
Framework makes a fairly extensive use of hashing, for example in
Hashtable
or SortedSet
.
Inherited Members
Namespace: Swan
Syntax
public static class CompositeHashCode
Examples
The following code constitutes a minimal use case for CompositeHashCode
, as well
as a reference for standard IEquatable<T> implementation.
Notice that all relevant properties are immutable; this is not, as stated in the summary, an absolute requirement, but it surely helps and should be done every time it makes sense.
using System;
using Swan;
namespace Example
{
public class Person : IEquatable<Person>
{
public string Name { get; private set; }
public int Age { get; private set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
public override int GetHashCode() => CompositeHashCode.Using(Name, Age);
public override bool Equals(object obj) => obj is Person other && Equals(other);
public bool Equals(Person other)
=> other != null
&& other.Name == Name
&& other.Age == Age;
}
}
Methods
Using(Object[])
Computes a hash code, taking into consideration the values of the specified fields and/oror properties as part of an object's state. See the CompositeHashCode.
Declaration
public static int Using(params object[] fields)
Parameters
Type | Name | Description |
---|---|---|
Object[] | fields | The values of the fields and/or properties. |
Returns
Type | Description |
---|---|
Int32 | The computed has code. |