This is a very technical Delphi tip, possibly the first of a series... or maybe not. Over the 5 years I've had this blog, I rarely covered purely technical tips, but it might change (particularly if you tell me you like it).

As if not nil

The problems at hand is how to perform an "as" cast (a cast to a derived class) but only if the reference is not nil. in fact if you write,

obj as TButton

it will raise an exception in case the obj is not a TButton, but also in case obj is not assigned. Now if you write:

if obj is TButton then

you'll equally get the exception in case the obj is not assigned. so we need to change the code to:

if Assigned (obj) and (obj is TButton)

plus we have to do the actual cast. Question: can we write a single function to provide this behavior? 


Well, that's the point of the tip. In fact it turns out we can use generics and write a generic function that has the type as parameter. However, we cannot use a global function (they don't support generics types) but a class function (the only function of a specific class). Here is the class definition and the method code:

Now we can call this like:

btn := TCast.GetAs<TButton> (Sender);

Generics open up a lot of new coding techniques to Delphi, this is just the tip of the iceberg. Hope you find it useful...