Comparing objects using reflection

G

GeezerButler

I am comparing 2 objects with a lot of public properties(more than 100
which are all ValueType or string)
So i decided to write a reflection based solution for that.
My code looks something like this:

public bool AreEqual(Mytype a, Mytype b)
{
PropertyInfo[] props =
typeof(MyType).GetProperties(PUBLIC_PROP_BINDINGS);
foreach (PropertyInfo prop in props)
{
object objA = prop.GetValue(a, null);
object objB = prop.GetValue(b, null);
switch (prop.PropertyType.Name)
{
case "Int32":
if ((int)objA != (int)objB) return false; break;
case "String":
if ((string)objA != (string)objB) return false; break;
case "DateTime":
if ((DateTime)objA != (DateTime)objB) return false; break;
}
}
return true;
}

This reduces the code somewhat but can i somehow avoid using the large
amount of case "typeName" statements.
I am having to do this because objA != objB is always true unless the
objects are cast to their correct type.
 
J

Jon Skeet [C# MVP]

GeezerButler said:
I am comparing 2 objects with a lot of public properties(more than 100
which are all ValueType or string)

I am having to do this because objA != objB is always true unless the
objects are cast to their correct type.

Yes, because of overloading being a compile-time thing. Have you tried
calling Equals instead, however, which would rely on overriding instead
of overloading?
 
G

GeezerButler

Yes, because of overloading being a compile-time thing. Have you tried
calling Equals instead, however, which would rely on overriding instead
of overloading?

Hi Jon,
Thanks. Your method works perfectly fine.
I had come up with objA.ToString() != objB.ToString() workaround but
that needed more checks for null and i was not too sure about it
anyhow.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top