Monday, February 23, 2015

Graceful Multi-line strings in vb.net

My Graceful Daughter, Laura
Many languages allow you to specify string literals that span more than one line in a graceful, elegant way.

C#, for example, allows an At-Sign prefix, so
string ThisString @="line one
                     Line two
                     Line three";
Python supports it as follows:
 aString ="""line one
             Line two
             Line three"""
But in VB, you're forced to do
Dim aString as String ="line one " & _
                       "Line two  " & _
                       "Line three "
That's both annoying, error-prone (it bites me most with multiple-line SQL statements where I forgot to put a space between a field name in the SELECT and the FROM clause.)

But I found a neat way to do away with the concatenation.
Use the XML Linq library

Imports System.XML
Imports System.XML.Linq
Imports System.Core
Dim aString As String = <![CDATA[Line one
                                 Line Two
                                 Line Three]]>.Value