I\'m trying to write a generic cached property accessor like the following but am getting a compiler error when trying to check whether the storage variable already contains
The problem is not the Default
function, but the equality operator =
.
You could constrain T
to IEquatable
and use the Equals
method like this:
TMyClass = class
function GetProp<T : IEquatable<T>>(var ADataValue: T; const ARetriever:
end;
...
function TMyClass.GetProp<T>(var ADataValue: T; const ARetriever: TFunc<T>): T;
begin
if ADataValue.Equals (Default(T)) then
ADataValue := ARetriever();
Result := ADataValue;
end;
After a hint in the comments from Binis and digging around a little in Generics.Collections I came up with the following which appears to work just as I wanted it:
function TMyClass.GetProp<T>(var ADataValue: T; const ARetriever: TFunc<T>): T;
var
lComparer: IEqualityComparer<T>;
begin
lComparer := TEqualityComparer<T>.Default;
if lComparer.Equals(ADataValue, Default(T)) then
ADataValue := ARetriever();
Result := ADataValue;
end;