Skip to content

Instantly share code, notes, and snippets.

@jpluimers
Last active October 18, 2018 15:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpluimers/dc3d64655b9baab589839562d2b7cbf9 to your computer and use it in GitHub Desktop.
Save jpluimers/dc3d64655b9baab589839562d2b7cbf9 to your computer and use it in GitHub Desktop.
ObjectHelperUnit as WordPress.com keeps mangling `code` and `pre` sections having angle brackets in them
unit ObjectHelperUnit;
interface
type
TObjectHelper = record
class function Cast<T: class>(const aValue: TObject): T; static;
class procedure FreeAndNil<T: class>(var Value: T); static;
end;
implementation
uses
System.SysConst,
System.SysUtils;
class function TObjectHelper.Cast<T>(const aValue: TObject): T;
var
lException: Exception;
begin
if Assigned(aValue) then
begin
if aValue is T then
Result := T(aValue)
else
begin
lException := EInvalidCast.CreateFmt('%s; actual type %s but expected %s.',
[SInvalidCast, aValue.QualifiedClassName, T.QualifiedClassName]);
raise lException at ReturnAddress;
end;
end
else
Result := nil;
end;
class procedure TObjectHelper.FreeAndNil<T>(var Value: T);
begin
System.SysUtils.FreeAndNil(Value);
end;
end.
procedure TMyServer.UnbindFromIdTcpServerStatusContext(const aContext: TIdContext);
var
lClientSession: TClientSession;
begin
lClientSession := TObjectHelper.Cast<TClientSession>(aContext.Data);
...
end;
type
TBaseDataInterface = class(TObject)
strict private
FDatabase: TIBDatabase;
FTransaction: TIBTransaction;
...
end;
destructor TBaseDataInterface.Destroy();
begin
TObjectHelper.FreeAndNil(FDatabase);
TObjectHelper.FreeAndNil(FTransaction);
...
inherited Destroy();
end;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment