Skip to content

Instantly share code, notes, and snippets.

@jpluimers
Created December 21, 2017 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpluimers/31a036b7c91bc121c422fcb1a0adbd39 to your computer and use it in GitHub Desktop.
Save jpluimers/31a036b7c91bc121c422fcb1a0adbd39 to your computer and use it in GitHub Desktop.
A typesafe FreeAndNil a Cast with more descriptive error in a TObjectHelper that limits the generics to class references.
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;
end;
end
else
Result := nil;
end;
class procedure TObjectHelper.FreeAndNil<T>(var Value: T);
begin
System.SysUtils.FreeAndNil(Value);
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment