🤖 In C#, the $ symbol is used to define an interpolated string. An interpolated string allows you to embed expressions inside a string literal, which are evaluated and their results are included in the string.
Example 1: Basic String Interpolation
string name = "John";
int age = 30;
string greeting = $"Hello, my name is {name} and I am {age} years old.";
Here, the expressions {name} and {age} are evaluated and their values are inserted into the string. The result is:
// Output: "Hello, my name is John and I am 30 years old."
Example 2: Expressions in Interpolation
You can also use more complex expressions inside the interpolation braces:
int a = 5;
int b = 10;
string result = $"The sum of {a} and {b} is {a + b}.";
This will output:
// Output: "The sum of 5 and 10 is 15."
Example 3: Formatting Numbers
You can also format numbers within an interpolated string:
This uses the :C2 format specifier to format the number as currency with two decimal places:
// Output: "The price is $123.46."
Example 4: Combining with Verbatim Strings
You can combine $ with @ to create an interpolated verbatim string, which is useful when dealing with multiline or file paths that also require interpolation:
🤖 In C#, the
$
symbol is used to define an interpolated string. An interpolated string allows you to embed expressions inside a string literal, which are evaluated and their results are included in the string.Example 1: Basic String Interpolation
Here, the expressions
{name}
and{age}
are evaluated and their values are inserted into the string. The result is:Example 2: Expressions in Interpolation
You can also use more complex expressions inside the interpolation braces:
This will output:
Example 3: Formatting Numbers
You can also format numbers within an interpolated string:
This uses the
:C2
format specifier to format the number as currency with two decimal places:Example 4: Combining with Verbatim Strings
You can combine
$
with@
to create an interpolated verbatim string, which is useful when dealing with multiline or file paths that also require interpolation:This results in:
These examples show how
$
is used to create interpolated strings in C#.