Overriding Equals method in Structs

前端 未结 6 554
-上瘾入骨i
-上瘾入骨i 2020-12-28 11:24

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

6条回答
  •  伪装坚强ぢ
    2020-12-28 11:58

    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;
    }
    

提交回复
热议问题