Team LiB   Previous Section   Next Section

17.1 Creating Strings

C# treats strings as if they were built-in types. C# strings are flexible, powerful, and easy to use.

In .NET, each string object is an immutable sequence of Unicode characters. In other words, methods that appear to change the string actually return a modified copy; the original string remains intact.

The declaration of the System.String class is:

public sealed class String : 
   IComparable, ICloneablee, IConvertible, IEnumerable

This declaration reveals that the class is sealed, meaning that it is not possible to derive from the String class. The class also implements four system interfaces — IComparable, ICloneable, IConvertible, and IEnumerable — which dictate functionality that System.String shares with other classes in the .NET Framework. Interfaces are introduced in Chapter 14.

The IComparable interface is implemented by types that can be sorted. Strings, for example, can be alphabetized; any given string can be compared with another string to determine which should come first in an ordered list. IComparable classes implement the CompareTo() method.

ICloneable objects can create new instances with the same value as the original instance. In this case, it is possible to clone a string to produce a new string with the same values (characters) as the original. ICloneable classes implement the Clone() method.

IConvertible classes provide methods to facilitate conversion to other primitive types; these methods include ToInt32(), ToDouble(), and ToDecimal().

IEnumerable, discussed in detail in Chapter 16, lets you use the foreach construct to enumerate a string as a collection of chars. That is, you can write:

string theString = "hello world";
foreach (char c in theString)
{
    Console.WriteLine(c);
}

The output is each letter of hello world on its own line.

17.1.1 String Literals

The most common way to create a string is to assign a quoted string of characters, known as a string literal, to a user-defined variable of type string. The following code declares a string called newString that contains the phrase This is a string literal.

string newString = "This is a string literal";

17.1.2 Escape Characters

Quoted strings can include escape characters, which begin with a backslash character (\). The two most common escape characters are "\n", which is used to create a new line, and "\t", which is used to insert a tab into a string.

In a quoted string a literal backslash must be preceded by another backslash ("\"). Thus, if you were writing the string c:\myDirectory, you'd write:

 "c:\\myDirectory"

17.1.3 Verbatim Strings

Strings can also be created using verbatim string literals, which start with the (@) symbol. This tells the String constructor that the string should be used verbatim, even if it spans multiple lines or includes escape characters. In a verbatim string literal, backslashes and the characters that follow them are simply considered additional characters of the string. Thus, the following two definitions are equivalent:

string literalOne = "\\\\MySystem\\MyDirectory\\ProgrammingC#.cs";
string verbatimLiteralOne = @"\\MySystem\MyDirectory\ProgrammingC#.cs";

In the first line, a nonverbatim string literal is used, and so the backslash character (\) must be escaped, which means it must be preceded by a second backslash character. In the second, a verbatim literal string is used, so the extra backslash is not needed. A second example illustrates two ways to specify multiline verbatim strings. The first definition uses a nonverbatim string with a newline escape character (\n) to signal the line break. The second definition uses a verbatim string literal:

string literalTwo = "Line One\nLine Two";
string verbatimLiteralTwo = @"Line One
Line Two";

Again, these declarations are interchangeable. Which one you use is a matter of convenience and personal style.

17.1.4 The ToString() Method

Another common way to create a string is to call the ToString() method on an object and assign the result to a string variable. All the built-in types override this method to simplify the task of converting a value (often a numeric value) to a string representation of that value. In the following example, the ToString() method of an integer type is called to store its value in a string:

int myInteger = 5;
string integerString = myInteger.ToString();

The call to myInteger.ToString() returns a string object that is then assigned to the string variable, integerString.

    Team LiB   Previous Section   Next Section