1

Lets say I have the following class

public class Test
{
    public int prop1 { get;set; }
    public string prop2 { get;set; }
    public Type prop3 { get;set; }
}

If I have two instances of this class, what is a fast approach to comparing the objects but at the same time allowing me to check if a property is something else assuming it did not match the other objects property. Currently I am just doing a ton of if statements but this feels like a bad way of doing things.

An example of the functionality I want; If first instance prop1 did not match prop1 of second instance I can still check if prop1 from first instance is 10 or something.

Yes this example is very crude but the actual code is HUGE so no way I can post it here.

Thanks

EDIT

I Should note, I can't edit the class Test as I do not own it.

Landin Martens
  • 3,283
  • 12
  • 43
  • 61

2 Answers2

2

You can build your own Comparer (untested code)

public class TestComparer : IEqualityComparer<Test>
{
    public bool Equals( Test x, Test y )
    {
        if( ReferenceEquals( x, y ) )
            return true;

        if( ReferenceEquals( x, null ) || ReferenceEquals( y, null ) )
            return false;

        return x.prop1 == y.prop1 &&
               x.prop2 == y.prop2 &&
               x.prop3 == y.prop3;
    }

    public int GetHashCode( Test entry )
    {
        unchecked
        {
            int result = 37;

            result *= 397;
            result += entry.prop1.ToString( ).GetHashCode( );
            result *= 397;
            result += entry.prop2.GetHashCode( );
            result *= 397;
            result += entry.prop3.ToString( ).GetHashCode( );

            return result;
        }
    }
}

and then simply call:

Test a = new Test( );
Test b = new Test( );

var equal = new TestComparer( ).Equals( a, b );
Viper
  • 2,216
  • 1
  • 21
  • 41
0

Without being able to edit the class itself I'd say your options are fairly limited. You could always abstract out the code somewhere and just make a compare function that takes 2 objects and returns a bool.

public static bool Compare(Test test1, Test test2)
{
     //May need to add some null checks
     return (test1.prop1 == test2.prop1) 
       && (test1.prop2 == test2.prop2); 
     //...etc
}

Unless you actually do have the same object, and not just 2 objects that happen to have all the same property values in which case you can simply do...

if (test1 == test2)

but I'm guessing from your question this is not the case.

Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138