Null Terminator character
A zero Char is added to a char array to indicate its end point, this character is referred to as the "Null Terminator". This character is added to the end of each string to mark its ending boundary - the String classes in .NET do this automagically. So, declaring something like:
string s = "Foo" ;
Results in the following character array being generated under the covers:
char[] s = {'F','o','o','0'} ;
This will almost never be a problem because, using .NET string classes and methods which return strings will always return a "safe" string rather than the raw character arrays. But, imagine if that wasn't the case and you had to deal with the "Null Terminator" in your own code; forgetting to do so could easily result in unexpected results:
Dim a As String = "Foo" MsgBox( a ) ' displays "Foo" Dim b As String = "Foo" & Chr(0) & "Bar" MsgBox( b ) ' displays "Foo"!!!
Yesterday, it did actually bite me because I was dealing with some API calls to get volume information about a machine:
Private Declare Function GetVolumeInformation Lib "kernel32" Alias "GetVolumeInformationA" _ (ByVal lpRootPathName As String, _ ByVal lpVolumeNameBuffer As String, _ ByVal nVolumeNameSize As Int32, _ ByRef lpVolumeSerialNumber As System.UInt32, _ ByRef lpMaximumComponentLength As Int32, _ ByRef lpFileSystemFlags As Int32, _ ByVal lpFileSystemNameBuffer As String, _ ByVal nFileSystemNameSize As Int32) As Int32 Dim drvserial As System.UInt32 Dim drvlbl As String = Space(200) Dim filesys As String = Space(200) Dim i As Int32 Dim j As Int32 Dim k As Int32 k = GetVolumeInformation("C:\", drvlbl, 200, drvserial, i, j, filesys, 200) MsgBox( drvserial.ToString & "-" & drvlbl & "-" & filesys )
What happened is that, when I ran this code the value of drvlbl was being returned with the Chr(0) character appended at the end of 200 spaces. Therefore, I was only ever seeing the value or drvserial being displayed. The easy way to fix that - in VB at least - is the use the VB Replace function to clean up the Chr(0) character:
MsgBox( drvserial.ToString & "-" & Replace( drvlbl, Chr(0), "" ) & "-" & filesys )
I'm not really sure whether this behaviour would be exhibited when making the same API call via C# or whether it's just a "feature" of the VB language; I suspect that it will only be an issue in VB!