Lect Note On Chapter 2 - Part I - Prog With Event Driven
Lect Note On Chapter 2 - Part I - Prog With Event Driven
byte System.Byte 8-bit unsigned integral type 0 to 255 byte val1 = 12;
char c = ‘a’;
char System.Char 16-bit unicode character 0 to 65535
char c = 255;
while(true)
{
break;
Transfers execution out
break // code here will never be reached
of the loop. }
// control transfers here
• Note: Loops that test for a boolean condition
must include some mechanism within the
body for setting the expression to false.
• If the condition always evaluates to true, the
result will be an infinite loop.
• Following are some examples of code that
result in an infinite loop:
– while(true) { }
– for(;;) { }
– do{}while(true);
Working With Arrays
• As you study this section, answer the following questions:
• Which array type is equivalent to a table with columns and
rows?
• Which array type is a collection of objects?
• What number is used to access the first element in an array?
• What type of values can be stored in an array? Can an array
hold more than one type of value?
Declare and initialize single- and multiple-dimension arrays.
Array Facts
• Arrays are reference-type objects that hold a
set of related data, much like a list of data or a
table.
• The following table describes two simple array
types.
• All elements in an array must be of the same
type.
• When you declare an array, you begin by
defining the data type, the number of
elements in the array, and the array name.
• The following table compares various methods
for declaring and initializing arrays.
• Array elements are referenced using a 0-based
numbering system and accessed by identifying
the array element index number(s). This means
that:
– The first element index is 0.
– The index of last element is the total number of
elements minus one.
• The following lines show examples of
referencing an array element:
– // gets the first element in array1
– int x = array1[0];
– // gets the second element in the first row of array2
– int y = array2[0,1];
• Keep in mind the following facts about arrays:
– Arrays are reference-type objects (even if they hold value-types).
– Arrays are not pointers into memory (like C++).
– The array can be declared as any type (even a reference type).
– All elements of an array must be of (or inherit from) the same type.
– Element access in an array is zero-based. The first element has an
index number of 0.
– All rows in a rectangular array must be of the same size.
– Rectangular arrays can be of any dimension (2, 3, 4, or more).
– Arrays are bounds-checked, meaning that you cannot access
elements outside of the array. Attempts to access elements outside
of the bounds of the array will result in a runtime error (called an
exception).
Jagged Arrays
• A jagged array is a multi-dimensional array
where each row can have a different number
of elements.
• A jagged array is really an array of array
references.
• Storage of jagged arrays is different than
single-dimensional and rectangular arrays.
• The following example shows one way to
declare and initialize a jagged array:
– int[][] array1 = new int[3][] {new int[3]{1,2,3}, new
int[4]{4,5,6,7}, new int[5]{8,9,10,11,12}};
• Be aware of the following when working with
jagged arrays:
– Use brackets [ ] to identify the number of array
elements within the jagged array.
– When creating the array object, only the size of
the first rank can be specified when the array is
created
Exercise
1. Create a window application and complete the following
tasks:
– Declare a single-dimensional array called myArray of integer
type.
– Initialize the array with the values 1, 3, 17 (in that order).
• When you are finished, run the program and click the
Show Array button. The text box should then contain a list
of the array contents.
2. Create a window application and complete the following
tasks:
– Declare a multi-dimensional array called MArray as integer type
– Give the array 3 rows and 4 columns
– Initialize the array cells with numbers 1 through 12 (reading
left-to-right, top-to-bottom)
• When you are done, you should have
constructed a simple table as follows:
Returns the index of the first occurrence of item in the ArrayList. Returns -1 if the
ArrayList.IndexOf(object item)
item is not found.
Returns the index of the first occurrence of item in the ArrayList after start. Use this
ArrayList.IndexOf(object item, int start)
to search for all occurrences of an element sequentially.
ArrayList.Reverse( ) Reverses the elements in the ArrayList.
ArrayList.Sort( ) Sorts the ArrayList. Requires that all members implement the IComparable interface.
Exercise
• Crate an application to manage student activity scores. Each student is
represented by an instance of the Student class. The class includes the
following fields:
• The name field holds the student name. You can get the student name
through the Name property.
• The activities field is an ArrayList that holds a collection of Activity objects.
• The Activity class includes the following fields:
• The name field holds the name of the activity. You can get the name through
the Name property.
• The score field holds the score the student received on the activity. You can
get the score through the Score property.
• You need to write the code to accomplish the following tasks:
• Add a new activity and its score to the collection of activities for a student.
• Remove an activity from the list of activities for a selected student.
• Return the average of scores for all activities for a selected student.
Edit the code in the Student.cs file to do the following:
• Create a public AddActivity method in the Student class that returns void and takes
two parameters: a string that passes the student name, and an int that passes the
score.
• Add code to the AddActivity method to create a new Activity object using the name
and the score and adding the object to the activities ArrayList object.
• Create a public RemoveActivity method in the Student class that returns void and
takes one parameter of int type that identifies an index number in the activities
ArrayList object.
• Add code in the RemoveActivity method to remove the object in the activities
ArrayList as specified by the index number.
• Create a public read-only AverageScore property that returns a value of type
double. The property should calculate the value by adding all the Activity Scores in
the activities ArrayList object and dividing by the number of activities in the
ArrayList to produce an average score.
• Run the test program to verify your code. Select a student name to show the
student's score. Enter activity information and click Add to add an activity. Select
an activity and click Remove to remove the activity.
Typecasting
Data Conversion Facts
• A data type conversion enables an expression of one
type to be treated as another type. For
• example:
– byte b = 100;
– int x = b;
• In this code segment x expects an int-type value to be
assigned to it but receives a byte value instead.
• The byte value of b is converted to an int so that it
can be stored in the integer x.
• There are two ways that type conversions can
happen: implicitly and explicitly.
• Explicitly converting from one data type to another is done by using a cast (or casting
expression).
• In C# there are two casting operators.
• When you explicitly convert data from one type to another, be aware that data loss can
occur. (see further in the supporting document)
Remember the following facts about data type conversions
– Implicit conversion happens automatically; explicit conversion
requires a casting expression.
– You may cast when an implicit conversion is defined, but it is
not necessary.
– Forgetting to cast when it is required (during an explicit
conversion) will generate a compiler error. In other words, one
way to remember when casting is required is to compile your
code. The compiler will identify each instance when a cast is
required.
– When casting from a larger type to a smaller type, the high-
order information is truncated.
– When casting from a higher precision type to a lower precision
type, the precision information is truncated.
– Converting between signed and unsigned types of the same
size is explicit and requires a cast.
– Data type conversions might result in runtime errors if not
handled properly.
Reference-Type Conversions
• Reference-type conversions happen when either
the initial type or the target type (or both) is a
reference-type object.
• The .NET framework includes code that can
convert between many value and reference
types.
• In addition, you can write your own code to
convert between reference types that you create.
• For example, your code can define two classes,
and you can add code which converts an instance
of one class into an instance of the other class.
Reference-type conversions can happen implicitly or explicitly.
• When a value-type is converted to a reference-type, a
special conversion operation called boxing occurs. For
example, the following code converts a value-type to a
reference-type:
– int x = 100;
– object obj = x;
• Reference-types, by definition, store a reference to an
object on the managed heap. Value-types, on the other
hand, store their data directly as shown in the following
graphic:
• When a value-type is converted to a reference-
type, a copy of the value-type value is boxed and
placed on the heap as shown in the following
graphic:
• The following events occur during a boxing operation:
– Space is allocated on the managed heap for the value.
– The value is copied to the newly allocated space (note that it
is a copy).
– The reference is set to the address on the managed heap.
• The act of casting a boxed value into a value-type
variable is called unboxing. Unboxing is an explicit
conversion and requires a cast. The following example
shows how to unbox a boxed value.
– object obj = 100;
– int x = (int)obj;
End of Chapter Two