In C#, you can interpolate strings using the string interpolation feature, which allows you to embed expressions directly within a string. String interpolation simplifies the process of building dynamic strings by automatically converting the expressions to their string representations.
To interpolate a string, you need to prefix the string with the $ symbol, and then use curly braces { } to enclose the expressions you want to include. Here's an example:
string name = "Alice"; int age = 30; string message = $"Hello, {name}! You are {age} years old."; Console.WriteLine(message); In the above code, the variables name and age are interpolated within the string message using the { } syntax. When the message string is printed using Console.WriteLine, the expressions {name} and {age} are replaced with their respective values.
The output will be:
Hello, Alice! You are 30 years old.
String interpolation supports not only variables but also any valid C# expression within the curly braces. For example, you can perform calculations or call methods:
double radius = 3.5; double area = Math.PI * radius * radius; string result = $"The area of a circle with radius {radius} is {area}"; Console.WriteLine(result); The output will be:
The area of a circle with radius 3.5 is 38.48451000647496
String interpolation offers a concise and readable way to construct dynamic strings by directly embedding expressions within them.
"String interpolation in C#"
string name = "John"; int age = 30; string message = $"Hello, my name is {name} and I am {age} years old."; "Format strings using interpolated strings in C#"
decimal price = 29.99m; int quantity = 2; string invoice = $"Total cost: {price * quantity:C}"; "Embed expressions within strings in C#"
int x = 5; int y = 10; string result = $"The sum of {x} and {y} is {x + y}."; "Conditional interpolation in C#"
bool isAdmin = true; string greeting = $"Welcome{(isAdmin ? ", Admin" : "")}!"; "Interpolate DateTime objects in C#"
DateTime currentDate = DateTime.Now; string formattedDate = $"Current date and time: {currentDate:yyyy-MM-dd HH:mm:ss}"; "Interpolate collection elements in C#"
List<string> fruits = new List<string> { "Apple", "Banana", "Orange" }; string message = $"My favorite fruits are: {string.Join(", ", fruits)}"; "Numeric formatting with interpolated strings in C#"
double pi = Math.PI; string formattedPi = $"The value of pi is approximately {pi:F3}"; "Escape characters in interpolated strings in C#"
string escapedString = $"This is an escaped string: {{ brackets }}"; "Multiline strings with interpolation in C#"
string multilineMessage = $@" Hello, This is a multiline message. Current date: {DateTime.Now:yyyy-MM-dd}"; "Localization and culture-specific formatting in C#"
int number = 12345; string localizedNumber = $"{number:N0}"; // Format with thousands separator based on culture utf-8 awk youtube-analytics h2o database-design html-generation uibutton dispatchevent matplotlib-basemap git-push