Differences Between String and StringBuilder in C#

4 Quick Differences Between String and StringBuilder in C#

With the help of this post, I am going to explain the differences between String and StringBuilder in C#. It is a common interview question for c#, asp.net developers as well.

String

The String is immutable. This means once we create a string object we cannot modify it.

When we perform any operation on strings like insert, replace, or append to change the string, it will discard the old value and a new instance will be created in memory to hold the new value.

Code Snippet

string str = "ds";
// It creates a new string instance instead of changing the old one
str += "tech";
str += "dipendra shekhawat";

StringBuilder

StringBuilder is mutable. This means once we create a string object we can modify it.

When we create a string builder object we can perform any operation like insert, replace, or append without new instances getting created every time.

Code Snippet

StringBuilder sb = new StringBuilder(20);

sb.Append("dotnet");

sb.Append("crunch");

string str = sb.ToString();

Differences Between String and StringBuilder

I have compiled the list of differences between String and StringBuilder in C#:

String StringBuilder

It is an immutable (unchanging)

It is mutable (liable to change)

Affects performance because every time it will create a new instance

Boosts performance as it will use the same instance of an object to perform any action

You cannot use the append keyword on strings

You can use the append keyword on the StringBuilder object

It belongs to the System namespace

It belongs to System.Text namespace

Summary

You have learned the differences between String and StringBuilder in C# along with their features with the help of code examples.

What do you think?

Dear Reader,
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.

{Happy Coding}

I write about technologies like WordPress, ASP.NET, C#, JQuery, HTML, CSS, AJAX, WCF, Web Services. I have started this blog to share my knowledge and help others to learn.

Share with your friends:

Leave a Comment

Your email address will not be published. Required fields are marked *