santiagoIT
santiagoIT

Reputation: 9421

Delphi Generics: cannot cast class and constructor constrained generic type to an interface

procedure Test<TType: class, constructor>;

procedure TTestClass.Test<TType>;
var
   Obj1: IInterface;
begin
   Obj1 := TType.Create as IInterface;
end;

Gives the following compile error:

[DCC Error] TestCNCTypesSerialization.pas(76): E2015 Operator not applicable to this operand type

I do not understand why. And I cannot find a way to make this work...

Thanks!

Upvotes: 2

Views: 340

Answers (1)

David Heffernan
David Heffernan

Reputation: 612794

The compiler has no grounds to believe that the generic type implements IInterface. You did not constrain the generic type to be derived from a class that implements IInterface.

You could constrain the class in that way, but that might be too restrictive. Alternatively use Supports to obtain the interface.

Upvotes: 5

Related Questions