Donotalo
Donotalo

Reputation: 13025

Equality testing of variables

I'm working on a project written in C# and .NET 4.0.

There is a function which compares certain properties of two objects. Both objects are of same type. Consider the following class:

class A
{
    public UInt32 Prop1 {get; set;}
    public byte Prop2 {get; set;}
    public string Prop3 {get; set;}
    public int[] Prop4 {get; set;}
}

In my comparison function, I'm iterating through each properties using reflection, and getting values of the properties:

var value1 = t1.GetType().GetProperty(cp.ToString()).GetValue(t1, null);
var value2 = t2.GetType().GetProperty(cp.ToString()).GetValue(t2, null);

where both t1 and t2 are of type A and cp is an enum of properties:

enum Properties
{ Prop1, Prop2, Prop3, Prop4 }

Next I'm doing equality test:

if (!value1.Equals(value2))
{
    // Handle differences
}

When testing for Prop4, which returns an array, Equals() always returns false even though the array size and content are same.

What's the easiest way to detect that the return type is enumerable and then perform equality testing for individual elements of the enumerable?

Upvotes: 0

Views: 66

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

You can use Type.IsAssignableFrom() method:

if(typeof(IEnumerable).IsAssignableFrom(t2.GetType()))
{

}

I'm not 100% sure what you're trying to achieve using your technique, but getting properties values using reflection with additional enum seems like poor design decision.

Update

If you own the classes code you should just implement IEquatable<T> and compare all the properties there.

class A : IEquatable<A>
{
    public UInt32 Prop1 { get; set; }
    public byte Prop2 { get; set; }
    public string Prop3 { get; set; }
    public int[] Prop4 { get; set; }

    public bool Equals(A other)
    {
        return other != null
            && Prop1 == other.Prop1
            && Prop2 == other.Prop2
            && Prop3 == other.Prop3
            && System.Linq.Enumerable.SequenceEqual(Prop4, other.Prop4);
    }
}

Upvotes: 3

Related Questions