1.11. The new Expression

We use the new expression to allocate either a single object:

Hello myProg = new Hello(); // () are necessary

or an array of objects:

messages = new string[ 4 ];

on the program's managed heap.

The name of a type follows the keyword new, which is followed by either a pair of parentheses (to indicate a single object) or a pair of brackets (to indicate an array object). We look at the allocation of a single reference object in Section 2.7 in the discussion of class constructors. For the rest of this section, we focus on the allocation of an array.

Unless we specify an initial value for each array element, each element of the array object is initialized to its default value. (The default value for numeric types is 0. For reference types, the default value is null.) To provide initial values for an array, we specify a comma-separated list of constant expressions within curly braces following the array dimension:

string[] m_message = new string[4]
{
   "Hi. Please enter your name: ",
   "Oops. Invalid name. Please try again: ",
   "Hmm. Wrong again! Is there a problem? Please retry: ",
   "Well, that's enough. Bailing out!",
};

int [] seq = new int[8]{ 1,1,2,3,5,8,13,21 };

The number of initial values must match the dimension length exactly. Too many or too few is flagged as an error:

int [] ia1;

ia1 = new int[128] { 1, 1 };  // error: too few
ia1 = new int[3]{ 1,1,2,3 };  // error: too many

We can leave the size of the dimension empty when providing an initialization list. The dimension is then calculated based on the number of actual values:

ia1 = new int[]{ 1,1,2,3,5,8 }; // OK: 6 elements

A shorthand notation for declaring local array objects allows us to leave out the explicit call to the new expression—for example,

string[] m_message =
{
   "Hi. Please enter your name: ",
   "Oops. Invalid name. Please try again: ",
   "Hmm. Wrong again! Is there a problem? Please retry: ",
   "Well, that's enough. Bailing out!",
};

int [] seq = { 1,1,2,3,5,8,13,21 };

Although string is a reference type, we don't allocate strings using the new expression. Rather, we initialize them using value type syntax—for example,

// a string object initialized to literal Pooh
string winnie = "Pooh";

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

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