The Daily Parker

Politics, Weather, Photography, and the Dog

S is for String

Blogging A to ZDay 19 of the Blogging A-to-Z challenge was Saturday, but Apollo After Hours drained me more or less completely for the weekend.

So this morning, let's pretend it's still Saturday for just a moment, and consider one of the oddest classes in the .NET Base Class Library (BCL): System.String.

A string is just a sequence of one or more characters. A character could be anything: a letter, a number, a random two-byte value, what have you. System.String holds the sequence for you and gives you some tools to control them, like Compare, Format, Join, Split, and StartsWith. Under the hood, the class holds the string as an array of char values.

Even though System.String is a class and not a struct, it behaves much more like the latter than the former. Strings are immutable: once you create a string, any changes you make to it create a new string instance. Also, below a certain length, strings live on the stack rather than in the heap, which has consequences for memory management and performance. But unlike structs, strings can be null. This is valid code:

var s = "Hello, world";
string t = null;
var u = t + s;

Strings can also be zero-length or all whitespace, which is why the class has a very useful method String.IsNullOrWhitespace().

The blog C# in Depth has a good description of strings that's worth reading. Jon Skeet also takes on string memory management in one of his longer posts.

Comments are closed