Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Equals method in Structs

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 null, as structs are value types and can't be null. But now that I come to think of it, as equals signature is

public bool Equals(object obj) 

it seems there is nothing preventing the user of my struct to be trying to compare it with an arbitrary reference type.

My second point concerns the casting I (think I) have to make before I compare my private fields in my struct. How am I supposed to cast the object to my struct's type? C#'s as keyword seems only suitable for reference types.

like image 503
devoured elysium Avatar asked Mar 30 '10 03:03

devoured elysium


People also ask

Can you override equals method?

You can override the equals method on a record, if you want a behavior other than the default. But if you do override equals , be sure to override hashCode for consistent logic, as you would for a conventional Java class.

What is the reason for overriding equals () method?

We can override the equals method in our class to check whether two objects have same data or not.

Can we override the equals method for the string class?

The String class overrides the equals method it inherited from the Object class and implemented logic to compare the two String objects character by character. The reason the equals method in the Object class does reference equality is because it does not know how to do anything else.

Should I override equality and inequality operators?

In a class, if you overload the Equals method, you should overload the == and != operators, but it is not required.


1 Answers

struct MyStruct  {    public override bool Equals(object obj)     {        if (!(obj is MyStruct))           return false;         MyStruct mys = (MyStruct) obj;        // compare elements here     }  } 
like image 154
James Curran Avatar answered Sep 23 '22 03:09

James Curran