Team LiB
Previous Section Next Section

Strings

We'll discuss one more important predefined type in this chapter—the string type.

Note?/td>

Just a reminder: unlike the other C# types that we've introduced in this chapter, string isn't a value type, but rather, is a reference type, as we mentioned earlier. For purposes of this introductory discussion of strings, this observation isn't important; the significance of the string type's being a reference type will be discussed in Chapter 13.

A string represents a sequence of Unicode characters. There are several ways to create and initialize a string variable. The easiest and most commonly used way is to declare a variable of type string and to assign the variable a value using a string literal. A string literal is any text enclosed in double quotes:

string name = "Zachary";

Note that we use double quotes, not single quotes, to surround a string literal when assigning it to a string variable, even if it consists of only a single character:

string shortString = "A";      // Use DOUBLE quotes when assigning a literal
                               // value to a string ...

string longString = "supercalifragilisticexpialadocious"; // (ditto)

char c = 'A';                    // ... and SINGLE quotes when assigning a literal
                                 // a value to a char.

Two commonly used approaches for assigning an initial value to a string variable as a placeholder are as follows:

The plus sign (+) operator is normally used for addition, but when used with string variables, it represents string concatenation. Any number of string variables or string literals can be concatenated together with the + operator.

  string x = "foo";
  string y = "bar";
  string z = x + y + "!"; // z now equals "foobar!"; x and y are unchanged

You'll learn about some of the many other operations that can be performed with or on strings, along with gaining insights into their object-oriented nature, in Chapter 13.


Team LiB
Previous Section Next Section