Gigi Labs

Please follow Gigi Labs for the latest articles.

Wednesday, May 22, 2013

C# Basics: Building Strings

Hullo! :)

In yesterday's article, C# Network Programming: Simple HTTP Client, we built an HTTP request (in a String variable) and sent it out over the network.

We built the String as a literal string. That is just one of several ways to build complex Strings. In this article, we will look at a few other techniques we could have used instead.

Method 1: Literal Strings

As a refresher, in yesterday's article we created a literal String like this:

             String request = @"GET / HTTP/1.1
Connection: Close


The @ character before the String denotes it as a literal. If you remove it, the program won't compile.

Literal Strings allow you to include newlines. A simple Console.WriteLine(request); allows you to see how the above code is translated:

Method 2: Escape Sequences

You can also include newlines by using the \r and \n escape sequences as follows:

 String request2 = "GET / HTTP/1.1\r\nHost:\r\nConnection: Close\r\n\r\n";

\r is a carriage return (ASCII #13) and \n is a line feed (ASCII #10); these two characters together make up a newline. There are several other of these escape sequences, all starting with a backslash (\) followed by a particular character, but these two are by far the most useful.

The disadvantage of this approach is that if you have a particularly long String (and HTTP requests are usually quite a bit longer than this), the code isn't very readable.

Method 3: String Concatenation

You can build up a long String from smaller Strings using concatenation (+ operator):

            String request3 = "GET / HTTP/1.1\r\n";
            request3 += "Host:\r\n";
            request3 += "Connection: Close\r\n\r\n";

You still need escape sequences, since this is not a literal String. However it's a bit more readable than having one long String.

While concatenating one or two small Strings is okay, this becomes very inefficient when you have a lot. This is because in C#, Strings don't change: you aren't really adding one String to another. You are in fact creating a third String made up of both of them.

Method 4: StringBuilder

The solution to the problem of String concatenation is to use the StringBuilder class. This is great for when you need to build a long String out of a lot of smaller ones. For this you first need to include:

using System.Text;

Then, just do something like this:

            StringBuilder request4Sb = new StringBuilder();
            request4Sb.Append("GET / HTTP/1.1\r\n");
            request4Sb.Append("Connection: Close\r\n\r\n");

The text here is only converted to a String when you use the ToString() method:

            String request4 = request4Sb.ToString();

This means that you can do a lot of String manipulation before that in an efficient way.

Method 5: Format Strings

You can use String.Format() to build up Strings using the familiar {0} notation we've been using all along in our calls to Console.WriteLine():

             String request5 = String.Format("{0}\r\n{1}\r\n{2}\r\n\r\n",
                "GET / HTTP/1.1""Host:""Connection: Close");

This is most useful when you have a number of variables that you want to swap into the Strings. Like with Console.WriteLine(), you can include those variables as parameters, and refer to them using {0}, {1}, etc.

In this case, there is not much use in using String.Format(), since all the Strings involved are well-known constants. It even looks pretty ugly.

But the fact remains that String.Format() is another useful way to build complex Strings.


In this article we have seen five different ways of building Strings, and compared them to each other.

In the case of a simple HTTP request, using a literal String is no doubt the best way, both for efficiency and for code readability.

In other scenarios, however, other techniques may prove to be more suitable.

Thanks for reading, and come back for more! :)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.