Delphi: Exposing Protected Properties

On occasion you’ll find yourself wanting to access a a protected property from a class in a different unit. If this is a 3rd party unit, you’ll often not want to modify it’s source code. So how do you access it? Sub-classing the class as you might have guessed, however, you can do this in very little code.

Delphi will allow any class to use protected properties from other classes as long as they are in the same unit. We can use this to our advantage. By creating a subclass, we can essentially use this to access protected values in the class we’re sub-classing, it works the same way, because your subclass is in the unit you need it in. All you have to do, is cast the object to the subclass and you’re set to access the protected property.

unit Example;

interface

uses
  Classes;

type
  TStringListEx = class(TStringList);

implementation

function SLChanged(const SL: TStringList): Boolean;
begin
  Result := TStringListEx(SL).Changed;
end;

end.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.