80 likes | 190 Vues
A Brief Introduction to C# Arrays. Chapter 10. 1. Objectives. You will be able to: Use arrays correctly in your C# programs. 2. Creating Arrays. In C#, arrays are reference types . Declaration does not allocate memory for the array. (Just for a reference.) You don’t declare the size.
E N D
A Brief Introduction to C# Arrays Chapter 10 1
Objectives You will be able to: • Use arrays correctly in your C# programs 2
Creating Arrays In C#, arrays are reference types. Declaration does not allocate memory for the array. (Just for a reference.) You don’t declare the size. int[ ] ID; Compare C: int ID[2000]; 3
Creating Arrays You must instantiate an array with “new”. my_ints = new int[2000]; The variable my_ints is a reference If a local variable, allocated on the stack If a member variable, allocated as part of the object of which it is a member (on the heap) The actual array is allocated on the heap. 4
Array Initialization By default, array elements are initialized the same as class member variables: • All numeric types 0 • Enumerations 0 (even if not a valid value) • bool false • References null • structs Apply above rules to members. 5
Array Initialization You can specify inital values with the instantiation: int[ ] id = new int [4] {9, 3, 7, 2}; The number of values supplied must match the array size. Initial values do not have to be compile time constants. 6
Array Initialization If you provide an initializer, you may omit the size int[ ] id = new int [ ] {9, 3, 7, 2}; or even int[ ] id = {9, 3, 7, 2}; 7
Accessing Array Elements • Index values run from 0 to N-1 • (Like C) • Unlike C, using an invalid index results in an exception. int[ ] id = new int [4] {9, 3, 7, 2}; int i; i = id[4]; // This throws an IndexOutOfRange exception. 8