Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8245023
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T22:03:20+00:00 2026-06-07T22:03:20+00:00

Ok, I have a class within which I want to over-ride the equality operator,

  • 0

Ok, I have a class within which I want to over-ride the equality operator, so I have the following code:

/// <summary>
/// Over-ride of the equality operator.
/// </summary>
/// <param name="credential1">The left hand object to test for equality.</param>
/// <param name="credential2">The right hand object to test for equality.</param>
/// <returns>True if the objects are equal.</returns>
public static bool operator ==(KnownServerCredential credential1, KnownServerCredential credential2)
{
    // ok check if either is null
    bool cell1Null = Equals(null, credential1);
    bool cell2Null = Equals(null, credential2);

    // if both are, then it's true
    if (cell1Null && cell2Null)
    {
        return true;
    }

    // if only one is, then how can they be the same?
    if (cell1Null || cell2Null)
    {
        return false;
    }

    // neither are - so we can now go to full on equality
    return credential1.IsEqualTo(credential2);
}

This works fine, and I’m happy with it. However, static analysis tools (both Resharper and the VS2010 Code Analysis) swear blind that the last line could throw a null reference exception, because of the way I am checking for null in the top two lines. If I change the top two lines from Equals(null, credentialX) to credentialX == null then the static analysis tools are happy, but it creates a stack overflow exception, because I am then recursively calling the equality over-ride. I can have the best of both worlds by using (object)credentialX == null, but that doesn’t seem like the cleanest way of doing it.

So the simple question is, am I missing something, or is cast-and-compare the best way to achieve what I’m looking for?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T22:03:22+00:00Added an answer on June 7, 2026 at 10:03 pm

    There are two ways of checking whether a pair of objects are equal: reference equality and structural/value equality. Reference equality is the default for all reference types (classes), and structural equality is the default for all value types (but the default implementation is not optimal). Use the following guide to implement structural equality for both reference types and value types.

    Equality

    The equality check should follow these rules:

    • An object is equal to itself (Identity)
    • Comparing x to y returns the same truth as comparing y to x. (Symmetry)
    • If x is equal to y and y is equal to z, then x must be equal to z. (Transitivity)
    • An object is never equal to null.
    • null is equal to null.
    • No exceptions should be thrown.

    Let your class or struct implement the IEquatable<T> interface for custom equality checking,
    then implement the IEquatable<T>.Equals(T) and Object.Equals() methods.

    Equality for reference types (classes)

    For reference types, implement the IEquatable<T>.Equals(T) method like this:

    public bool Equals(MyType other)
    {
        if (Object.ReferenceEquals(other, null) ||      // When 'other' is null
            other.GetType() != this.GetType())          // or of a different type
            return false;                               // they are not equal.
        return this.field1 == other.field1
            && this.field2 == other.field2;
    }
    

    Then override Object.Equals() like this:

    public override bool Equals(object obj)
    {
        return Equals(obj as MyType);
    }
    

    Equality for value types (structs)

    Since value types cannot be null, implement the IEquatable<T>.Equals(T) method like this:

    public bool Equals(MyType other)
    {
        return this.field == other.field
            && this.field2 == other.field2;
    }
    

    Then override Object.Equals() like this:

    public override bool Equals(object obj)
    {
        if (!(obj is MyType))
            return false;
        return Equals((MyType)obj);
    }
    

    Equality operators

    For both reference and value types, you may want to override the default equality and inequality operators. Based on this post by Jon Skeet the equality and inequality operators can be implemented like this:

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

    Note that when left and/or right is null, Object.Equals(object, object) does not call the Object.Equals(object) override (and therefore not the IEquatable<T>.Equals(T) method).

    Hash code

    Sometimes the hash code of an object is important, for example when the object might be put in a dictionary or hash table. In general, when you override the Equals() method, override the GetHashCode() method. The hash code should follow these rules:

    • The hash code should never change, not even after modifying some fields in the object.
    • The hash code must be equal, for objects that are considered to be equal.
    • The hash code may be anything (including equal) for objects that are considered to be unequal.
    • The hash codes should be randomly distributed.
    • The hash code function must never throw an exception and must always return.
    • The hash code should be calculated very fast.

    So to implement Object.GetHashCode() for a class or struct that uses structural equality, choose some fields from your object that are immutable and mark them readonly. Use only those fields to calculate the hash code. Override the Object.GetHashCode() method and implement it like this:

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;
            // Don't forget to check for null values.
            hash = hash * 29 + field1.GetHashCode();
            hash = hash * 29 + field2.GetHashCode();
            // ...
            return hash;
        }
    }
    

    Or, if you have only one immutable field, you may consider just using:

    public override int GetHashCode()
    {
        // Don't forget to check for null values.
        return field1.GetHashCode();
    }
    

    If you have no immutable fields, return a constant hash code. For example, the hash code of the type itself.

    public override int GetHashCode()
    {
        return GetType().GetHashCode();
    }
    

    Structural equality for collections

    Collections should not be compared using the default Equals() method. Instead, the default equality for collections should be reference equality. To also implement structural equality, implement the IStructuralEquatable interface. For example:

    bool IStructuralEquatable.Equals(object obj, IEqualityComparer comparer)
    {
        var other = obj as MyType;
        if (other == null)
            return false;
        return ((IStructuralEquatable)this.innerArray)
            .Equals(other.innerArray, comparer);
    }
    
    int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
    {
        return ((IStructuralEquatable)this.innerArray).GetHashCode(comparer);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Say I have a class which represents a person, a variable within that class
I have a class called Metadata, which is declared within the namespace A::B::C ,
I have a background worker which calls a function within a separate class. This
I have subclassed a UITableViewCell and within this class I want to get it's
I have a class which uses a HashSet and I want the class implement
Is it possible to have a single class reside within two name-spaces and how
I have a quite simple question: I want to have a Java Class, which
I have a class which extends ListActivity within I have all methods for managing
I have a class which contains a textfield and within that class an inner
If I have a class called myclass does having static methods within the class

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.