Search code examples
c#stringstringbuilder

C# How StringBuilder is mutable?


I was trying to find out a post which should explain how exactly append function works for StringBuilder.

I got across through this answer.

Now, String is immutable. I get this.

But, StringBuilder is also initializing a new temporary character array whenever we try to append something to it.


Solution

  • Mutable doesn't mean that it can't create new stuff. Mutable just means that its state can change after the constructor returns.

    For example, this is mutable, even though string is immutable:

    class Foo {
        public string Bar { get; set; }
    
        public void FooMethod() {
            Bar = new string('!', 10);
        }
    }
    

    Because we can change the state of it by setting Bar or calling FooMethod:

     someFoo.FooMethod();
    

    Yes, I am creating a new string here in the FooMethod, but that does not matter. What does matter is that Bar now has a new value! The state of someFoo changed.

    We say StringBuilder is mutable because its state can change, without creating a new StringBuilder. As you have looked up, StringBuilder stores a char array. Each time you append something, that char array changes to something else, but no new StringBuilders are created. This is solid proof that StringBuilder is mutable.