Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I avoid using ClassType in application code?

Tags:

oop

delphi

The Delphi online documentation says

"Avoid using ClassType in application code".

However there are many places where a class type is needed. For example when a program uses the class System.Contnrs.TClassList, I need the ClassType of an object to pass it in the parameter of IndexOf().

What is the reason behind this recommendation in the ClassType documentation?

like image 934
mjn Avatar asked Jun 03 '13 11:06

mjn


1 Answers

The most obvious reason why this advice is given is for programmers that want to write code like this:

if obj.ClassType = TStringList then
  ....

That condition will only evaluate true if the object's class is TStringList. However, very commonly you would want the conditional code to run for TStringList and any descendents. In which case you write:

if obj is TStringList then
  ....

If you need to know what class an instance is, then ClassType is what you should use. If you are maintaining a list of classes in a TClassList instance, then feel free to use ClassType to obtain the meta class of an instance.

like image 153
David Heffernan Avatar answered Oct 30 '22 06:10

David Heffernan