Mega Code Archive

 
Categories / Delphi / ADO Database
 

Hacking readonly properties

Title: Hacking readonly properties. Question: Delphi compiler is smart to know if in your code you wrote an assignment to a read only property and does not compile your code. We know that read only properties can be modified directly if the class that is modifying it is declared in the same unit that the class that owns the property. But if it is not the case? Answer: Suppose you have a TMyClass declared in unit2 and use it in Unit1: * Note that this works only to properties that are NOT read/written by a method (Get/Set methods). ============================================== unit Unit2; interface type TMyClass = class private FMyReadOnlyProperty: string; public constructor Create; property MyReadOnlyProperty: string read FMyReadOnlyProperty; end; implementation constructor TMyClass.Create; begin FMyReadOnlyProperty:= 'Default Value'; end; end. ============================================== unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, unit2; type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.Button1Click(Sender: TObject); var MyClass: TMyClass; PString: ^string; begin MyClass:= TMyClass.Create; {This shows the default value.} ShowMessage(MyClass.MyReadOnlyProperty); {The compiler does not allow this to be done.} //MyClass.MyReadOnlyProperty:= 'A Value'; {Get the address of MyClass.MyReadOnlyProperty} PString:= Addr(MyClass.MyReadOnlyProperty); {But in this case the compiler doesn't know what is being done with the property, because this is a pointer operation} PString^:= 'Wrote to a read only property !!!'; {And this shows the new value of the "Read Only" property.} ShowMessage(MyClass.MyReadOnlyProperty); MyClass.Free; end; end. {This is NOT a bug. Do you think this is? Please, send me your suggestions. rribas@facilities.com.br}