Start learning free

LESSON 58 OF 674 · STRINGS I

String Immutability in C#

Lesson

In C#, strings are immutable, which means that they cannot be altered once created.

For example, the following code:

string message = "Jello world";

message[0] = 'H';

would produce a compile error: Property or indexer 'string.this[int]' cannot be assigned to -- it is read only.


Variable can still be changed:

Note that this does not mean that message cannot be changed, just that the individual characters of a string literal cannot be changed.

"Jello world" is a string literal that C# stores in memory, while message is a variable that refers to that string literal.

When we do message[0] = 'H', we are trying to alter the string literal "Jello world", which is not allowed.

But like any other variable, message can be changed by reassigning it with a new string, like this:

string message = "Jello world";

message = "Hello world";

Console.WriteLine(message);

This code would output:

Hello world

Instead of trying to alter the first string, this code now creates a new one ("Hello world"), stores it in memory and tells message to refer to this new string.


Assignment
Follow the Coding Tutorial and let's practice with string immutability!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check