Delphi – E2021 Class type required

A class type is required in some cases by the compiler:

As a class type’s ancestor
In a try-except statement, in the on-clause.
A raise statement’s first argument.
In a forward specified class type, as the final type.

A Class Declaration must include a Class Type.
If you try to declare a class with no parent class that implements one or more interfaces, you’ll get this error. Consider the following scenario:

TMyClass = class(IMyInterface1, IMyInterface2);

Every class in Delphi inherits from a parent class, and the compiler thinks that your class inherits from TObject if you don’t mention a parent class when you declare it. To put it another way, the following two lines of code are interchangeable:

TMyClass = class;
TMyClass = class(TObject);

You must provide a parent class before the interfaces that your class implements in order to fix your code:

TMyClass = class(TObject, IMyInterface1, IMyInterface2);

If you inherit straight from TObject, however, you must implement the IInterface API, which is the foundation of all interfaces. TInterfacedObject is a convenience class that implements the API for you:

TMyClass = class(TInterfacedObject, IMyInterface1, IMyInterface2);

Raise Statements Require a Class Type
If you try to raise a string literal, you’ll get this error. Consider the following scenario:

program Produce;
begin
  raise 'This would work in C++, but does not in Delphi';
end.

Instead, you must build an exception object:

program Solve;
uses SysUtils;
begin
  raise Exception.Create('There is a simple workaround, however');
end.
%d bloggers like this: