Strings are one of the most useful types in .Net, and since you’ll be using it almost every day, let’s see what we can learn about String.

MSDN: A string is a sequential collection of Unicode characters that is used to represent text.

Strings are a reference type but in some ways it behaves like a value type. For instance, String is immutable, meaning you cannot change content of a string.

Strings can be null.

You can compare two strings.

Maximum size of a string is 2Gb.

Common Operations with Strings

Strings are hard-coded with literals. There are two types of literals: “regular literal” and “verbatim literal”.

If you try running a program, the output will be the same. So how do we know which type of literal to use? When you have a simple text that can be written in one line and does not contain escape characters, you will typically use regular expressions.  Verbatim literals are for example useful when you write SQL code.

Let’s try out some common operations with strings using the following well-known sentence:  The quick brown fox jumps over the lazy dog.

\n –  newline

\” – double quotes

\’ – single quote

\\ – backslash


Trim text

A very common operation, and all it does is basically remove empty space at the beginning, end or both. Remember, because strings are immutable, String itself will not be changed.


How to Check if String Is Empty

All the scenarios above bring about the same result. But there are a few things to be aware of. Length method is the fastest one, both Length and Empty methods create the same code in IL, but in my opinion, the last approach is the easiest one to read and it also checks the strings for null.


Thank you for following me so far and be sure to check in tomorrow because in the next post we will continue covering Strings.