On Casts in C# and Delphi

Posted by on in Blogs
Be advised: The rules for typecasting when a cast is invalid are almost exactly the opposite in C# and Delphi for .NET. Let's say you have a reference of type Object and you want to cast that reference to type FileStream. Presume further that the cast is invalid, because the reference is actually a completely different type. In C#, there are two ways to cast:
FileStream fs = (FileStream) someReference; // way 1
FileStream fs = someReference as FileStream; // way 2
Since the cast is invalid, way 1, in C#, will throw an exception, whereas way 2 will result in fs being null. In Delphi for .NET, there are two similar ways to cast, with opposite results:

var
fs: FileStream;
begin
fs := FileStream(someReference); // way 1
fs := someReference as FileStream; // way 2
Way 1, in Delphi, results in fs being nil, whereas way 2 throws an exception. Why didn't Delphi for .NET follow C#'s implementation? Because Delphi needs to be compatible with Delphi for Win32 code, where as will throw an exception. A "hard" cast (way 1) in Delphi for Win32 produces junk when the cast is invalid, so the .NET behavior is actually a non-code-breaking improvement over Delphi for Win32. This is only made more confusing by an error in the Delphi for .NET documentation which says that both cast syntaxes produce the same effect; they don't.
Tags: C# Delphi


Comments

Check out more tips and tricks in this development video: