0% found this document useful (0 votes)
34 views49 pages

Lect Note On Chapter 2 - Part I - Prog With Event Driven

Uploaded by

beshahashenafi32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views49 pages

Lect Note On Chapter 2 - Part I - Prog With Event Driven

Uploaded by

beshahashenafi32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Chapter 2:

Programming with Event Driven:


Using Data Types, Constants, and Variables
Making Statements in a Program
Working with Conditional Statements
Working with Loops
Working with Arrays
Working with Strings and Typecasting (see
string in a separate slide)
Using Data Types, Constants, and Variables
• C# offer a wide array/range of predefined data
types.
• Most of these data types are commonly found
in various language such as C, C++,VB, Java, etc
• Classified in to two: Value type and reference
type
• The distinction between the two type of data
type is important.
• Value type directly contain the data while ref
type contain a reference.
• Value type - simply contain the value
• Value type are simple or primitive data type
that are found in other languages like C++,
Java…
– int x = 20;
• With a reference-type variable, the system
allocates storage on the managed heap.
• The variable itself is a reference (or a pointer)
to the object on the heap.
• With a value-type variable, storage depends
upon the scope in which they are created.
– If a value-type is created in a method, then the
value-type object is stored on the stack.
– If it is a member of the class, then the object is
stored on the managed heap, but directly inside
the owning class.
– If a value type is a member of another value type,
its storage is in-line, wherever the owning struct is
being stored.
• Notice that the reference-type "refers" to an
object somewhere else in memory, namely,
the managed heap.
• On the other hand, value-type objects (in
most cases) are stored directly in the current,
working memory. (see more at the end of this
slide)
Data Type Keywords
• Because C# is strongly typed, all variables must be
declared before they can be used.
• .NET framework data types can be declared using
either the .NET framework type name or a C# keyword.
• For example, the following graphic shows how the
keyword int corresponds to the System.Int32 data
type.
C# common data type
.NET Variable
Keyword Framework Description Value Range Declaration
Type Example
System.Boolea Boolean type; a bool value is bool val1 = true;
bool true or false
n either true or false. bool val2 = false;

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;

System.Decim 128-bit fixed-point decimal decimal val =


decimal -7.9e28 to 7.9e28
al type with 28 significant digits 1.23M;
double val1 =
64-bit double-precision floating -1.79e308 to 1.23;
double System.Double
point type 1.79e308 double val2 =
4.56D;
32-bit single-precision floating -3.40e38 to
float System.Single float val = 1.23F;
point type 3.40e38
-2,147,483,648 to
int System.Int32 32-bit signed integral type int val = 12;
2,147,483,647
-
9,223,372,036,854,77
long val1 = 12;
long System.Int64 64-bit signed integral type 5,808 to
long val2 = 34L;
9,223,372,036,854,77
5,807
sbyte System.SByte 8-bit signed integral type -128 to 127 sbyte val = 12;
short System.Int16 16-bit signed integral type -32,768 to 32767 short val = 12;
Immutable string of 16-bit All valid string string val = "Hello
string System.String
Unicode characters characters world."
uint val1 = 12;
uint System.UInt32 32-bit unsigned integral type 0 to 4,294,967,296
uint val2 = 34U;
0 to
ulong val1 = 12;
ulong System.UInt64 64-bit unsigned integral type 18,446,744,073,709,5
ulong val4 = 78UL;
51,615
ushort System.UInt16 16-bit unsigned integral type 0 to 65535 ushort val1 = 12;
Be aware of the following special cases when
initializing data types:
• When initializing a char, use single quotes
surrounding the letter.
• When initializing a string, use double quotes
surrounding the text.
• When initializing a value that includes the decimal
point,
– For a decimal type, follow the number with the letter M.
– For a float type, follow the number with the letter F.
• Under other special circumstances, you might be
required to include letter values following the
numeric values for other data types.
Keep in mind the following facts when declaring and initializing variables:
• You can use either the C# keyword or the .NET Framework type to declare
data types. For example both of the following lines declare a 32-bit signed
integer variable named x, initialized to the value 5.
System.Int32 x = 5;
int x = 5;
• You can also declare a variable using the new keyword as follows:
– int x = new int();.
• This syntax declares the variable and initializes it with the default value (in
this case 0).
• Multiple variables can be declared and initialized on a single line.
– For example, int x = 5, y = 2, z; creates three signed integer variables:
– x which is initialized to a value of 5
– y which is initialized to a value of 2
– z which is not initialized.
• Class-level variables that are not explicitly assigned to are given a default
value of 0 (null for reference-types).
• Local variables must be assigned before they can be used (no default value
is given).
Conditional Statement
The following table describes three conditional blocks
available with C#.
Example Explanation

if blocks have the following characteristics:


if(x == 0)  The condition must evaluate to a boolean expression
FunctionA(); (true or false).
else if(y == 0)
{  When the condition is true, the block following the if
FunctionB(); statement (called the body) is executed. When the
FunctionC(); condition is false, the code block following the if block
} is executed (either an else block or the next block of
else if(z == 0)
{
code).
if(zz == 0)  Braces within the blocks are optional when the block
FunctionD();
includes a single statement.
}  if statements can be nested (or chained). When doing so,
else
FunctionE();
it can be difficult to distinguish where one code block
ends. Add braces to explicitly identify where each block
begins and ends.
switch(x)
{
case 1:
// code here
break;
case 2:
case 3:
case 4:
// code here
break;
case 5:
// code here
return;
case 6:
// code here
goto case 1;
default:
// code here
break;
}
Be aware of the following about switch statements:
 The parameter of the switch statement must be one of the following types:
o Integral, String , Enum
o User-defined type with exactly one implicit conversion to an integral type or string
 The body of a switch statement must be surrounded by braces.
 The body may contain zero or more case statements. Each case statement corresponds to exactly
one value.
 A case statement value must be compile-time constant (literal values or constants only).
 Control may only fall from one case statement to another if there is no code between the two
statements. In this example, cases 2, 3, and 4 execute the same code block.
 To prevent control from reaching the end of a case statement, use one of the following constructs
in each case block:
o break (the most common) sends control to the first statement after the switch body
o return returns from the current function
o throw throws an exception (branches to error handling code)
o goto branches to the specified labeled statement
 The body may contain one default statement. The default statement must appear after all the case
statements and must include a break or similar statement.
return ((x == 0) ? "Hello" : "Goodbye")

The ternary operator is used as shorthand notation for an if-else


construct. It is called ternary because it takes three operands.
 The conditional statement. Like an if-else statement, the
condition must evaluate to a boolean value and must be followed
by a question mark.
 The value to return if the condition is true (in this example, the
word "Hello").
 The value to return if the condition is false (in this example, the
word "Goodbye").
Iteration Statement Facts
• Iteration statements are used to create loops in the
flow of execution of a program.
• The body of an iteration statement is a single
statement or a code block.
• The test expression of every iteration statement,
except foreach, is a boolean expression.
• The following table describes the four iteration types
available with C#
The while statement repeatedly executes the body as long as the test expression
evaluates to true.
Example:
bool running = true;
while (running)
{
Console.WriteLine("Continue?");
running = !(Console.ReadLine() == "no");
}
The while loop is processed as follows:
1. The test expression is evaluated.
2. If the test expression is true, the body is executed. Otherwise, control
transfers out of the loop.
3. After the execution of the body, the test expression is evaluated again.
Note: Because the condition is evaluated before the execution of the loop, the
body of the loop may be executed zero or more times.
The do statement executes the body at least once, and repeats
execution of the body as long as the test expression evaluates to
true.
Example:
bool running = false;
do
{
Console.WriteLine("Continue?");
running = !(Console.ReadLine() == "no");
}
while (running);
The do loop is processed as follows:
1. The body is executed.
2. The test expression is evaluated.
3. If the expression is true, the body is executed again. Otherwise,
control transfers out of the loop.
Note: Because the condition is evaluated after the execution of the
loop, the body of the loop will always be executed at least once.
The for statement contains the following items
 An initialization statement (such as a counter initialization). You can have multiple initialization statements,
each separated by commas.
 A test expression that evaluates to a true/false.
 One or more iteration expressions (with multiple statements, separate each statement with a comma).
 A body.
Example:
int limit = 16;
for( int i = 1; i <= limit; ++i )
{
i += i;
Console.WriteLine("{0} ", i);
}
// Output:
// 2 6 14 30
The for loop is processed as follows:
1. The initialization statement(s) is executed.
2. The test expression is evaluated.
3. If the condition is true, the body is executed. Otherwise, control transfers out of the loop.
4. The iteration expression(s) is/are executed and then the test expression is evaluated again.
Note: The initialization statement, test expression, and iteration expressions are optional. If the test expression is
omitted, the test expression defaults to true.
The foreach statement iterates through an array or a collection. The foreach block includes:
 A local variable, declared as the same type of the objects in the array or collection.
 An array or collection that will be analyzed.
Example:
int[] numbers = {1,4,9,16};
foreach( int i in numbers )
{
Console.WriteLine(" {0}", i);
}
// Output:
// 1 4 9 16
The foreach loop is processed as follows:
1. The block assigns the first element to the local variable (in this example, i).
2. Execute the body.
3. If all elements have been iterated over, exit the loop. Otherwise, assign the next variable in the
collection to the local variable and repeat the code body.
Notes: The foreach block automatically goes through each element in the array or collection. You do
not need to create and increment a counter manually.
The iteration variable declared within the foreach statement is read-only.
You should not change the array or collection while inside a foreach body.
There are two statements that allow you to control the
execution of a loop from within the body: continue and
break.
Construct Explanation Example

Transfers execution to while(true) // control transfers here


{
the test expression
continue continue;
evaluation or the next // code here will never be reached
iteration in a foreach. }

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:

• When you are finished, run the program and


click the button to verify your work
ArrayList
• An ArrayList is a dynamically-sized array of
elements stored in contiguous memory.
• Following is an example of using an ArrayList:
• ArrayList al = new ArrayList();
• // No elements to access yet
• // al[0] = "hello"; // this will thrown an exception
• // add three elements
• al.Add("Hello World");
• al.Add(100);
• al.Add(3.14159265);
• Be aware of the following facts about using an ArrayList:
• Like using normal arrays, items in an ArrayList can be accessed by using
the index number.
• When you try to access an index position that does not yet hold data,
an IndexOutOfBoundsException is thrown.
• Use the Add method to add items to the ArrayList.
• An ArrayList is an ordered collection. That is, elements placed in an
ArrayList are stored in the order in which they are added to the
ArrayList.
• Whereas a normal array can only hold elements of the same type, an
ArrayList can hold data of multiple types. The example shown here adds
a string, and int, and a double to the same ArrayList.
• The ArrayList resizes automatically to hold all items added to it. The
default initial capacity is 16. If an ArrayList is full and one more element
is added to it, the ArrayList must be resized. To do this, enough space is
allocated for double its capacity, then it copies all of its elements into
the new space. Be aware that this reallocation can take some time. It is
wise to set the capacity to a reasonable size when creating the ArrayList
to prevent resizing.
• When you access an element you must cast it
to its derived type. For example, the following
line gets index item 2, identifying it as a
double type:
– MessageBox.show( ((double)al[2]).ToString() );
The following table lists common methods for working with ArrayLists.
Method Description
ArrayList.Add(object obj) Appends an element to the end of the ArrayList.
ArrayList.AddRange(ICollection c) Appends a collection of elements to the end of the ArrayList.
Inserts an element in the position indicated. Insert must move (copy) all subsequent
ArrayList.Insert(int index, object obj)
elements.
Inserts a collection of elements in the position indicated. All subsequent elements
ArrayList.InsertRange(int index, ICollection c)
must be moved.
ArrayList.Remove(object obj) Removes the first occurrence of obj.
ArrayList.RemoveAt(int index) Removes the element at the index indicated.
ArrayList.RemoveRange(int index, int count) Removes elements of a specific type (in this example int) beginning at index position.
ArrayList.Clear( ) Removes all the elements from the ArrayList.
ArrayList.GetRange(int index, int count) Returns a new ArrayList containing the elements from index for count.
ArrayList.ToArray( ) Builds a System.Array out of the ArrayList.
ArrayList.Clone( ) Makes an exact (shallow) copy of the ArrayList.
ArrayList.Contains(object item) Indicates whether the array list contains item. Performs a linear search.

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

You might also like