Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 471
XO39 Avatar asked Dec 04 '22 04:12

XO39


1 Answers

With {0} you're specifying a format placeholder, whereas with & you're just concatenating the string.

Using format placeholders

Dim name As String = String.Format("{0} {1}", "James", "Johnson")

Using string concatenation

Dim name As String = "James" & " " & "Johnson"
like image 137
James Johnson Avatar answered Jan 01 '23 14:01

James Johnson