Link to home
Start Free TrialLog in
Avatar of aubs
aubs

asked on

Comparing Objects

Suppose I declare a class TTest

TTest=class(TObject)
             fred: string;
             chris: boolean;
             end;

Then declare and create 2 objects: test1 and test2

var
   test1, test2: TTest;

procedure TForm1.Button1Click(Sender: TObject);
begin
  test1:= TTest.create;
  test2:= TTest.create;
end;

Then later I want to compare the values of the parameters of each class to see if they match. I dont want to have to compare each parameter like this:

  if (test1.fred=test2.fred) AND (test1.chris=test2.chris) then...
 
This gets very messy if the object has 10 or more parameters to compare.

Ideally I would like to do something like

if test1 = test2 then...

but this doesn't work!

Any suggestions
Avatar of cabela
cabela

The simple comparison does not work because you are dealing with pointers. You have to compare the objects. You can do a call like the following:

CompareMem (P1, P2, P1.InstanceSize)

But this works only if you do not have other pointers in the object (like string). To compare these, you have to compare them separatly.
You can write a function like this
 
type
  TTest=class(TObject)
    fred  : string;
    chris : boolean;
    function IsEqual(otherTest: TTest) : boolean;
  end;

function TTest.IsEqual(otherTest: TTest) : boolean;
begin
  result := (fred  = otherTest.fred) and
            (chris = otherTest.chris);
end;

Now you can compare two test objects like this:

  if test1.IsEqual(test2) then
    ...

Regards, Madshi.
Avatar of aubs

ASKER

Hi Cabela

I realised that the reason

  if  test1=test2...

doesnt work is because you're comparing everything in each object. I had already tried something similar to your suggestion with pointers but still had no success.

Basically what your saying is that I'm stuck with the long winded method of:

  if (test1.fred=test2.fred) AND (test1.chris=test2.chris) AND ...

If this is true then I think that Madshi's suggestion is a good one.
Yeah, Madshi's idea is a nice and simple one. And moreover it's safe. Not like mine.
Thanx...  :-)  Well, I'm using my suggestion in my own sources, too.
Sometimes you can deal with records:
TMyRec= packed record
  Byte1, Byte2: Byte;
  Word1: Word;
  str: ShortString;
end;

TMyClass= class
private
  FMyRec: TMyRec
end;
Now you can compare the memory of the FMyRecs but like cabela said that doesn't work with long strings.
ptm.
Avatar of aubs

ASKER

OK Madshi,

Can you post an answer so that I can give you the points.

Aubs
You can do this by accepting a comment as an answer....
Right...  :-)  You could have accepted one of my comments as an answer - anyway, here is the answer...

Regards, Madshi.
ASKER CERTIFIED SOLUTION
Avatar of Madshi
Madshi

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial