Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entities—they remain the same length once they’re created.
Arrays are reference types.
The elements of an array can be either value or reference types (including other arrays).
An app refers to an array element with an array-access expression that includes the name of the array, followed by the index of the particular element in square brackets ([]
).
The first element in every array has index zero and is sometimes called the zeroth element.
An array’s Length
property returns the number of elements in the array.
To create an array instance, you specify the type and the number of array elements as part of an array-creation expression that uses keyword new, such as
int[] a = new int[12];
When an array is created, each element of the array receives a default value.
Every element of a value-type array contains a value of the array’s declared type. In an array of a reference type, every element is a reference to an object of the array’s declared type or null
.
An app can create an array and initialize its elements with an array initializer, which is a comma-separated list of expressions (called an initializer list) enclosed in braces.
Constants must be initialized when they’re declared and cannot be modified thereafter.
foreach
The foreach
statement iterates through the elements of an entire array or collection. The syntax of a foreach
statement is:
foreach (type identifier in arrayName)
{
statement
}
where type and identifier are the type and name of the iteration variable, and arrayName is the array through which to iterate.
The foreach
header can be read concisely as “for each iteration, assign the next element of the array to the iteration variable, then execute the following statement.”
The foreach
statement’s iteration variable can be used only to access array elements, not to modify them. Any attempt to change the value of the iteration variable in the body of a foreach
statement will cause a compilation error.
var
In a format item, a D
format specifier indicates that the value should be formatted as an integer, and the number after the D
indicates how many digits this formatted integer must contain.
The var
keyword declares a local variable and lets the compiler determine the variable’s type, based on the variable’s initializer. This process is known as type inference, and local variables declared in this manner are known as implicitly typed local variables.
The var
keyword cannot be used to declare an array that’s initialized via an initializer list—such initializers also can be used with collections, so the compiler cannot infer whether the variable should be an array or collection.
An exception indicates a problem that occurs while a program executes. ”
Exception handling enables you to create fault-tolerant programs that can resolve exceptions.
try
StatementTo handle an exception, place any code that might throw an exception in a try
statement.
The try
block contains the code that might throw an exception, and the catch
block contains the code that handles the exception if one occurs.
You can have many catch
blocks to handle different types of exceptions that might be thrown in the corresponding try
block.
When a try
block terminates, any variables declared in the try
block go out of scope.
catch
BlockA catch
block declares a type and an exception parameter. Inside the catch
block, you can use the parameter’s identifier to interact with a caught exception object.
When a program is executed, array element indices are checked for validity—all indices must be greater than or equal to 0 and less than the length of the array. If an attempt is made to use an invalid index to access an element, an IndexOutOfRangeException
exception occurs.
Message
Property of the Exception ParameterAn exception object’s Message
property returns the exception’s error message.
Card
and Getter-Only Auto-Implemented PropertiesPrior to C# 6 auto-implemented properties required both a get
and a set
accessor.
C# 6 supports getter-only auto-implemented properties that are read only.
Getter-only auto-implemented properties must be initialized either in their declarations or in all of the type’s constructors.
Initializing an auto-implemented property in its declaration is another C# 6 feature known as auto-property initializers.
The ToString
method of an object is called implicitly in many cases when the object is used where a string
is expected, such as concatenating an object to a string
.
When a method’s argument is an array or an individual array element of a reference type, the called method receives a copy of the reference. However, when an argument to a method is an individual array element of a value type, the called method receives a copy of the element’s value.
Two-dimensional arrays are often used to represent tables of values consisting of information arranged in rows and columns. To identify a particular table element, we must specify two indices.
C# supports two types of two-dimensional arrays—rectangular arrays and jagged arrays.
Rectangular arrays are used to represent tables of information in the form of rows and columns, where each row has the same number of columns.
Elements in rectangular array a
are identified by an expression of the form a[row, column]
.
A rectangular array could be declared and initialized with array initializers of the form
arrayType[,] arrayName = {{row0 initializer}, {row1 initializer}, …};
provided that each row of the rectangular array must have the same length.
A rectangular array can be created with an array-creation expression of the form
arrayType[,] arrayName = new arrayType[numRows, numColumns];
A jagged array is maintained as a one-dimensional array in which each element refers to a one-dimensional array.
The lengths of the rows in a jagged array need not be the same.
We can access the elements in a jagged array arrayName by an array-access expression of the form arrayName[
row][
column]
.
A jagged array can be declared and initialized in the form:
arrayType[][] arrayName = {new arrayType[] {r ow0 initializer},
new arrayType[] {row1 initializer}, …};
GradeBook
Using a Rectangular ArrayWhen the foreach
statement traverses a rectangular array’s elements, it looks at each element of the first row in order by index, then each element of the second row in order by index and so on.
A one-dimensional array parameter preceded by params
in a method’s parameter list indicates that the method receives a variable number of arguments with the type of the array’s elements.
The params
modifier can appear only in the last entry of the parameter list.
C# treats a variable-length argument list as a one-dimensional array.
When an app is executed from the Command Prompt, the execution environment passes the command-line arguments that appear after the app name to the app’s Main
method as string
s in a one-dimensional array.
When a reference-type object is passed with ref
, the called method actually gains control over the reference itself, allowing the called method to replace the original reference in the caller with a different object or even with null
.
If you encounter a situation where you truly want the called procedure to modify the caller’s reference, pass the reference-type parameter using keyword ref
—but such situations are rare.