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

String interpolation and formatting 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 in C# is a way to insert variables or expressions directly inside a string literal by prefixing the string with a $ symbol and placing the expressions inside curly braces {}.
Click to reveal answer
beginner
How do you format a number to show two decimal places using string interpolation?
Use a format specifier inside the curly braces, like this: $"{number:F2}". This will format the number to two decimal places.
Click to reveal answer
intermediate
What is the difference between String.Format and string interpolation?
String.Format is a method that formats strings using placeholders like {0}, {1}, etc., while string interpolation lets you embed expressions directly in the string with $ and {}. Interpolation is usually easier to read and write.
Click to reveal answer
intermediate
How can you align text using string interpolation?
Inside the curly braces, after the variable name, use a comma and a number to specify alignment. For example, $"{name,10}" right-aligns in 10 spaces, and $"{name,-10}" left-aligns.
Click to reveal answer
advanced
What happens if you use a format specifier that doesn't match the data type in string interpolation?
You will get a runtime error or unexpected output because the format specifier expects a certain type. For example, using a numeric format on a string will cause an error.
Click to reveal answer
Which symbol is used to start a string interpolation in C#?
A$
B#
C@
D%
How do you format a number to show exactly 3 decimal places using string interpolation?
A{number:3}
B{number:F3}
C{number:.3f}
D{number:#.###}
What does this code output? string name = "Bob"; Console.WriteLine($"{name,5}");
A Bob (right-aligned in 5 spaces)
BBob (left-aligned in 5 spaces)
CBob (no spaces)
DError
Which method is an alternative to string interpolation for formatting strings?
AToString()
BConsole.Write
CString.Format
DParse()
What will happen if you use {value:D2} where value is a string?
AOutputs 'D2'
BFormats string as decimal with 2 digits
COutputs the string unchanged
DThrows a runtime error
Explain how to use string interpolation in C# to include variables and format numbers.
Think about how you write variables inside a string with $ and {}.
You got /4 concepts.
    Describe how to align text using string interpolation in C#.
    Remember the syntax {variable,number} inside the string.
    You got /4 concepts.