Post

Using CR and LF: The Options. (VB.NET)

After posting a response to a question on GDN about using CR and LF in a VB.NET project.

The question was how to insert a LF or CR into a string in VB.NET without using the vbLF, vbCR or even the Environment.LineFeed values. They were also thinking that the vbXX values were in the VisualBasic.Compatibility namespace; which isn’t the case.

There are several options available. Before looking into all of them, I’d like to point out that I lean more towards the readability side of it; as long as there isn’t a noticable performance hit for doing so. So to me, vbCR, vbLF, vbCRLF are offer more readability to the code and easier to type since the Imports for the Constants portion of the VisualBasic namespace is already done for all VB.NET projects (IDE wise that is) ;-)

So, upon further inspection of all of the options, here is a quick outline of all of them:

Microsoft.VisualBasic.

  ControlChars.Cr [Char]
  ControlChars.Lf [Char]
  ControlChars.CrLf [String]

  Constants.vbCr [String]
  Constants.vbLf [String]
  Constants.vbCrLf [String]

  Chr(13) [Char]
  Chr(10) [Char]

System.

  Environment.NewLine [String]

System.Windows.Forms.

  Keys.Return.ToString (String)
  Keys.LineFeed.ToString (String)
  Chr(Keys.Return) (Char)
  Chr(Keys.LineFeed) (Char)

I’ve pointed out which ones are Strings and which ones are Chars so that you would know the return type; which might be important under some pretty specific circumstances (sometimes performance related).

All of the first three options are available through the VisualBasic namespace, and through the System namespace you have the NewLine option (which is equiv to vbCRLF or /r/n in C’ish). If you wanted to, you could add…

1
Imports Microsoft.VisualBasic.ControlChars

…to the top of your module. This would allow you to use Cr, Lf, and CrLf in the same manner as vbCr, vbLF, and vbCrLf. On the other side of the coin, you could use the Constants.vbCr syntax as well.

Using the System.Windows.Forms.Keys option, you would be better off using the Chr() method instead of the ToString method. This is because the ToString will return a string that will consume some of the memory that will have to be GC’d; while the Chr() will return a numeric value that doesn’t have to be GC’d unless it’s assigned to a variable (Stack based variable).

UPDATE: It’s worth mentioning that, at least as of VB.NET 2003, Chr() and ChrW are both processed at Compile-Time. This makes, for example Chr(10) literally equivalent to the C-ish \n. The true value is stored in place in the compiled assembly. If 10 is not a literal (meaning, a variable), then Chr is processed at runtime.

UPDATE: Slight correction, for Chr(), only values 0-127 work in this manner. For values higher than 127, it will have to be computed at runtime based on the machine’s locale. (Thanks to Kardax for pointing this out.)

This post is licensed under CC BY 4.0 by the author.