Introduction

There are several ways to concatenate string in VB.Net. Most will use the &-operator but we all know you should use the String.Format method. And sometimes you might by accident use the +-operator. The +-operator is however not such a good idea. Here is why.

The problem

If you run this little program you will see that the result is not always what you expect.

Option Strict Off
Option Infer On

Module Module1

	Sub Main()
		Dim _I = "1" + 1
		Console.WriteLine(_I)
		Console.WriteLine("1" + 1)
		Console.WriteLine("1" + "1")
		Console.WriteLine("1" & 1)
		Console.WriteLine("1" & "1")
		Console.ReadLine()
	End Sub

End Module

The result being.

2

2

11

11

11

Why the +-operator infers a double here instead of a string is less important. Knowing that it does so is more important, you can read more about it on MSDN.

Where you will also see this little quote.

However, to eliminate ambiguity, you should use the & operator instead. If the components of an expression created with the + operator are numeric, the arithmetic result is assigned. If the components are exclusively strings, the strings are concatenated.

So I would recommend not using the + sign to concatenate strings.

The solution

The solution is called Resharper. Resharper and the custom patterns (this could have been a book title) to be exact. And this is the custom pattern you can use.

As you can see I have also done a replace already. So next time you use a plus you will see this.

Alas the replace does not work well in Resharper 6.0. But I have filed a bug and I hope this will be fixed soon.

And here you have the pattern you can import into your patterns. Just save it in an xml-file and import.

xml <CustomPatterns> Pattern Severity="WARNING" FormatAfterReplace="True" ShortenReferences="True" Language="VBASIC"> <Comment>String concatenation with a plus is highly discouraged try to use &.</Comment> <ReplacePattern><![CDATA[$str1$ & $str2$]]></ReplacePattern> <SearchPattern>$str1$ + $str2$</SearchPattern> <Params /> <Placeholders> <ExpressionPlaceholder Name="str1" ExpressionType="System.String" ExactType="False" /> <ExpressionPlaceholder Name="str2" ExpressionType="System.String" ExactType="False" /> </Placeholders> </Pattern> </CustomPatterns>

Conclusion

String concatenation with the +-operator is to be avoided in VB.Net so use the &-operator instead. And you can use Resharper to avoid from making this mistake.