C# Classes
C# Programming
Quincy College
Fall 2021
Robert I. Pitts
How arrays stored in C#
Creating new arrays and their elements
Processing elements of existing array
Built-in Array class
Accessing commandline arguments
Variable-length argument lists
Two-dimensional arrays
Fall 2021C# Programming 2
Arrays in C# are reference types hold elements of
same type
◦ Elements can also hold references to objects
◦ Access with subscript [i] (zero-based)
◦ Number of elements with Length property
Bounds checking
Fall 2021C# Programming 3
list [0] [1] [2]
: when index outside proper
range, generates IndexOutOfRangeException
Since arrays are reference types: create with new
int[] highTemps = new int[3];
Elements get default value (null if element type
is reference)
string[] colors = new string[samples];
Fall 2021C# Programming 4
Reference to hold address of array object
No strings objects,
just null refs
Provide array initializer
int[] highTemps = { 110, 80, 60 };
string[] colors = {
“red”, new string(‘0’, 6), “green” };
Assign array object later
highTemps = new int[] { 110, 80, 60 };
Assign element: highTemps[1] = 90;
Counting loop: create each element, read from
user/file, etc.
Fall 2021C# Programming 5
Counting loop
for (i = 0; i < arrayName.Length; i++)
… arrayName[i] …
Foreach loop
foreach (ElementType val in arrayName)
… val …
val is iteration variable takes on value of each
element in turn
May use var for implicitly-typed local variable
Cannot change elements stored in array via val
Fall 2021C# Programming 6
var
^
Question: When pass entire array?
When compare two array variables with ==?
◦ Answer: Tests if addresses same
Fall 2021C# Programming 7
array1 [0] [1] [2]
array2
array1 array2
(actual parameter)
(formal parameter)
Base class of arrays is Array
Many utility methods
// Create shallow copy of elements
int[] backup = (int[])orig.Clone();
Some are static methods
// Change size of arrayParam
Array.Resize(arrayParam, newSize);
Question: What would allow Resize method to
change array parameter?
Fall 2021C# Programming 8
ref arrayParam, newSize);
May generate 2 versions of C# program
◦ Debug: testing version
◦ Release: final distributable version
Command-line arguments: specified when run
program from terminal/command prompt
program.exe arg1 arg2 arg3
◦ Separated by spaces
Available to source code as argument of Main
public static void Main(string[] args)
Fall 2021C# Programming 9
May call same-name method with different # of
parameters
Deduct(1)
Deduct(2, 5)
params keyword allows variable number of
arguments stored in array
void Deduct(params int[] deductions)
{
foreach (var amt in deduction)
score -= amt;
}
◦ Must be last argument
Fall 2021C# Programming 10
(overloading, optional parameters)
For rectangular array, declare with dimensions
separated by comma
double[,] scores = new double[2, 3];
May provide initializer
char[,] ticTacToe = {
{'X', 'O', 'X' }, {…}, {…} };
Compiler determines dimensions (# values in
columns must be consistent)
Fall 2021C# Programming 11
0 1 2
0
1
scores
Access elements with 2 indices and comma in
one subscript operator
scores[studNum, hwNum] = 80.5;
foreach on rectangular array, goes through as
if 1D array (row by row)
foreach (double grade in scores)
Console.Write("score: {0}", grade);
Dimension size via GetLength(dim) method
◦ First dimension numbered zero
Fall 2021C# Programming 12
Can create by relying on 1D array capabilities
(array of arrays)
double[][] scores = new double[2][];
◦ Create each row (or instead via initializer list)
scores[0] = new double[3];
scores[1] = new double[2];
Fall 2021C# Programming 13
[0] [1]scores
[0] [1] [2]
[0] [1]
Access elements with 2 indices and 2 subscript
operators
scores[studNum][hwNum] = 80.5;
Use nested loop to go through rows, then
columns of 2D array
Question: Can use foreach or just for
counting loop?
◦ Answer: foreach also, but must be nested to go
through entire array
Fall 2021C# Programming 14
Arrays are reference types (created via new)
◦ If elements are references, must also create
objects stored in array with new
2 loops ideal to process array elements
◦ for: counter goes through indices of elements
◦ foreach: variable takes on each element value
2 types of multidimensional arrays
◦ Rectangular array created in one new operation
◦ Jagged array has top-level array with references to
arrays (requires multiple new operations)
Fall 2021C# Programming 15
Adding extra element to array so that may start
with index of 1
Overriding ToString() method
Shuffling array holding “playing cards”
◦ Fisher-Yates Algorithm for unbiased shuffling
Fall 2021C# Programming 16