Abusing XML literals in VB.NET

Posted on Wed 25 April 2012 in Coding

One of the things I do like about VB.NET is XML literals. Given that XML is so common, it’s really a great idea! Here’s a tiny example:

Dim x = <p>Some test.</p>

I thought I’d write about how XML literals can be abused to create multi-line strings very easily. But then I realized that it doesn’t stop there - we can as easily use them as multi-line format strings too! Consider the following code that uses String.Format to solve the task:

Private Function CreateStringUsingStringFormat(a As String, b As Integer,
                                               c As Boolean) As String
    Return String.Format(
        "This is a multi-line string{0}that runs over multiple lines{0}" +
        "and incorporates {1} and {2}{0}and finally {3}.",
        Environment.NewLine, a, b, c)
End Function

This piece of code has at least two problems. One is that the connection between the format items and the arguments that populate them is quite loose (which arguably also is a strength). The other is that we have to encode newlines explicitly as format items.

The corresponding solution that uses an XML literal solves both problems and is more readable, IMHO:

Private Function CreateStringUsingXmlLiteral(a As String, b As Integer,
                                             c As Boolean) As String
    Return <p>This is a multi-line string
that runs over multiple lines
and incorporates <%= a %> and <%= b %>
and finally <%= c %>.</p>.Value
End Function

Note how I added “.Value” to the XML literal. This is where the abuse comes in - the XML literal is only used as a means to an end and once we’ve reached the goal, we don’t care about the XML anymore. It was just a convenient language feature, like a here document.

I did some microbenchmarking and found that the two techniques are equivalent in terms of speed. The XML literal solution is about 3 to 5 percent slower using the example above. I think that’s a small price to pay for readability, don’t you? If speed is important, you should use StringBuilder or pure string concatenation, as these are roughly twice as fast.