I\'ve looked for overriding guidelines for structs, but all I can find is for classes.
At first I thought I wouldn\'t have to check to see if the passed object was n
Thanks to pattern matching in C# 7.0 there is an easier way to accomplish the accepted answer:
struct MyStruct
{
public override bool Equals(object obj)
{
if (!(obj is MyStruct mys)) // type pattern here
return false;
return this.field1 == mys.field1 && this.field2 == mys.field2 // mys is already known here without explicit casting
}
}
You could also make it even shorter as an expression-bodied function:
struct MyStruct
{
public override bool Equals(object obj) =>
obj is MyStruct mys
&& mys.field1 == this.field1
&& mys.field2 == this.field2;
}