String.Concat instead of &

We all know that the concatenation operator & is evil when you use it intensively.
We know writing like this is no good:

Dim s as String = ""
s &= "<"
s &= spFieldName
s &= ">"
s &= spFieldValue
s &= "</"
s &= spFieldName
s &= ">"

This is no good because a new String object is being created for every line of this code and the value is being copied to the newly created object and no optimizations can be made during compilation. One could avoid this using a StringBuilder object and calling ToString() method to achieve the same result. However the readability wouldn’t be too good.

So today I was paging through code of some library not written by me. I used Lutz Roeder’s Reflector. I came accross the following approach of string concatenation:

Dim s as String
s = String.Concat("<",  spFieldName,  ">", spFieldValue, "</", spFieldName, ">")

They had used the “Dotfuscator” to obfuscate the code of the library. As far as I know, the Reflector also makes some optimizations to the code. That’s why I’m not really sure if this is a coding approach or an effect by Dotfuscator/Reflector. Anyway, I believe it is quite a good solution: it doesn’t use much memory for execution and it’s quite readable!

2 thoughts on “String.Concat instead of &”

  1. Man gan patīk variants Dim s as String s = String.Format("<{0}>{1}</{0}>", spFieldName, spFieldValue)

Comments are closed.