Consider a struct which does not contain any reference fields (only basic types and other structs).
Consider this struct will be used in collections and I want it to behave like a value type (ie int).
Particularly if your value type contains fields that are reference types, you should override the Equals(Object) method. This can improve performance and enable you to more closely represent the meaning of equality for the type.
It is best to implement IEquatable to avoid boxing (default Equals accepts an object type, so your struct will have to undergo boxing to fit that type). Collections (Arrays, Dictionaries, etc...) will usually check if their members implement IEquatable, and will use IEquatable.Equals, so it's best to implement it. It is also recommended to implement the default Equals (from System.Object) and direct to to the IEquatable.Equals implementation. Example:
struct MyStruct : IEquatable<MyStruct>
{
public int A { get; set; }
public int B { get; set; }
public bool Equals(MyStruct other)
{
return A == other.A && B == other.B;
}
public override bool Equals(object obj)
{
if (!(obj is MyStruct)) return false;
return ((MyStruct)obj).Equals(this);
}
public override int GetHashCode()
{
return (A, B).GetHashCode();
}
}
I also provided an example of how to implement GetHashCode, best way is to use the implementation of Tuple.
Again, implementing == and != is up to you The standard library (System, System.Collections, etc...) uses System.Equals or IEquatable.Equals to do comparison, and you should too.
So no, implementing == and != is not necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With