- 1 A First C# Program
- 2 Namespaces
- 3 Alternative Forms of the Main() Function
- 4 Making a Statement
- 5 Opening a Text File for Reading and Writing
- 6 Formatting Output
- 7 The string Type
- 8 Local Objects
- 9 Value and Reference Types
- 10 The C# Array
- 11 The new Expression
- 12 Garbage Collection
- 13 Dynamic Arrays: The ArrayList Collection Class
- 14 The Unified Type System
- 15 Jagged Arrays
- 16 The Hashtable Container
- 17 Exception Handling
- 18 A Basic Language Handbook for C#
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 expressionfor 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 syntaxfor example,
// a string object initialized to literal Pooh string winnie = "Pooh";