What are the differences between InheritsFrom and the is operator?
Yes, there is a difference. InheritsFrom
is class function and it's primary purpose is testing whether class IS
(inherits from some class).
You cannot use is
operator on classes.
TMyChildClass is TMyClass
would not compile, but you can use TMyChildClass.InheritsFrom(TMyClass)
instead.
The is
operator is built on top of InheritsFrom
. So,
obj is TSomeClass
is implemented as
(obj <> nil) and obj.InheritsFrom(TSomeClass)
The expression obj.InheritsFrom(TSomeClass)
is perhaps a little confusing because it looks like InheritsFrom
is an instance method. In fact InheritsFrom
is a class method, and the runtime class of obj
is passed to InheritsFrom
as the Self
pointer.
So fundamentally is
and InheritsFrom
perform the same task, at least when restricting attention to classes. Note that is
is more general and can also be used with interfaces, for example.
There are obvious syntactical differences. Namely that is
requires an instance, whereas InheritsFrom
is a class function. Although, as we have seen, the Delphi language does support calling class functions on instance references. And the other obvious difference is that is
has a built-in test for a nil
reference.
These are just syntactical differences though, the fundamental operation is the same, as evidenced by the fact that is
calls InheritsFrom
.