What is the best way to use C # struct as a dictionary key?

I have a C # structure that I use as a key in the standard dictionary collection. I wrote overrides for both GetHashCode and Equals, but I'm a little unhappy that Equals is provided with an object in the form of a box, and not a link to my structure type directly.

Is there anything I can do to optimize the use of the dictionary with my type of structure in order to avoid unnecessary boxing operations?

(This is not a premature optimization, but a completely appropriate optimization, thank you very much.)

+5
source share
2 answers

You can implement a general comparator:

public class MyStructComparer : IEqualityComparer<MyStruct> { public bool Equals(MyStruct x, MyStruct y) { // ... } public int GetHashCode(MyStruct obj) { // ... } } 

Then use this for the constructor of the word:

 var myStructDict = new Dictionary<MyStruct, string>(new MyStructComparer()); 

Another way is to implement IEquatable<MyStruct> in MyStruct , for example:

 public struct MyStruct: IEquatable<MyStruct> { public int Id; public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is MyStruct && Equals((MyStruct)obj); } public bool Equals(MyStruct other) { return this.Id == other.Id; } public override int GetHashCode() { return this.Id; } } 

Then the dictionary can be initialized by the default constructor:

 var myStructDict = new Dictionary<MyStruct, string>(); 
+7
source

You can also try executing the load statement. check the code below.

 struct MyStruct { public int id; public static bool operator ==(MyStruct s1, MyStruct s2) { if (s1.id == s2.id) return true; return false; } public static bool operator !=(MyStruct s1, MyStruct s2) { if (s1.id == s2.id) return false; return true; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is MyStruct && Equals((MyStruct)obj); } public bool Equals(MyStruct other) { return this.id == other.id; } public override int GetHashCode() { return this.id; } } 
0
source

Source: https://habr.com/ru/post/1271180/


All Articles