---
lang: ja-jp
breaks: true
---
# C# objectインスタンスの識別に `GetHashCode()` はどの程度利用可能なのか? 2021-11-10
object型の内部では、`RuntimeHelpers.GetHashCode(this)`を使用してハッシュコードが産出されている。
当然、`Tuple`等の `IStructuralEquatable`や`IComparable`を継承しているクラスは、データの中身が同じであれば同じハッシュコードとなる為、これらを継承していないクラスの場合にハッシュコードが重複する確率がどのくらいあるのかを調べる。
検証したクラス
```csharp=
public class TestClass001
{
private string m_name;
private int m_number;
public TestClass001(
string name,
int number
)
: base()
{
this.m_name = name;
this.m_number = number;
}
public string Name { get { return this.m_name; } protected set { this.m_name = value; } }
public int Number { get { return this.m_number; } protected set { this.m_number = value; } }
public override string ToString()
{
return new StringBuilder()
.Append("name:").Append(m_name).AppendLine("、")
.Append("number:").Append(m_number).AppendLine("、")
.ToString();
}
}
```
| 項番 | インスタンス件数 | 重複件数 | 重複率 |
| ----:| ----------------:| --------:| ------:|
| 1 | 10,000 | 1 | 0.01 % |
| 2 | 100,000 | 76 | 0.07 % |
| 3 | 1,000,000 | 7,425 | 0.74 % |
| 4 | 10,000,000 | 667,354 | 6.67 % |
| 5 | 100,000,000 | 29,581,671| 29.58 % |
| 6 | 1,000,000,000 | 67,108,797 | 6.71 % |
:::info
項番5の重複率が以上に高いので、後日再計測する。
→再計測したが、同様の結果だった。
:::
想像通りの結果となった。
インスタンスの識別に`GetHashCode()`を使用する場合は、最終的に`Object.ReferenceEquals`を使用して同じかどうかを確認する必要がある。
また、`ObjectIDGenerator`クラスも有用。
> https://docs.microsoft.com/ja-jp/dotnet/api/system.runtime.serialization.objectidgenerator?view=net-5.0
###### tags: `C#` `object` `GetHashCode()` `重複`