Created
December 21, 2017 09:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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