String Initialization and System.String Class using C#

This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

C# strings stem from the String class of the System namespace: System.String. A similar class, the StringBuilder class, can be found in the System.Text namespace. We'll talk more about the StringBuilder class later in this article. 

The String class is used to work with strings in the .NET Framework. String objects are immutable: Once they are created, their values cannot be changed. However, you can reassign the string reference to another string, freeing up the first string for garbage collection if no other reference to it exists. 

String class methods that appear to manipulate a string do not change the current string but instead create a new string and return it. This process of repeatedly creating and throwing away strings can be slow. However, with immutable objects, ownership, aliasing, and threading issues are all much simpler. 

Strings consist of characters in the ascii set. These characters include simple alphanumeric such as 'a' or '_'. These characters also include special characters that include <return> or <tab> characters. Return, tab and other special characters are represented in a string using escape sequences. Table 20.1 shows the escape sequences some of the common special characters. 


Table 20.1: Escape Sequences 

Verbatim string literals begin with @" and end with the matching quotation mark. They do not require escape sequences. The only exception to the no-escape-sequence rule for verbatim string literals is that you can put a double quotation mark inside a verbatim string by doubling it: 

        @"A ""quote"" from Conan the Cimmerian"

Verbatim string literals can also extend over a line break. If they do, they include any white space between the quotes: 

         @"First \t line tabbed second line"

Like all classes, the String class is a reference type with built-in .NET Framework support methods and operators to simplify development. Such support includes string indexing to read (but not write) individual characters (as in s[i]), string concatenating with the + operator (as in s + t), and equality and inequality operators (as in s == t and s != t). Listing 20.19 demonstrates their use. 

Listing 20.19: String Assignments Comparisons 

            string strValue1 = @"verbatim C# text";
            string strValue2 = @"verbatim C# text " + @" concatenated…";
            string strValue3 = "regular C# text \r\n"; // beware escape sequences \r\n
            char chrFirst = strValue1[3]; // stores 't'
            if (strValue1 == strValue2) { } // value equality comparison
            if (strValue1 != strValue2) { } // value inequality comparison
            if ((object)strValue1 == (object)strValue2) { } //reference equality comparison
            if ((object)strValue1 != (object)strValue2) { } //reference inequality comparison

You can also concatenate any object with a string. This concatenates the return value from the object's ToString method with the string. For instance, all of the following are valid: 

            String str1 = " everyone using C# is hefty ";
            String str2 = 4 + str1; // "4 everyone using C# is hefty"
            String str3 = str2 + 19.19; // "4 everyone using C# is hefty 19.19"

In addition, because strings are immutable, the compiler and runtime will merge duplicate string literals so that there's only one copy. 

The two most common methods of initializing a string are to assign the string with a string literal or to assign a string with the value from another string: 

            String str1 = "Hello, World!";
            String str2 = str1;

As Listing 20.20 shows, you can use the static method Copy if you want a second copy of the string. 

Listing 20.20: String Assignments Comparisons 

            String str1 = "Hello, World again…";

            //no copy; str1 and str2 refer to same String
            String str2 = (String)str1.Clone();

            // makes copy; str1 and str3 refer to different objects
            String str3 = String.Copy(str1);
            Console.WriteLine("str1 same as str2: {0}, str1 same as str3: {1}",
            (Object)str1 == (Object)str2, (Object)str1 == (Object)str3);

You can also create an array of strings, as Listing 20.21 shows. 

Listing 20.21: String Arrays

        String[] a = new String[3];
            a[0] = "1";
            a[1] = "2";
            a[2] = "3";


        String[,] aa = new String[3, 3];
        aa[0,0] = "1";
        aa[1,0] = "2";
        aa[2,0] = "3";

Listing 20.22 shows additional ways to assign values to strings. 

Listing 20.22: String Creation Styles

using System;

class myString
    public String str;

    //Create the string through character Array
    public myString(char[] strValue)
        str = new String(strValue);
        Console.WriteLine("The string '" + str + "' has been initialized by passing an array of characters");

    //Create the string through a single character which is repeated a number of times
    public myString(char strValue, int intCount)
        str = new String(strValue, intCount);
        Console.WriteLine("The string '" + str + "' has been initialized by a character '" + strValue + "' which is repeated '" + intCount + "' times");

    //Create the string through character array specifying the starting and ending places
    public myString(char[] strValue, int intStart, int intEnd)
        str = new String(strValue, intStart, intEnd);
        Console.WriteLine("The string " + str + " has been initialized by array of characters starting from '" + intStart + "' and ending at '" + intEnd +"'");

    static void Main(string[] args)


Hope this article would have helped you in understanding the String Initialization and System.String Class. See other articles on the website on .NET and C#.

visual C-sharp.jpg
The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.