Alex's answer is the correct solution to the problem. And it also does well to return from the function as soon as the answer is known.
I'd like to expand on the answer with some more explanation. In particular I'd like to answer the question you asked in comments to Alex's answer:
As an aside ... why doesn't the original work? T is derived from X.
The problem code is here:
function XList<T>.Find(Id: Integer): T;
var
t: X;
begin
for t in Self do
if t.Id = Id then
Result := t;
end;
The way to think about generics, is to imagine what the code looks like when you instantiate the type and supply a concrete type parameter. In this case, let's substitute T
with Y
. Then the code looks like this:
function XList_Y.Find(Id: Integer): Y;
var
t: X;
begin
for t in Self do
if t.Id = Id then
Result := t;
end;
Now you have a problem at the line that assigns to Result
:
Result := t;
Well, Result
is of type Y
, but t
is of type X
. The relationship between X
and Y
is that Y
is derived from X
. So an instance of Y
is an X
. But an instance of X
is not a Y
. And so the assignment is not valid.
As Alex correctly pointed out, you need to declare the loop variable to be of type T
. Personally I would write the code like this:
function XList<T>.Find(Id: Integer): T;
begin
for Result in Self do
if Result.Id = Id then
exit;
Result := nil;
// or perhaps you wish to raise an exception if the item cannot be found
end;
This also deals with the problem that your search routine leaves its return value uninitialized in case the item is not found. That's a problem that you compiler would have warned about once you got the code as far as actually compiling. I do hope you enable compiler warnings, and deal with them when they appear!