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

  • Home
  • SEARCH
  • 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 198069
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T16:54:24+00:00 2026-05-11T16:54:24+00:00

This is what I’ve come up with as a method on a class inherited

  • 0

This is what I’ve come up with as a method on a class inherited by many of my other classes. The idea is that it allows the simple comparison between properties of Objects of the same Type.

Now, this does work – but in the interest of improving the quality of my code I thought I’d throw it out for scrutiny. How can it be better/more efficient/etc.?

/// <summary>
/// Compare property values (as strings)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool PropertiesEqual(object comparisonObject)
{

    Type sourceType = this.GetType();
    Type destinationType = comparisonObject.GetType();

    if (sourceType == destinationType)
    {
        PropertyInfo[] sourceProperties = sourceType.GetProperties();
        foreach (PropertyInfo pi in sourceProperties)
        {
            if ((sourceType.GetProperty(pi.Name).GetValue(this, null) == null && destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null) == null))
            {
                // if both are null, don't try to compare  (throws exception)
            }
            else if (!(sourceType.GetProperty(pi.Name).GetValue(this, null).ToString() == destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null).ToString()))
            {
                // only need one property to be different to fail Equals.
                return false;
            }
        }
    }
    else
    {
        throw new ArgumentException("Comparison object must be of the same type.","comparisonObject");
    }

    return true;
}
  • 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-11T16:54:25+00:00Added an answer on May 11, 2026 at 4:54 pm

    I was looking for a snippet of code that would do something similar to help with writing unit test. Here is what I ended up using.

    public static bool PublicInstancePropertiesEqual<T>(T self, T to, params string[] ignore) where T : class 
      {
         if (self != null && to != null)
         {
            Type type = typeof(T);
            List<string> ignoreList = new List<string>(ignore);
            foreach (System.Reflection.PropertyInfo pi in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
            {
               if (!ignoreList.Contains(pi.Name))
               {
                  object selfValue = type.GetProperty(pi.Name).GetValue(self, null);
                  object toValue = type.GetProperty(pi.Name).GetValue(to, null);
    
                  if (selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue)))
                  {
                     return false;
                  }
               }
            }
            return true;
         }
         return self == to;
      }
    

    EDIT:

    Same code as above but uses LINQ and Extension methods :

    public static bool PublicInstancePropertiesEqual<T>(this T self, T to, params string[] ignore) where T : class
    {
        if (self != null && to != null)
        {
            var type = typeof(T);
            var ignoreList = new List<string>(ignore);
            var unequalProperties =
                from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                where !ignoreList.Contains(pi.Name) && pi.GetUnderlyingType().IsSimpleType() && pi.GetIndexParameters().Length == 0
                let selfValue = type.GetProperty(pi.Name).GetValue(self, null)
                let toValue = type.GetProperty(pi.Name).GetValue(to, null)
                where selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue))
                select selfValue;
            return !unequalProperties.Any();
        }
        return self == to;
    }
    
    public static class TypeExtensions
       {
          /// <summary>
          /// Determine whether a type is simple (String, Decimal, DateTime, etc) 
          /// or complex (i.e. custom class with public properties and methods).
          /// </summary>
          /// <see cref="http://stackoverflow.com/questions/2442534/how-to-test-if-type-is-primitive"/>
          public static bool IsSimpleType(
             this Type type)
          {
             return
                type.IsValueType ||
                type.IsPrimitive ||
                new[]
                {
                   typeof(String),
                   typeof(Decimal),
                   typeof(DateTime),
                   typeof(DateTimeOffset),
                   typeof(TimeSpan),
                   typeof(Guid)
                }.Contains(type) ||
                (Convert.GetTypeCode(type) != TypeCode.Object);
          }
    
          public static Type GetUnderlyingType(this MemberInfo member)
          {
             switch (member.MemberType)
             {
                case MemberTypes.Event:
                   return ((EventInfo)member).EventHandlerType;
                case MemberTypes.Field:
                   return ((FieldInfo)member).FieldType;
                case MemberTypes.Method:
                   return ((MethodInfo)member).ReturnType;
                case MemberTypes.Property:
                   return ((PropertyInfo)member).PropertyType;
                default:
                   throw new ArgumentException
                   (
                      "Input MemberInfo must be if type EventInfo, FieldInfo, MethodInfo, or PropertyInfo"
                   );
             }
          }
       }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 91k
  • Answers 91k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The answer is a multi-byte character that is an bug… May 11, 2026 at 6:13 pm
  • Editorial Team
    Editorial Team added an answer You could use Select in the first list, use the… May 11, 2026 at 6:13 pm
  • Editorial Team
    Editorial Team added an answer Today Mono is quite mature in terms of performance and… May 11, 2026 at 6:13 pm

Related Questions

I am currently running into a problem where an element is coming back from
Is it possible to replace javascript w/ HTML if JavaScript is not enabled on
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
This is what I've got. It works. But, is there a simpler or better
This is what I've got. It works. But, is there a simpler or better

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.