Do you know you can override the == operator ?

Yes you can!

In order to override equality in Value Types we should :

  • implement IEquatable
  • override object.Equals()
  • implement ==
  • implement !=
  • implement object.GetHashCode()
public struct FoodStruct : IEquatable<FoodStruct>
{
    private readonly string _name;

    private readonly FoodGroup _group;

    public FoodStruct(string name, FoodGroup group)
    {
        _name = name;
        _group = group;
    }

    public string Name
    {
        get
        {
            return _name;
        }
    }

    public FoodGroup Group
    {
        get
        {
            return _group;
        }
    }

    public override string ToString()
    {
        return _name;
    }

    public bool Equals(FoodStruct other)
    {
        return _name == other._name && _group == other._group;
    }

    public override bool Equals(object obj)
    {
        if (obj is FoodStruct)
        {
            return Equals((FoodStruct)obj);
        }

        return false;
    }

    public static bool operator ==(FoodStruct left, FoodStruct right)
    {
        return left.Equals(right);
    }

    public static bool operator !=(FoodStruct left, FoodStruct right)
    {
        return !left.Equals(right);
    }

    public override int GetHashCode()
    {
        return _name.GetHashCode() ^ _group.GetHashCode();
    }
}

Check Simon Robinson course on Pluralight about C# Equality and Comparisons

Advertisements
This entry was posted in c#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s