Lou
Lou

Reputation: 2509

What do numbers in braces e.g. "{0}" mean?

I've been looking around but having great difficulty finding the answer to this question as the thing I'm looking for is so unspecific.

I've seen a lot of code which uses {0} in it, and I still can't work out what it's doing. Here's an example:

Dim literal As String = "CatDogFence"
Dim substring As String = literal.Substring(6)
Console.WriteLine("Substring: {0}", substring)

Upvotes: 5

Views: 3858

Answers (4)

dbasnett
dbasnett

Reputation: 11773

It is called composite formatting and is supported by many methods, Console.WriteLine being one. Besides indexed placeholders there are other features available. Here is a link to the documentation that shows some of the other features of composite formatting.

Composite Formatting

Upvotes: 0

Lotok
Lotok

Reputation: 4607

Console.WriteLine() and String.Format() use that syntax. It allows you to inject a variable into a string, for example:

dim name = "james"
String.Format("Hello {0}", name)

That string will be "Hello james"

Using Console.Writeline:

Console.WriteLine("Hello {0}",name)

That will write "Hello james"

Upvotes: 3

qqilihq
qqilihq

Reputation: 11454

It's a placeholder. Beginning at the second parameter (substring in your case), they are included in the given string in the given order. This way you avoid long string concatenations using + operator and can do easier language localization, because you can pull the compete string including the placeholders to some external resource file etc.

Upvotes: 1

tckmn
tckmn

Reputation: 59273

Console.WriteLine("Substring: {0}", substring)

Is the same as

Console.WriteLine("Substring: " & substring)

When using Console.WriteLine, {n} will insert the nth argument into the string, then write it.

A more complex example can be seen here:

Console.WriteLine("{0} {1}{2}", "Stack", "Over", "flow")

It will print Stack Overflow.

Upvotes: 4

Related Questions