1. Home
  2. Computing & Technology
  3. Delphi Programming

An Invalid Hard-Cast is NIL in Delphi for .NET

Find out why TButton(Edit1) is NIL in Delphi for .NET

By Zarko Gajic, About.com

In Delphi you can (type) cast an object to a different class using either a hard-cast: TObject(Sender).Name or an as-cast (soft-cast): (Sender as Object).Name.

TObject(Sender) vs. (Sender as TObject) explains differences between an as-cast and a hard-cast from the WIN32 perspective.

Both of the supported type-casts will "convert" an object to a different type object.

The hard-cast forces an object to act as a diferent object. If the hard-cast is invalid, meaning that an object you are casting cannot be casted to the class you want it to "mimic", access violation might occur at run-time. However hard-casts are fater and when paired to the IS check a hard cast can be safe.

On the other hand, an as-cast checks if an object can be casted to a different type. If not, an "Invalid Type Cast" will be raised by Delphi.

An Invalid Hard-Cast is NIL in Delphi for .NET

Since .NET is more strict when it comes to casting an object to a different type, Delphi for .NET does not allow "unsafe" hard-casts.

In a scenario where TDeveloper extends TPerson, and TLanguage is not related to any of the two classes:

type
  TLanguage = class(TObject)
  TPerson = class(TObject)
  TDeveloper = class(TPerson)
...
var
  developer : TDeveloper;
  language : TLanguage;
begin
  //an ok cast
  TPerson(developer).PersonMethod;

  //invalid cast
  language = TLanguage(developer) ;

  //object reference not set to an instance of an object
  language.LanguageMethod;
end

In the above code, "language" is NIL after the invalid cast - and the result is the .Net version of the access violation exception: object reference not set to an instance of an object.

Note: as-casts and is-tests work identically in Win32 and .NET.

C# Code Readers Warning

If you have some C# code you need to convert to Delphi, be very careful.

Delphi for .NET's invalid hard-cast TObject(Sender) returns NIL. C# version returns NIL when an as-cast is used.

Therefore, C#'s (Sender as TObject) should be translated to Delphi's TObject(Sender).

A confession: I have a "bug" in the title of this article! If Edit1 is a TEdit, Delphi for .NET compiler will not let Button(Edit1) to be compiled. E2089 Invalid Typecast will be raised at compile time.

Delphi tips navigator:
» Programmatically Convert RGB Color to CYMK
« TObject(Sender) vs. (Sender as TObject)

More Delphi Programming Quick Tips

Explore Delphi Programming

More from About.com

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2007 Tips
  7. An Invalid Hard-Cast is NIL in Delphi for .NET. Find out why TButton(Edit1) is NIL in Delphi for .NET

©2008 About.com, a part of The New York Times Company.

All rights reserved.