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 424461
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T19:16:56+00:00 2026-05-12T19:16:56+00:00

I would like to be able to compare two classes derived from the same

  • 0

I would like to be able to compare two classes derived from the same abstract class in C#. The following code illustrates my problem.

I now I could fix the code by making BaseClass non abstract and then return a new BaseClass object in ToBassClass(). But isn’t there a more elegant and efficient solution?

abstract class BaseClass
{
   BaseClass(int x)
   {
       X = x;
   }

   int X { get; private set; }

   // It is probably not necessary to override Equals for such a simple class,
   // but I've done it to illustrate my point.
   override Equals(object other)
   {
       if (!other is BaseClass)
       {
           return false;
       }

       BaseClass otherBaseClass = (BaseClass)other;

       return (otherBaseClass.X == this.X);
   }

   BaseClass ToBaseClass()
   {
       // The explicit is only included for clarity.
       return (BaseClass)this;
   }
}

class ClassA : BaseClass
{
   ClassA(int x, int y)
       : base (x)
   {
       Y = y;
   }

   int Y { get; private set; }
}

class ClassB : BaseClass
{
   ClassB(int x, int z)
       : base (x)
   {
       Z = z;
   }

   int Z { get; private set; }
}

var a = new A(1, 2);
var b = new B(1, 3);

// This fails because despite the call to ToBaseClass(), a and b are treated
// as ClassA and ClassB classes so the overridden Equals() is never called.
Assert.AreEqual(a.ToBaseClass(), b.ToBaseClass());
  • 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-05-12T19:16:56+00:00Added an answer on May 12, 2026 at 7:16 pm

    It depends on where exactly you want to test for equality. Clearly ClassA and ClassB instances will never be “equal” in the real sense of that word, so overriding Equals to behave like this might actually cause some weird bugs in your code.

    But if you want to compare them based on a specific criteria, then you can implement a specific IEqualityComparer (or several comparers) which suites your needs.

    So, in this case you would have:

    /// <Summary>
    /// Compares two classes based only on the value of their X property.
    /// </Summary>
    public class ComparerByX : IEqualityComparer<BaseClass>
    {
         #region IEqualityComparer<BaseClass> Members
    
         public bool Equals(BaseClass a, BaseClass b)
         {
             return (a.X == b.X);
         }
    
         public int GetHashCode(BaseClass obj)
         {
             return obj.X.GetHashCode();
         }
    
         #endregion
    
    }
    

    [Edit] Regarding comment:

    Note that this doesn’t have anything with overriding the Equals method.

    But you will be able to check for equality like this:

    IEqualityComparer<BaseClass> comparer = new ComparerByX();
    Assert.True(comparer.Equals(a, b));
    

    This may not seem like a great thing at first, but it gives you several advantages:

    a) You can have as many IEqualityComparer<T> implementations as you want. Depending on the case, it may turn up that you Equals override is not so great after all. Then you risk breaking all of your code depending on this.

    b) There are actually many classes which use IEqualityComparer<T> to compare items.

    For example, you might want to use the BaseClass as a key in a dictionary. In that case, you would use the Dictionary<Key,Value> constructor overload which accepts an IEqualityComparer<T>:

    Dictionary<BaseClass, SomeOtherClass> dictionary 
        = new Dictionary<BaseClass, SomeOtherClass>(new ComparerByX());
    

    This way, dictionary will use the custom ComparerByX during key lookup.

    Also, for example, if you are using LINQ, you can check the Distinct() method example. It also supports an overload which returns distinct values, but compared using the specified custom IEqualityComparer.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to compare two different sets of data on the same imshow
I would like to be able to compare the asm generated by visual studio
I would like to compare two lists (two rows of a data frame) and
I would like to compare two collections (in C#), but I'm not sure of
I would like to be able to compare, on application start, the running version
Would like to be able to set colors of headings and such, different font
I would like to be able to output the name of a variable, along
I would like to be able to print in the logs a message for
I would like to be able to show a personal message to abusers of
I would like to be able to create a variable that holds an instance

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.