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

String type and immutability in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
String Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code?
Consider the following C# code snippet. What will be printed to the console?
C Sharp (C#)
string s = "hello";
s = s.Replace('h', 'j');
Console.WriteLine(s);
AHello
Bjello
Chello
Djello\nhello
Attempts:
2 left
💡 Hint
Remember that strings in C# are immutable. The Replace method returns a new string but does not change the original.
Predict Output
intermediate
2:00remaining
What is the output of this code?
What will this C# program print?
C Sharp (C#)
string a = "abc";
string b = a + "def";
Console.WriteLine(a);
Console.WriteLine(b);
Aabcdef\nabc
Babcdef\nabcdef
Cabc\nabc
Dabc\nabcdef
Attempts:
2 left
💡 Hint
Adding strings creates a new string; the original string remains unchanged.
🔧 Debug
advanced
2:00remaining
Why does this code not change the string?
This code tries to change the first character of a string. Why does it fail?
C Sharp (C#)
string s = "test";
s[0] = 'b';
Console.WriteLine(s);
ACompilation error: strings are immutable and cannot be changed by index.
BRuntime error: index out of range.
COutput: test
DOutput: best
Attempts:
2 left
💡 Hint
Think about whether you can assign to a character in a string by index in C#.
Predict Output
advanced
2:00remaining
What is the output of this code?
What will this program print?
C Sharp (C#)
string s1 = "hello";
string s2 = s1.ToUpper();
Console.WriteLine(s1);
Console.WriteLine(s2);
AHELLO\nHELLO
Bhello\nHELLO
Chello\nhello
DHELLO\nhello
Attempts:
2 left
💡 Hint
ToUpper returns a new string; it does not change the original string.
🧠 Conceptual
expert
2:00remaining
Why is string immutability important in C#?
Which of the following is NOT a reason why strings are immutable in C#?
AIt allows direct modification of characters in the string to save memory.
BIt improves performance by enabling string interning and caching.
CIt allows strings to be safely shared across multiple threads without synchronization.
DIt simplifies security by preventing unexpected changes to string data.
Attempts:
2 left
💡 Hint
Think about what immutability means and how it affects string modification.