How to VB.NET String.Format()

The VB.NET String.Format() method is used to format a composite string by replacing placeholders with corresponding values. It allows you to dynamically construct strings with placeholders for variables or values that need to be inserted.

String.Format()

Here is an example that demonstrates how to use the String.Format() method in VB.NET:

Dim name As String = "John" Dim age As Integer = 25 Dim message As String = String.Format("My name is {0} and I am {1} years old.", name, age) Console.WriteLine(message)

In the above example, we have a composite string with two placeholders: {0} and {1}. These placeholders indicate the positions where the corresponding values (name and age) will be inserted.

The String.Format() method takes the composite string as the first argument, followed by the values to be inserted in the placeholders. The values are passed as separate arguments in the order that matches the placeholders.

The output of the above example will be:

My name is John and I am 25 years old.

You can also specify formatting options for the values being inserted. For example, you can specify the number of decimal places for a numeric value, specify a specific date format, or add padding to a string. Here's an example:

Dim price As Double = 12.3456 Dim formattedPrice As String = String.Format("The price is {0:C2}", price) Console.WriteLine(formattedPrice)

In this example, the {0:C2} placeholder formats the price value as a currency with two decimal places. The output will be:

The price is $12.35

Conclusion

The String.Format() method provides a powerful way to create formatted strings with placeholders and insert dynamic values. It supports a wide range of formatting options and is commonly used in scenarios where you need to construct complex strings with variable values.