16.3 string Constructors

Figure 16.1 demonstrates three of class string’s constructors.

Fig. 16.1 Demonstrating string class constructors.

Alternate View

 1   // Fig. 16.1: StringConstructor.cs
 2   // Demonstrating string class constructors.
 3   using System;
 4
 5   class StringConstructor
 6   {
 7      static void Main()
 8      {
 9         // string initialization
10         char[] characterArray =
11            {'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y'};
12         var originalString = "Welcome to C# programming!";
13         var string1 = originalString;
14         var string2 = new string(characterArray);      
15         var string3 = new string(characterArray, 6, 3);
16         var string4 = new string('C', 5);              
17
18         Console.WriteLine($"string1 = "{string1}"
" +
19            $"string2 = "{string2}"
" +
20            $"string3 = "{string3}"
" +
21            $"string4 = "{string4}"
");
22      }
23   }

string1 = "Welcome to C# programming!"
string2 = "birth day"
string3 = "day"
string4 = "CCCCC"

Lines 10–11 create the char array characterArray, which contains nine characters. Lines 12–16 declare the strings originalString, string1, string2, string3 and string4. Line 12 assigns string literal "Welcome to C# programming!" to string reference originalString. Line 13 sets string1 to reference the same string literal.

Line 14 assigns to string2 a new string, using the string constructor with a character array argument. The new string contains a copy of the array’s characters.

Line 15 assigns to string3 a new string, using the string constructor that takes a char array and two int arguments. The second argument specifies the starting index position (the offset) from which characters in the array are to be copied. The third argument specifies the number of characters (the count) to be copied from the specified starting position in the array. The new string contains a copy of the specified characters in the array. If the specified offset or count indicates that the program should access an element outside the bounds of the character array, an ArgumentOutOfRangeException is thrown.

Line 16 assigns to string4 a new string, using the string constructor that takes as arguments a character and an int specifying the number of times to repeat that character in the string.

Software Engineering Observation 16.1

In most cases, it’s not necessary to make a copy of an existing string. All string s are immutable—their character contents cannot be changed after they’re created. Also, if there are one or more references to a string (or any reference-type object for that matter), the object cannot be reclaimed by the garbage collector.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset