string
ConstructorsFigure 16.1 demonstrates three of class string
’s constructors.
Lines 10–11 create the char
array characterArray
, which contains nine characters. Lines 12–16 declare the string
s 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
.
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.