Passing object properties in functions

Is it possible to pass a property of an object as a parameter when that property has a getter and setter?

I can pass it as const, but that only works when the function doesn’t need to change the value.

What I’d like to do is pass a const value and a reference to the object property. If they are different, I want to update the object property (with the value of the other parameter) and return true so the caller can invoke something else.

Hi David

One solution I would consider is to pass two anon methods to the function/procedure instead of the property.

For example

type
TMyGetter = reference to function: TMyResult;
TMySetter = reference to procedure(const xValue: TMyResult);

function MyFunc(const xMyGetter: TMyGetter; const xMySetter: TMySetter):
begin
value:= xMyGetter;
xMySetter(NeValue);
end;

If MyFunction(function: MyResult
begin
result:=MyProperty;
end
,procedure(const xValue: MyResult)
begin
MyProperty:= xValue;
end
);

If this is confusing please contact me offline;

Regards
Graeme

consider is to pass

I think I understand the above. The objects and properties will vary so that won’t work in my case?

In short, no. Whilst the property type might be compatible - when you pass the property you are passing a reference to the getter (ie a referenc to a method), which is not the same as a reference to a value (e.g boolean).

I thought that was the case and the reason for the compiler error. At first I didn’t get it until I realised the “variables” I was trying to pass were actually properties!

Hi David

I don’t understand why my solution will not work for different objects and properties.
The TSetter and TGetter methods just need to replicate the real getters and setters.
It’s just that you will need two parameters and instead of one in your function/procedure.

If you wish to send me an example of what you are trying to do, please do so, and I will see if I can supply a solution.

Regards
Graeme

Are you able to send me

If I understand your solution it would work, but I’d have to create a TGetter and TSetter for every object type that I want to use this generic function with. Since each object type only has one place in code where I would have used the generic function, it seems like the extra work is not warranted.

What I was trying to do is:

If ParameterUpdate(Obj.A, NewValue) then
  DoUpdate;

Right now I’ve just coded each one as:

If Obj.A <> NewValue then
begin
  Obj.A := NewValue;
  DoUpdate;
end;

I still thank you for your time and may be able to use your idea for something else in the future.

Hi David

Ummmm… Hi Graeme !

er hello.

Can I help you with anything or do you want to leave it?

Regards
Graeme

All good my friend. I was just relying to your partial quote reply. :smiley:

Hi, I can’t figure out anonymous procedures or methods. Simple examples may be helpful. Thanks