What's the differences between "{0}" and "&" in VB.NET?

concatenation, vb.net

Solution

What you're seeing here are two very different expressions that just so happen to evaluate to the same output.

The `&` operator in VB.Net is the string concatenation operator. It essentially works by converting both the left and right side of the expression to a `String` and them adding them together. This means all the below operations are roughly equivalent

"Hello " & num
"Hello " & num.ToString()
"Hello " & CStr(num)

The `{0}` is a feature of the .Net APIs. It represents a position within a string which will later be replaced with a value. The `{0}` refers to the first value passed to the function, `{1}` the second and so on. This means that all the below operations are roughly equivalent

Console.WriteLine("Hello {0}!", num)
Console.WriteLine("Hello " & num & "!")

The reason you see the same output is because putting `{0}` at the end of the string is almost exactly the same as a string concatenation of the 2 values.

Problem

Please be easy on me guys as I'm still learning. The following code: ``` Imports System.Console Module Module1 Sub Main() Dim num As Integer Dim name As String num = 1 name = "John" WriteLine("Hello, {0}", num) WriteLine("Hello, {0}", name) WriteLine("Hello, {0}", 1) WriteLine("Hello, {0}", "John") WriteLine("5 + 5 = {0}", 5 + 5) WriteLine() End Sub End Module ``` has the same output as this code: ``` Imports System.Console Module Module1 Sub Main() Dim num As Integer Dim name As String num = 1 name = "John" WriteLine("Hello, " & num) WriteLine("Hello, " & name) WriteLine("Hello, " & 1) WriteLine("Hello, " & "John") WriteLine("5 + 5 = " & 5 + 5) WriteLine() End Sub End Module ``` Both output: Hello, 1 Hello, John Hello, 1 Hello, John 5 + 5 = 10 I looked everywhere and couldn't find the answer. When to use "{0}, {1}, ... etc"? and when to use "&"? Which is better? And why?

Original source

Related problems