473,765 Members | 2,224 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A Function That Compares the Properties of Two Objects

Hi There

I am learning about reflection so apologies if this post is vague ...

I am doing some unit testing and have written a function that accepts
two objects and tests to see if their properties are equal. It seems
to work OK except when a object has a property that is an array.

The GetValue method of the PropertyInfo class returns an object, and I
want to convert it to an array of objects. For some reason, this
fails:

object[] objectArray = (object[])myObject;

However if I know the type, then it works. For example:

SecurityRoles[] rolesArray = (SecurityRoles[])object;

The problem is that I don't know the type at design time ! I tried to
do this:

propInfo.Proper tyType[] objectArray =
(propInfo.Prope rtyType[])myObject;

But it did not compile (ps ... propInfo is an instance of the
PropertyInfo class).

The code listing for my function is below. I would really appreciate
any guidance!

Thanks
Bill

using System;
using System.Reflecti on;

namespace ServerTest
{
public static class ObjectComparer
{
/// <summary>
/// This function compares any two objects properties. It will
recursively search down through nested properties
/// WARNING - It only compares properties that are one of the
following string, char, short, int, long, bool, DateTime, Enum
/// *** IT IGNORES ANY PROPERTIES THAT ARE ARRAYS ***
/// </summary>
/// <param name="thisType" >The type of the two objects</param>
/// <param name="leftObjec t"></param>
/// <param name="rightObje ct"></param>
/// <returns>True to indicate that the objects are equal.
False otherwise</returns>
public static bool AreTheseObjectE qual(Type thisType, object
leftObject, object rightObject)
{
if (leftObject == null && rightObject == null)
return true;

if (leftObject == null || rightObject == null)
return false;

PropertyInfo[] fields = thisType.GetPro perties();

foreach (PropertyInfo propInfo in fields)
{
if (propInfo.Prope rtyType.IsArray )
{
//*************** *************** *************** *************** *************** ******
//Property is an array, need to iterate through the
elements and compare them

//*************** *************** *************** *************** *************** ******

//object lhs = propInfo.GetVal ue(leftObject, null);
//object rhs = propInfo.GetVal ue(rightObject,
null);

////This does not work
//object[] lhsArray = (object[])lhs;
//object[] rhsArray = (object[])rhs;

////If the above worked, I could then do this:
//if (lhsArray.Lengt h != rhsArray.Length )
// return false;
//else
//{
// for (int i = 0; i < lhsArray.Length ; i++)
// {
// if (false ==
AreTheseObjectE qual(propInfo.P ropertyType,
(object)lhsArra y[i],(object)rhsArr ay[i]))
// return false;
// }
//}

//BUT .... If I knew the type then this would
work:
//STE.Model.Secur ityRoles[] secRolesLHS =
(STE.Model.Secu rityRoles[])lhs;
//STE.Model.Secur ityRoles[] secRolesRHS =
(STE.Model.Secu rityRoles[])rhs;
//But I don't know the type at run time
}
else
{
object lhs = propInfo.GetVal ue(leftObject, null);
object rhs = propInfo.GetVal ue(rightObject, null);

if (propInfo.Prope rtyType.IsEnum)
{
if (lhs.ToString() != rhs.ToString())
return false;
}
else if (lhs is string)
{
if (false == rhs is string)
return false;
if ((string)lhs != (string)rhs)
return false;
}
else if (lhs is char)
{
if (false == rhs is char)
return false;
if ((char)lhs != (char)rhs)
return false;
}
else if (lhs is bool)
{
if (false == rhs is bool)
return false;
if ((bool)lhs != (bool)rhs)
return false;
}
else if (lhs is short)
{
if (false == rhs is short)
return false;
if ((long)lhs != (long)rhs)
return false;
}
else if (lhs is int)
{
if (false == rhs is int)
return false;
if ((int)lhs != (int)rhs)
return false;
}
else if (lhs is long)
{
if (false == rhs is long)
return false;
if ((long)lhs != (long)rhs)
return false;
}
else if (lhs is DateTime)
{
if (false == rhs is DateTime)
return false;
if ((DateTime)lhs != (DateTime)rhs)
return false;
}
else
{
PropertyInfo[] nestedFields =
propInfo.Proper tyType.GetPrope rties();
if (nestedFields.L ength > 0)
{
if (false ==
AreTheseObjectE qual(propInfo.P ropertyType,
propInfo.GetVal ue(leftObject, null), propInfo.GetVal ue(rightObject,
null)))
return false;
}
}
}
}
return true;
}
}
}

Nov 17 '05 #1
4 1741
Thats not so hard to do:

//...

PropertyInfo[] fields = thisType.GetPro perties();
foreach (PropertyInfo propInfo in fields) {

if (propInfo.Prope rtyType.IsArray ) {
object val = propInfo.GetVal ue(angel, null);

IEnumerator ie = ((System.Array) val).GetEnumera tor();
while(ie.MoveNe xt()) {
//Now we have the individual object in the array
Console.WriteLi ne(ie.Current.G etType().ToStri ng());
}
}

//...
}

Nov 17 '05 #2
Hi,
Ashura's post should solve your problem, I just want to remember you that if
a property has a reference type you are comparing references ( if both
instances refers to the very same instance, not two instances with same
values).
cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

<or*******@yaho o.com.au> wrote in message
news:11******** **************@ g49g2000cwa.goo glegroups.com.. .
Hi There

I am learning about reflection so apologies if this post is vague ...

I am doing some unit testing and have written a function that accepts
two objects and tests to see if their properties are equal. It seems
to work OK except when a object has a property that is an array.

The GetValue method of the PropertyInfo class returns an object, and I
want to convert it to an array of objects. For some reason, this
fails:

object[] objectArray = (object[])myObject;

However if I know the type, then it works. For example:

SecurityRoles[] rolesArray = (SecurityRoles[])object;

The problem is that I don't know the type at design time ! I tried to
do this:

propInfo.Proper tyType[] objectArray =
(propInfo.Prope rtyType[])myObject;

But it did not compile (ps ... propInfo is an instance of the
PropertyInfo class).

The code listing for my function is below. I would really appreciate
any guidance!

Thanks
Bill

using System;
using System.Reflecti on;

namespace ServerTest
{
public static class ObjectComparer
{
/// <summary>
/// This function compares any two objects properties. It will
recursively search down through nested properties
/// WARNING - It only compares properties that are one of the
following string, char, short, int, long, bool, DateTime, Enum
/// *** IT IGNORES ANY PROPERTIES THAT ARE ARRAYS ***
/// </summary>
/// <param name="thisType" >The type of the two objects</param>
/// <param name="leftObjec t"></param>
/// <param name="rightObje ct"></param>
/// <returns>True to indicate that the objects are equal.
False otherwise</returns>
public static bool AreTheseObjectE qual(Type thisType, object
leftObject, object rightObject)
{
if (leftObject == null && rightObject == null)
return true;

if (leftObject == null || rightObject == null)
return false;

PropertyInfo[] fields = thisType.GetPro perties();

foreach (PropertyInfo propInfo in fields)
{
if (propInfo.Prope rtyType.IsArray )
{
//*************** *************** *************** *************** *************** ******
//Property is an array, need to iterate through the
elements and compare them

//*************** *************** *************** *************** *************** ******

//object lhs = propInfo.GetVal ue(leftObject, null);
//object rhs = propInfo.GetVal ue(rightObject,
null);

////This does not work
//object[] lhsArray = (object[])lhs;
//object[] rhsArray = (object[])rhs;

////If the above worked, I could then do this:
//if (lhsArray.Lengt h != rhsArray.Length )
// return false;
//else
//{
// for (int i = 0; i < lhsArray.Length ; i++)
// {
// if (false ==
AreTheseObjectE qual(propInfo.P ropertyType,
(object)lhsArra y[i],(object)rhsArr ay[i]))
// return false;
// }
//}

//BUT .... If I knew the type then this would
work:
//STE.Model.Secur ityRoles[] secRolesLHS =
(STE.Model.Secu rityRoles[])lhs;
//STE.Model.Secur ityRoles[] secRolesRHS =
(STE.Model.Secu rityRoles[])rhs;
//But I don't know the type at run time
}
else
{
object lhs = propInfo.GetVal ue(leftObject, null);
object rhs = propInfo.GetVal ue(rightObject, null);

if (propInfo.Prope rtyType.IsEnum)
{
if (lhs.ToString() != rhs.ToString())
return false;
}
else if (lhs is string)
{
if (false == rhs is string)
return false;
if ((string)lhs != (string)rhs)
return false;
}
else if (lhs is char)
{
if (false == rhs is char)
return false;
if ((char)lhs != (char)rhs)
return false;
}
else if (lhs is bool)
{
if (false == rhs is bool)
return false;
if ((bool)lhs != (bool)rhs)
return false;
}
else if (lhs is short)
{
if (false == rhs is short)
return false;
if ((long)lhs != (long)rhs)
return false;
}
else if (lhs is int)
{
if (false == rhs is int)
return false;
if ((int)lhs != (int)rhs)
return false;
}
else if (lhs is long)
{
if (false == rhs is long)
return false;
if ((long)lhs != (long)rhs)
return false;
}
else if (lhs is DateTime)
{
if (false == rhs is DateTime)
return false;
if ((DateTime)lhs != (DateTime)rhs)
return false;
}
else
{
PropertyInfo[] nestedFields =
propInfo.Proper tyType.GetPrope rties();
if (nestedFields.L ength > 0)
{
if (false ==
AreTheseObjectE qual(propInfo.P ropertyType,
propInfo.GetVal ue(leftObject, null), propInfo.GetVal ue(rightObject,
null)))
return false;
}
}
}
}
return true;
}
}
}

Nov 17 '05 #3
Unless of course, the reference type overloaded the equality operator.

Nov 17 '05 #4
Ben
Great !!! It appears to be working perfectly. Thanks everyone for your help.

If you are interested I have posted the complete code:

https://msdn.microsoft.com/newsgroup...5-583e484fb370

It is my first foray into reflection and recursion, so I would be interested
in any feedback

Cheers
Bill
Nov 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
14947
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
31
3534
by: nikola | last post by:
Hi all, I was working with a simple function template to find the min of two values. But since I would like the two values to be different (type) I dont know what kind of value (type) it will return. I tried to write something like this: template <class Type1, class Type2, class Type3> Type3 findMin(Type1 x, Type2 y){ return (x < y) ? x : y;
2
1387
by: _andrea.l | last post by:
I'd like to roder an array: $array $array $array I'd like to order $array by name or by numbre of by a function($array,$array) that return 1 or -1 if id1 is less tha id2 or viceversa... How can I do that? How can I order in a complex case like this?
1
1466
by: Ben | last post by:
Hi There I am learning about reflection so apologies if this post is vague ... I am doing some unit testing and have written a function that accepts two objects and tests to see if their properties are equal. It seems to work OK except when a object has a property that is an array. The GetValue method of the PropertyInfo class returns an object, and I want to convert it to an array of objects. For some reason, this
41
2577
by: Telmo Costa | last post by:
Hi. I have the following code: -------------------------------------- function Tunnel() { //arguments(???); } function Sum() { var sum = 0; for (i=0; i<arguments.length; i++) sum += arguments;
28
4336
by: Larax | last post by:
Best explanation of my question will be an example, look below at this simple function: function SetEventHandler(element) { // some operations on element element.onclick = function(event) {
5
2243
by: Daz | last post by:
Hi everyone. My query is very straight forward (I think). What's the difference between someFunc.blah = function(){ ; } and
26
25607
by: tnowles00 | last post by:
Hi friend, what is the use of function pointer in c language and where it is useful? tell with simple example...? plz help me.
36
3393
by: Julienne Walker | last post by:
Ignoring implementation details and strictly following the C99 standard in terms of semantics, is there anything fundamentally flawed with describing the use of a (non-inline) function as an address? I keep feeling like I'm missing something obvious. -Jul To keep things in context, this is in reference to describing functions to a beginner.
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9398
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9951
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8831
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5275
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5419
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2805
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.