0
0
C Sharp (C#)programming~5 mins

String interpolation in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is string interpolation in C#?
String interpolation is a way to insert variables or expressions directly inside a string literal using a special syntax, making the code easier to read and write.
Click to reveal answer
beginner
How do you start a string literal to use string interpolation in C#?
You start the string with a $ symbol before the opening double quote, like this: $"Your text {variable}".
Click to reveal answer
beginner
What is the output of this code?<br>
int age = 25;<br>string message = $"I am {age} years old.";<br>Console.WriteLine(message);
The output will be: I am 25 years old.
Click to reveal answer
intermediate
Can you use expressions inside the curly braces in string interpolation?
Yes, you can put any valid expression inside the curly braces, like calculations or method calls, and it will be evaluated and inserted into the string.
Click to reveal answer
intermediate
How do you format numbers or dates inside string interpolation?
You can add a colon and a format string after the expression inside the braces, for example: $"{price:C}" to format as currency or $"{date:yyyy-MM-dd}" for a date format.
Click to reveal answer
Which symbol is used to start a string literal for interpolation in C#?
A$
B#
C@
D%
What will this code print?<br>
int x = 3;<br>int y = 4;<br>Console.WriteLine($"Sum is {x + y}");
ASum is x + y
BSum is {x + y}
CSum is 34
DSum is 7
How do you include a literal curly brace '{' in an interpolated string?
AUse single quotes '{'
BEscape with backslash '\{'
CUse double braces like '{{'
DYou cannot include curly braces
Which of these is a valid interpolated string in C#?
A$"Hello {name}"
B"Hello {name}"
C@"Hello {name}"
D#"Hello {name}"
How can you format a date inside an interpolated string?
A"{date}"
B$"{date:MM/dd/yyyy}"
C"{date:MM/dd/yyyy}"
D$"{date.format('MM/dd/yyyy')}"
Explain how string interpolation works in C# and give a simple example.
Think about how to insert a variable value directly inside a string.
You got /3 concepts.
    Describe how to format numbers or dates inside an interpolated string in C#.
    Remember the syntax {expression:format} inside the string.
    You got /3 concepts.