StringBuilder sb is declared but not assigned an instance with 'new'.
Step 2: Understand consequences
Calling Append on uninitialized sb causes runtime error (NullReferenceException).
Final Answer:
StringBuilder is not initialized before use -> Option A
Quick Check:
Uninitialized objects cause errors = B [OK]
Hint: Always initialize StringBuilder with 'new' before use [OK]
Common Mistakes:
Forgetting to use 'new' keyword
Thinking Append is missing
Assuming ToString() is invalid
5. You want to build a string by adding numbers from 1 to 5 separated by commas using StringBuilder. Which code snippet correctly does this without extra comma at the end?
hard
A. var sb = new StringBuilder();
for(int i=1; i<=5; i++) {
sb.Append(i + ",");
}
Console.WriteLine(sb.ToString());
B. var sb = new StringBuilder();
for(int i=1; i<=5; i++) {
sb.Append(i);
if(i < 5) sb.Append(",");
}
Console.WriteLine(sb.ToString());
C. var sb = new StringBuilder();
for(int i=1; i<=5; i++) {
sb.Append("," + i);
}
Console.WriteLine(sb.ToString());
D. var sb = new StringBuilder();
sb.Append("1,2,3,4,5");
Console.WriteLine(sb.ToString());
Solution
Step 1: Analyze each option for comma placement
var sb = new StringBuilder();
for(int i=1; i<=5; i++) {
sb.Append(i);
if(i < 5) sb.Append(",");
}
Console.WriteLine(sb.ToString()); adds number then comma only if not last, avoiding trailing comma.
Step 2: Check other options
var sb = new StringBuilder();
for(int i=1; i<=5; i++) {
sb.Append(i + ",");
}
Console.WriteLine(sb.ToString()); adds comma after every number, causing extra comma at end; C adds comma before number, starting with comma; D hardcodes string, not using loop.
Final Answer:
var sb = new StringBuilder();
for(int i=1; i<=5; i++) {
sb.Append(i);
if(i < 5) sb.Append(",");
}
Console.WriteLine(sb.ToString()); -> Option B
Quick Check:
Conditionally add commas to avoid trailing one = A [OK]
Hint: Add commas only between items, not after last [OK]
Common Mistakes:
Adding comma after last item
Adding comma before first item
Hardcoding string instead of looping
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.