A nerd pretending to be a software engineer.

Some Stuff I Didn’t Know About String in C#

Written on

Well, its a bit strange getting to know something that I’ve used extensively for quite a while, but there are indeed some things that feels revealing.

First of all, I knew that strings is a little bit special, in a way that it is a reference type, but it behaves very much like a value type, for example:

SomeClass a = new SomeClass();
a.age = 18;
SomeClass b = a;
b.age = 30;

// a.age will be 40, since they are both referring to the same value
// but,

string x = "hello";
string y = x;
y = "world;  // x will stay as "hello"

So, well, that’s about it. I also knew that string are immutable, as in, the value can’t be changed after they are set, so something like this would throw an error:

string x = "hello";
x[0] = 'j';

But, since something like that didn’t get used much anyway, I never put too much thought into it, and I just learned that the two are actually related. In the first code snippet, since x is immutable, when y try to change the value, it will create a new string instead, so it will point to a new location in the memory, leaving x alone, and the two no longer refer to the same memory location.

The value of the string itself are stored in the same memory location as well, so even if two strings are created separately, if they have the same value, they will still point to the same location.

string x = "hello";
string y = "hello";
// x == y is true

I personally have ran into some bugs related to this behaviour, of course, I just tried do something else that works without understanding why. Until now.

That mentioned, one thing to remember is that new string values are created each time the value change, so that means there would be a lot of temporary objects in the memory, and the garbage collection will run more often, so if there value of the change is something that is done very extensively in the program, it would be better to use a class called StringBuilder. It behaves almost the same way as a string, but it is not immutable, and it is designed to build string, as the name suggest. I wanted to talk more about it, but I found a better explanation about it, so I’ll just use this post as a book mark to that post.

Some other interesting stuffs about strings and the manipulation of strings as well:

comments powered by Disqus