Null Strings

Null Strings

In .NET, strings can have a value of null (nil). In Delphi strings cannot be set to nil. Trying to set a string to nil in Delphi will result in a compile error:

[DCC Error] Incompatible types: 'string' and 'Pointer'

This causes a problem with .NET strings that are returned via CrossTalk if they are set to null. Fortunately this is not a common practice in .NET, but it is valid and some code uses it.

Handling Null Strings

There are several ways to work around this. If an empty string can be used instead, this is the best option. If null indicates information and is unique from an empty string, then this cannot work with Delphi.

If a null string is encountered and you try to access it, CrossTalk will raise a ECTNullString exception which can be caught and handled.

As an example, the following code could be used:

xUsernameIsNull := true;
try
  xUsername := xDotNetObject.Username;
except on ex: ECTNullString do begin
  xUsernameIsNull := true;
  xUsername := '';
end;

Note: ECTNullString was added in CrossTalk 2.0.29.

Box When Needed

The next simplest solution is to change the call or wrap it if you cannot change the code to return an object instead. CrossTalk will then box the string and null can be handled as an object value of null, with the string still accessible inside the box.

Why Not Box All?

While it would be possible to have CrossTalk box all strings, this would create an undesired boxing of every string and complicate your code. Since there is no way to detect if a string will contain null at compile time, CrossTalk cannot conditionally box strings either.

CrossTalk could be altered to have a special string type, but this too would add some complexity and require a fair bit of changes to CrossTalk for a scenario which is not commonly encountered. For such corner cases, the ECTNullString exception usually suffices.