String Interpolation UseUse string interpolation to place values like Integers and Strings into another String.
This page was last reviewed on Jan 3, 2024.
String interpolation. In VB.NET it is often useful to print out values by surrounding them by another string. This can be done when using Console.WriteLine or when a String is needed.
With String interpolation, we use the "$" symbol before a string literal. And we place variables (and expressions) directly into it.
Example. Here we have 2 Integers, one called "cats" and one called "dogs." We place these values into another string that is then passed to Console.WriteLine.
Tip The leading "$" symbol is important. If we forget to insert it, the variables will not be inserted.
Tip 2 Variable names must be enclosed within curly brackets. We can reference variables from the surrounding code.
Module Module1 Sub Main() Dim cats As Integer = 100 Dim dogs As Integer = 2 ' Place 2 variables into the string. Dim animals As String = $"cats = {cats} and dogs = {dogs}" ' Call WriteLine. Console.WriteLine(animals) End Sub End Module
cats = 100 and dogs = 2
Arrays. String interpolation in VB.NET supports more complex expressions, and we can even access array elements. The standard syntax of the language is used for the indexing expression.
Module Module1 Sub Main() Dim values = { 10, 20, 30 } ' Access array element within a string interpolation. Dim result = $"The second value is {values(1)}" Console.WriteLine(result) End Sub End Module
The second value is 20
Expression. Suppose we need to multiply or add a number with a string interpolation. This is possible, but the expression must come in between the curly brackets.
Module Module1 Sub Main() Dim id = 100 ' Do some arithmetic within the string interpolation. Dim result = $"The multiplied ID is {id * 10}" Console.WriteLine(result) End Sub End Module
The multiplied ID is 1000
Function call. A Function can also be called within a string interpolation expression. Here we call the Paws() function within the string, and we print the result with Console.WriteLine.
Module Module1 Function Paws(cats as Integer) As Integer ' Multiply by 4 to return total paws. Return cats * 4 End Function Sub Main() ' Invoke Function within string interpolation. Dim result = $"The paw count is {Paws(5)}" Console.WriteLine(result) End Sub End Module
The paw count is 20
Summary. Because it has clearer syntax than alternatives, string interpolation is a good choice for creating strings and console output. With simpler code, programs can be better maintained.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 3, 2024 (new).
© 2007-2024 Sam Allen.