You are on page 1of 110

INSTRUCTIONAL MATERIALS IN

20093 ADVANCE PROGRAMMING

COMPILED BY
PROF. JHUNEL B. PEÑAFLORIDA
OVERVIEW

The course aims to teach a high-level programming language that is beneficial to a variety
of real-world applications. It introduces the advanced topics of the selected language as well as
its properties. It will also involve development of several applications, case studies and exercises.
During the second half of the semester, students work in teams to build a mid-scale software
application based on the needs of a specific client.

Each team presents the final project, sharing how course concepts were applied to
address unique client needs. The concepts and skills learned in this course are transferable to a
wide variety of contemporary programming languages and software development tools.

i
ii
TABLE OF CONTENTS
OVERVIEW .......................................................................................................................................i
TABLE OF CONTENTS................................................................................................................... ii
COURSE OUTCOMES ................................................................................................................... iii
LESSON 1 INTRODUCTION TO C# .............................................................................................. 1
LESSON 2 REVIEW OF STATEMENTS AND EXCEPTIONS ...................................................... 8
LESSON 3 REVIEW OF ARRAYS AND INTRODUCTION OF INDEXERS ............................... 26
LESSON 4 REVIEW OF METHODS AND PARAMETERS ......................................................... 36
LESSON 5 OBJECT-ORIENTED PROGRAMMING CONCEPTS .............................................. 48
LESSON 6 INHERITANCE ........................................................................................................... 64
LESSON 7 VIRTUAL METHODS AND POLYMORPHISM ......................................................... 76
LESSON 8 INTERFACES ............................................................................................................ 84
LESSON 9 ADVANCED WINDOW APPLICATION ..................................................................... 89
LESSON 10 DATA CONNECTION .............................................................................................. 96
GRADING SYSTEM ................................................................................................................... 104
REFERENCES ........................................................................................................................... 105
iii
COURSE OUTCOMES

After successful completion of the course you should be able to:

1. The students are expected to implement flow control, looping and exception handling.
2. Create methods, functions and subroutines that take return values and take parameters.
3. Create, initialize and use arrays.
4. Use the common objects and reference types.
5. Create windows applications using forms, control and event handling.
6. Understand and use graphics and multimedia.
7. Create, read from, write to, and update data files.
8. Access Relational Databases using Structured Query Language.
9. Develop web applications using ASP.NET Web Forms and web controls.
1
LESSON 1
INTRODUCTION TO C#

Learning Outcomes

After successful completion of the lesson you should be able to:


1. Comprehend the C# Programming Language.
2. Learn the Program Architecture of C# Program.
3. Use variables and operators in a program
4. Demonstrate the ability to perform the basic input and output.

Course Materials

1.1 Introduction to C#

C# is an object-oriented programming language. The fundamental architectural element


of a program is a class, and from a programmer’s perspective is a C# program a family of classes,
that collectively define all the application’s properties and functionality. Writing a program is thus
to define – design – and write the code for the program’s classes. Nothing in C# exists outside a
class. A program will also operate by many other classes that are not written by the programmer,
but classes that are coming from the .NET framework, and thus is available to the programmer
as finished components.

Example: Hello World

using System;
namespace HelloWorld
{
class Program
{
static void Main(string[]args)
{
Console.WriteLine("Hello World!")
}
}
}

The program runs in a command window (prompt), where it prints the text Hello World on
the screen. The program is not doing much, but it is a full-fledged program.
The above example shows in principle the overall architecture of a C# program which is a
class that has a Main() method as a starting point.

1.2 Running a C# Program

1. Make sure you downloaded an installed the Visual Studio properly.


2. Open Visual Studio and choose File | New | Project from the menu show below.
2

1.3 Program Architecture

The program below has several statements and methods. This shows how a method is
called and written in C#. These methods are important for many reasons but basically to subdivide
the code into more manageable parts.

Example: Printing a book

using System;
namespace Example02
{
class Program
{
static void Main(string[]args)
{
Title();
More();
}

private static void Title()


{
Console.WriteLine("Introduction to Programming with C#");
Console.WriteLine("Paul Klousen");
Console.WriteLine("bookboon.com");
Console.WriteLine("ISBN : 978-87-403-0250-9");
}
private static void More()
3
{
Console.WriteLine("2. Edition")
Console.WriteLine("Published 2012")
Console.WriteLine9("205 pages")
}
}
}

Code Explanation: This works like the example provided in the previous section. The methods
Title() and More() are create with print statement inside each block and they are called in the
Main() method.

A method has a form as follows:

private static void MethodName()


{
//Statement
}

1.4 Variables

Applications must process data and to do this, they need a way to save or store the data. These
programs have variables which may have or may store a value. A variable is characterized by:

• a name
• a type
• operators

Variables must have a name so you can refer to them in the program. C# is similar to other modern
programming languages relatively flexible in regard to the naming of variables but should be
complied with:

• the name of a variable should always start with a small letter


• then there may follow any number of characters consisting of letters and digits
• a name must not contain spaces.

Variables must be created or declared before they can be used. This is done by a statement of
the form:

type name = value

First you write the type, then the variable name, and finally assigned it a value, for example:

int number = 23;


4
C# built-in or simple data types

Type Description Value Notations


bool Boolean true, false
char 16 bit Unicode character ‘A’, ‘\x0041’, ‘\u0041’
sbyte 8 bit signed inter
byte 8 bit unsigned integer
short 16 bit signed integer
ushort 16 bit unsigned
int 32 bit signed integer
uint 32 bit unsigned integer Suffix: U
long 64 bit signed integer Suffix: L/l
ulong 64 bit unsigned integer Suffix: U/u eller L/l
float 32 bit floating-point number Suffix: F/f
double 64 bit floating –point number Suffix: D/d
decimal 96 bit decimal number Suffix: M/m
string Character string (text) C:\\test.txt”, @”C:\test.txt”

Example: Adding two numbers with variables.

using System;

namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
int num1 = 17;
int num2 = 23;

int sum = num1 + num2;

Console.WriteLine(" The sum of " + num1 + " and " + num2 + " is "
+ sum);
Console.ReadKey();
}
}
}
Note: ReadKey() Method makes the program wait for a key press and it prevents the screen until
a key is pressed. In short, it obtains the next character or any key pressed by the user.
When the above code is executed it produces the following result.
5

Explanation:

First, the program declares two variables num1 and num2 that are initialized respectively
with 17 and 23. The type is int, which means that the two variables may contain integer values.
They are local variables, as they are created in the Main(), and they are only known in the Main()
method. Then the sum of the two variables is stored in the variable sum. Note that the value
stored in sum, is the result of an expression. WriteLine() writes the result. In this case, it builds a
string from a number of parts or elements. Note that the individual elements are separated by +
which here means string concatenating, and integer values automatically are converted to a
string.

1. 5 Operators

C# has the following operators in order of priority, and with decreasing priority downwards:

Operators
() . [] function(...) new typeof sizeof checked unchecked
+ - ! ~ ++ -- (unary operatorer)
*/%
+-
<< >>
< > <= >= is as
== !=
&
^
|
&&
||
?:
= *= /= %= += -= <<= >>= &= ^= |=

1.6 Input and Output

Get the User Input

In the previous lesson, you have learned the Console.WriteLine() to output or print
values. Now we will use the Console.ReadLine() to get user input.

Example:

namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
//Displays a command to input the name
Console.WriteLine("Enter your name: ");
6

//variable name is initialized to ask keyboard input.


string name = Console.ReadLine();

//Print the value stored in variable name

Console.WriteLine("Your name is: " + name);


Console.ReadKey();
}

}
}

When the above code is executed it displays the input of the user in console.

User Input and Numbers

The Console.ReadLine() method returns a string. Therefore, you cannot get


information from another data type, such as int. The following program will cause an error:

Example:

Console.WriteLine("Enter your age:");


int age = Console.ReadLine();
Console.WriteLine("Your age is: " + age);

When the above code is executed it displays an error message Cannot implicitly
convert type 'string' to 'int'.

To address this situation, the type casting is used by convert any type explicitly, by using
one of the Convert.To methods:

1.7 Type Conversion Method

It is also possible to convert data types explicitly by using built-in methods, such as
Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int)
and Convert.ToInt64 (long):

Example:

using System;

namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
7
Console.WriteLine("Enter your name");
string name = Console.ReadLine();

Console.WriteLine("Enter your age:");


int age = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Your name is: " + name + " and you are " + age
+ " years old");
Console.ReadKey();
}

}
}

Notice that the use of conversion method Convert.ToInt32 to convert the string age because
by default the Console.ReadLine(); returns a string.

Activities/Assessments

All class assignments and activities should be submitted via google classroom website on
or before the due date. The solutions to the programming problems must include full working
code, not just an output of your program.

1. What is C# programming language and cite its uses?


2. Write a simple program architecture of C# with methods called inside the main function.
3. Create a program to find the perimeter and area of a circle.
4. Create a program that ask the user to input the in all subjects and perform operation. The
value returned must be in a double format.
8
LESSON 2
REVIEW OF STATEMENTS AND EXCEPTIONS

Learning Outcomes

After successful completion of the lesson you should be able to:


1. Identify the different Selection Statements.
2. Identify the different Iteration Statements.
3. Describe the for each.
4. Describe the uses of Jump Statements.
5. Demonstrate the ability to use the Control Statements and Exceptions in Machine
Problem.

Course Materials

2.1 Control Statements

In the previous examples, the programs run sequentially this time. We will understand
when we want to execute a statement depending on condition such as:

Example: If there is enough money in the bank account, give the money.

We want to execute one statement when a condition holds and another statement when
a condition does not hold.

Example: If dollar is high, sell dollar. Otherwise, buy dollar.

We want to select from many statements according to one or more criteria (selection).

Example: If dollar is high and euro is low, sell dollar and buy euro. If dollar is low and euro is high,
sell euro and buy dollar. If both of them are high, sell both and buy YTL. The conditional execution
can be achieved using the if-else statements.

2.1.1 If Statements

If the condition is true, then the block (the block’s statements) inside the if is executed.
Otherwise, nothing happens.

A condition is an expression whose value is a bool and hence an expression that is true
or false. If only a single statement has to be controlled by a condition, you must omit the
parentheses and simply write:

if (condition) statement;
9
Example:
using System;

namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{

Console.WriteLine("Enter your age: ");


int age = Convert.ToInt32(Console.ReadLine());

if (age >= 18)

Console.WriteLine("You are voter!");


Console.ReadKey();

}
}

2.1.2 Switch Statement

With the switch/case conditional statement, we can simplify some of the tasks that are
long and cumbersome when we use the ladderized if else if. This is substitute in writing concise
and clearer multi-way decision program. However, it has a limitation it cannot test or evaluate
floating point and string values or variables. This means that only those variables that are declared
as integer or character are the candidates that can be tested or evaluated by the switch/case
conditional statement.

Example

using System;

namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{

Console.WriteLine("Enter the day number in a week");

string text = Console.ReadLine();

switch (Convert.ToInt32(text))
10
{
case 1:
Console.WriteLine("Monday");
break;

case 2:
Console.WriteLine("Tuesday");
break;

case 3:
Console.WriteLine("Wednesday");
break;

case 4:
Console.WriteLine("Thursday");
break;

case 5:
Console.WriteLine("Friday");
break;

case 6:
Console.WriteLine("Saturday");
break;

case 7:
Console.WriteLine("Sunday");
break;

}
Console.ReadKey();

}
}

2.2 Using Iteration Statements

The while, for and do are control structures for loops or iterations,

2.2.1 While Loop

It is often needed to carry out a statement or a block several times until a condition occurs.
Here you can use a while statement, which has the following form:

while (condition)
block
11
The significance is that the block and its statements are performed as long as the condition
after while is true. Then the program continues with the next statement after the while construct.

Example

The sum of positive integers less than 100.

using System;

namespace ConsoleApplication
{
class Program

{
const int N = 100; //declared as constant and global variable.

static void Main(string[] args)


{

long s = 0;

int n = 1;

while (n <= N)
{
s +=n;
++n; //Incrementing
}
Console.WriteLine("The value is " + s);
Console.ReadKey();

}
}

Explanation

const int N = 100; - is a constant, which is the largest number to be included.

Note the algorithm. First define a variable s to the result. Next, define a variable n to the number
to be added to the sum and initialize it to 1, which is the first number. Then repeat the subsequent
block as long as n is less than or equal to 100 (the constant N). In the block two things happens:
The value of the variable n is added to s and n is incremented by 1. Note that the last statement
means that n is 1 more for each repetition, and thus the condition for the while, sooner or later
becomes false.
12
2.2.2 For Loop

The for statement has three parts separated by semicolons: initialization, condition and
expression:

for (initialization; condition; expression)


block;

Each of the three parts of the for statement can actually be empty. When the statement is
carried out, the following occurs:

1. Perform the initialization part (if there is one).


2. Test whether the condition is true (if the condition is empty it is true).
3. If the condition is true executes the following block
4. Otherwise the for statement is interrupted
5. Execute the expression part
6. Continue with step 2

Example

using System;

namespace ConsoleApplication
{
class Program

{
const int N = 100; //declared as constant and global variable.

static void Main(string[] args)


{

long s = 0; for (int i = 1; i <= N; ++i)


{
s += i;
Console.WriteLine(s);
}

Console.ReadKey();

}
}

If the initialization expression declares the control variable, the control variable will not
exist outside the for statement. This restriction is known as the variable’s scope. Similarly, a
local variable can be used only in the method that declares the variable and only from the point
of declaration.
13
2.2.3 Do While Loop

It is similar to while loop, but the test is after the execution of the loop body. The while loop may
never execute, do-while loop executes at least once.

Syntax

do
{
<statement1>

}
while(condition)

The significance is that the statements in the block are performed and then the condition
is tested. Is it true, repeat the block and it continues until the condition becomes false. Compared
with the while statement is the difference that do always will perform the block at least once, since
the condition is first tested after the block is executed. The do loop is not used as often as the
other loops.

Example

using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


{
int num = 0;

do
{
Console.WriteLine("Number = {0}", num);
num++;
} while (num <= 10);

Console.ReadKey();
}

}
}
14
2.2.4 foreach Loop

C# provides an easy to use and more readable alternative to for loop, the foreach loop
when working with arrays and collections to iterate through the items of arrays/collections. The
foreach loop iterates through each item, hence called foreach loop.

Syntax

foreach (element in iterable-item)


{
// body of foreach loop
}

How foreach loop works


15
Example

using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


{
char[] myArray = { 'H', 'e', 'l', 'l', 'o' };

foreach (char ch in myArray)


{
Console.WriteLine(ch);
}
Console.ReadKey();
}

}
}

The in keyword used along with foreach loop is used to iterate over the iterable-item.
The in keyword selects an item from the iterable-item on each iteration and store it in the
variable element.

On first iteration, the first item of iterable-item is stored in element. On second iteration,
the second element is selected and so on.

The number of times the foreach loop will execute is equal to the number of elements in
the array or collection.

2.3 Using Jump Statements

The break, goto, continue, return and throw statements are known as jump statements.
These are used to transfer program control from one point in the program to another point, at any
time.

2.3.1 The break Statement

This statement terminates the execution of loop or switch in which it appears and transfers
program control to the next statement which is placed immediately after the loop or switch
16
Example

using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


{
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
break;
}
Console.WriteLine(i);
}
Console.ReadKey();
}

}
}

Notice that the program jumps out of the loop when the variable i == 4. Try changing the values
and see what happens.

2.3.2 goto Statements

This statement transfers program control to a labeled statement. The label statement must
exist in the scope of the goto statement. More than one goto statement can transfer control to the
same label. This statement can be used to get out from a loop or an inner nested loop to outer
loop.

Example

using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


{
17
ineligible:

Console.WriteLine("You are not eligible to vote!");

Console.WriteLine("Enter your age:\n");


int age = Convert.ToInt32(Console.ReadLine());
if (age < 18)
{
goto ineligible;
}
else
{
Console.WriteLine("You are eligible to vote!");
}
Console.ReadKey();
}

}
}

Notice that when condition inside the if statement is true then the program executed the goto
statement and jumps to its label.

2.3.3 continue Statement

This statement skips the current iteration and passes program control to the next iteration
of the enclosing loop in which it appears. The continue statement breaks one iteration (in the
loop), if a specified condition occurs, and continues with the next iteration in the loop.

Example

using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


{
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
Console.WriteLine(i);
}
18

Console.ReadKey();
}

}
}

The program above skips the value of four and continue iterating until the condition is met
in the for loop statement.

Example: Using the break in while loop.

using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


{
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i++;
if (i == 4)
{
break;
}
}

Console.ReadKey();
}

}
}

Example: Using the continue in a while loop

using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


19
{
int i = 0;
while (i < 10)
{
if (i == 4)
{
i++;
continue;
}
Console.WriteLine(i);
i++;
}
Console.ReadKey();
}

}
}

2.3 Handling Basic Exceptions

An exception is a problem that arises during the execution of a program. A C# exception


is a response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C#
exception handling is built upon four keywords: try, catch, finally, and throw.

2.3.1 Try and Catch

A try block identifies a block of code for which particular exceptions is activated. It is
followed by one or more catch blocks.

Assuming a block raises an exception, a method catches an exception using a


combination of the try and catch keywords. A try/catch block is placed around the code that might
generate an exception. Code within a try/catch block is referred to as protected code.

Syntax

try
{
//Statements
}
catch(Exception e1)
{
//Error Handling code
}

catch(Exception e2)
{
20
//Error Handling code
}

catch(Exception e2)
{
//Error Handling code
}

finally
{
//statements to be executed
}

Example

using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


{
try
{
int[] myNumbers = { 1, 2, 3 };
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey();
}

}
}

If an error occurs, we can use try...catch to catch the error and execute some code
to handle it.

In the following example, we use the variable inside the catch block (e) together with the
built-in Message property, which outputs a message that describes the exception.

You can also output or display your own error. Below is an example.
21
using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


{
try
{
int[] myNumbers = { 1, 2, 3 };
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine("Something went wrong.");
}
Console.ReadKey();
}

}
}

2.3.2 Finally

The finally statement lets you execute code, after try...catch, regardless of the result:

Example

using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


{
try
{
int[] myNumbers = { 1, 2, 3 };
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine("Something went wrong.");
22
}
finally
{
Console.WriteLine("The 'try catch' is finished.");
}

Console.ReadKey();
}

}
}

2.3.3 The throw Keyword

The throw statement allows you to create a custom error. The throw statement is used together
with an exception class. There are many exception classes available in C#:
ArithmeticException, FileNotFoundException, IndexOutOfRangeException,
TimeOutException, etc:

Example

using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


{

try
{

GetDetails();

catch (Exception ex)


{

Console.WriteLine(ex.Message);

Console.ReadLine();

}
23

private static void GetDetails()


{

string name = null;

if (string.IsNullOrEmpty(name))
{

throw new NullReferenceException("Name is Empty");

else
{

Console.WriteLine("Name: " + name);

}
}

The Exception Classes in C#

C# exceptions are represented by classes. The exception classes in C# are mainly directly
or indirectly derived from the System.Exception class. Some of the exception classes derived
from the System.Exception class are the System.ApplicationException and
System.SystemException classes.

The following are the predefined exception classes.

Exception Class & Description

System.IO.IOException Handles I/O errors.


System.IndexOutOfRangeException Handles errors generated when a method refers to
an array index out of range.
System.ArrayTypeMismatchException Handles errors generated when type is mismatched
with the array type.
System.NullReferenceException Handles errors generated from referencing a null
object.
System.DivideByZeroException Handles errors generated from dividing a dividend
with zero.
24
System.InvalidCastException Handles errors generated during typecasting.

System.OutOfMemoryException Handles errors generated from insufficient free


memory.
System.StackOverflowException Handles errors generated from stack overflow.

Activities/Assessments

All class assignments and activities should be submitted via google classroom website on
or before the due date. The solutions to the programming problems must include full working
code, not just an output of your program.

1. Identify different selection statements and their uses?


2. Identify the different iterations statement and provide your own example on their usage.
3. Describe how foreach statement is used.
4. Identify the different jumping statements and how they are used in a program.
5. Machine Problems

a. if-else statement

Write a program that determines whether a given letter is a vowel or consonant.


Apply Exception Handling when the user enters a numerical or floating value.

b. Switch/case statement
Write a program that displays an equivalent color once an input letter matches its first
character. For example, b for Blue, r for Red, and so on. Here is the given criteria:

Letters Colors
‘B’ or ‘b’ Blue
‘R’ or ‘r’ Red
‘G’ or ‘g’ Green
‘Y’ or ‘y’ Yellow
Other letters Unknown Color
25
c. Looping

Write a program that calculates and produces these two columns sequence
numbers using the three looping statements.

Sequence Nos. Squared


1 1
2 4
3 9
4 12
5 25

1st Solution – using the for loop statement.


2nd Solution – using the while loop statement.
3rd Solution – using the do while loop statement.
26
LESSON 3
REVIEW OF ARRAYS AND INTRODUCTION OF INDEXERS

Learning Outcomes

After successful completion of the lesson you should be able to:


1. Identify the different types of Arrays.
2. Demonstrate the ability to use Square and Rectangular Arrays in a program.
3. Demonstrate the ability to use Jagged Array in a program
4. Make a computer program using Indexers.

Course Materials

3.1 C# Array

An array stores a fixed-size sequential collection of elements of the same type. An array
is used to store a collection of data, but it is often more useful to think of an array as a collection
of variables of the same type stored at contiguous memory locations.

All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.

Declaring Arrays

Syntax:

datatype[] arrayName;

where

• datatype is used to specify the type of elements in the array.


• [ ] specifies the rank of the array. The rank specifies the size of the array.
• arrayName specifies the name of the array.

Initializing an Array

Declaring an array does not initialize the array in the memory. When the array variable is
initialized, you can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of the array.
Example

double[] balance = new double[10];


27
Assigning Value to an Array

You can assign values to an Array using the following.

• Using the index number

double[] balance = new double[10];


balance[0] = 4500.0;

• During the time of declaration

double[] balance = { 2340.0, 4523.69, 3421.0};

• Create and initialize an array

int [] marks = new int[5] { 99, 98, 92, 97, 95};

A size of an array can also be omitted

int [] marks = new int[] { 99, 98, 92, 97, 95};

Example

using System;

namespace ArrayApplication
{
class Program

static void Main(string[] args)


{

int[] n = new int[10]; /* n is an array of 10 integers */


int i, j;

/* initialize elements of array n */


for (i = 0; i < 10; i++)
{
n[i] = i + 100;
}

/* output each array element's value */


for (j = 0; j < 10; j++)
{
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
28
}

}
}

3.2 Square and Rectangular Array

C# allows multidimensional arrays. Multi-dimensional arrays are also called rectangular


array. In rectangular arrays, number of elements in a dimension is same for all. For example, if
number of columns for in a row is 5 then all the rows will be having 5 columns.

There are 3 ways to initialize multidimensional array in C# while declaration.

int[,] arr = new int[3,3]= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

We can omit the array size.

int[,] arr = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

We can omit the new operator also.

int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

Example:

using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


{

int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }
};//declaration and initialization

//traversal
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();//new line at each row

}
29
Console.ReadKey();
}

}
}

3.3 Jagged Array

A jagged array in C# is an array whose elements are arrays. The elements of a jagged
array can be of different dimensions and sizes. A jagged array is sometimes called an "array of
arrays." A special type of array is introduced in C#. A Jagged Array is an array of an array in which
the length of each array index can differ.

Example

int[][] jagArray = new int[5][];

Declaring and Initializing a Jagged Array

int[][] jaggedArray = new int[5][];


jaggedArray[0] = new int[3];
jaggedArray[1] = new int[5];
jaggedArray[2] = new int[2];
jaggedArray[3] = new int[8];
jaggedArray[4] = new int[10];
jaggedArray[0] = new int[] { 3, 5, 7, };
jaggedArray[1] = new int[] { 1, 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 1, 6 };
jaggedArray[3] = new int[] { 1, 0, 2, 4, 6, 45, 67, 78 };
jaggedArray[4] = new int[] { 1, 0, 2, 4, 6, 34, 54, 67, 87, 78 };

You can also initialize the array upon declaration like this:

int[][] jaggedArray = new int[][]


{
new int[] { 3, 5, 7, },
new int[] { 1, 0, 2, 4, 6 },
new int[] { 1, 6 },
new int[] { 1, 0, 2, 4, 6, 45, 67, 78 }
};

You can use the following shorthand form:

int[][] jaggedArray =
{
new int[] { 3, 5, 7, },
new int[] { 1, 0, 2, 4, 6 },
new int[] {1, 2, 3, 4, 5, 6, 7, 8},
30
new int[] {4, 5, 6, 7, 8}
};

Example

using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


{

/* a jagged array of 5 array of integers*/


int[][] a = new int[][]{new int[]{0,0},new int[]{1,2},
new int[]{2,4},new int[]{ 3, 6 }, new int[]{ 4, 8 } };
int i, j;

/* output each array element's value */


for (i = 0; i < 5; i++)
{
for (j = 0; j < 2; j++)
{
Console.WriteLine("a[{0}][{1}] = {2}", i, j,
a[i][j]);
}
}

Console.ReadKey();
}

}
}

3.4 Indexers

An indexer is a special type of property that allows a class or a structure to be accessed


like an array for its internal collection. C# allows us to define custom indexers, generic indexers,
and also overload indexers.

An indexer can be defined the same way as property with this keyword and square brackets
[].

Syntax

<return type> this[<parameter type> index]


31
{
get{
// return the value from the specified index of an
internal collection
}
set{
// set values at the specified index in an internal
collection
}
}

Example:

using System;

namespace ConsoleApplication
{
class Program

static void Main(string[] args)


{

StringDataStore strStore = new StringDataStore();

strStore[0] = "One";
strStore[1] = "Two";
strStore[2] = "Three";
strStore[3] = "Four";

for (int i = 0; i < 10; i++)


Console.WriteLine(strStore[i]);

Console.ReadKey();
}

}
}

The above StringDataStore class defines an indexer for its private array strArr. So now,
you can use the StringDataStore like an array to add and retrieve string values from strArr,
as shown below.

using System;

namespace ConsoleApplication
{
class Program
32

static void Main(string[] args)


{

StringDataStore strStore = new StringDataStore();

strStore[0] = "One";
strStore[1] = "Two";
strStore[2] = "Three";
strStore[3] = "Four";

for (int i = 0; i < 10; i++)


Console.WriteLine(strStore[i]);

Console.ReadKey();
}

}
}

3.4.1 Generic Indexer

Indexer can also be generic. It means that it can be used with any data type.

Example

class DataStore<T>
{
private T[] store;

public DataStore()
{
store = new T[10];
}

public DataStore(int length)


{
store = new T[length];
}

public T this[int index]


{
get
{
if (index < 0 && index >= store.Length)
throw new IndexOutOfRangeException("Index out of
range");
33

return store[index];
}

set
{
if (index < 0 || index >= store.Length)
throw new IndexOutOfRangeException("Index out of
range");

store[index] = value;
}
}

public int Length


{
get
{
return store.Length;
}
}
}

The following example demonstrates the use of generic indexer.

DataStore<int> grades = new DataStore<int>();


grades[0] = 100;
grades[1] = 25;
grades[2] = 34;
grades[3] = 42;
grades[4] = 12;
grades[5] = 18;
grades[6] = 2;
grades[7] = 95;
grades[8] = 75;
grades[9] = 53;

for (int i = 0; i < grades.Length; i++)


Console.WriteLine(grades[i]);

DataStore<string> names = new DataStore<string>(5);


names[0] = "Steve";
names[1] = "Bill";
names[2] = "James";
names[3] = "Ram";
names[4] = "Andy";

for (int i = 0; i < names.Length; i++)


Console.WriteLine(names[i]);
34
3.4.2 Overloaded Indexer

You can be overloaded with the different data types for index. The following example
overloads an indexer with int type index as well as string type index.

Example

using System;

namespace ConsoleApplication
{
class StringDataStore
{
private string[] strArr = new string[10]; // internal data storage

// int type indexer


public string this[int index]
{
get
{
if (index < 0 || index >= strArr.Length)
throw new IndexOutOfRangeException("Index out of range");

return strArr[index];
}

set
{
if (index < 0 || index >= strArr.Length)
throw new IndexOutOfRangeException("Index out of range");

strArr[index] = value;
}
}

// string type indexer


public string this[string name]
{
get
{
foreach (string str in strArr)
{
if (str.ToLower() == name.ToLower())
return str;
}

return null;
}
}
35
}

class Program
{
static void Main(string[] args)
{
StringDataStore strStore = new StringDataStore();

strStore[0] = "One";
strStore[1] = "Two";
strStore[2] = "Three";
strStore[3] = "Four";

Console.WriteLine(strStore["one"]);
Console.WriteLine(strStore["two"]);
Console.WriteLine(strStore["Three"]);
Console.WriteLine(strStore["Four"]);
}
}
}

Activities/Assessments

All class assignments and activities should be submitted via google classroom website on
or before the due date. The solutions to the programming problems must include full working
code, not just an output of your program.

1. Define the different types of Arrays presented in this lesson and cite your own example.
2. Create a program that utilizes the multidimensional array in real life scenario.
3. Using jagged arrays create a movie ticket counter where ticket selling counters are fixed
(rows are fixed) but you don't know how many people will be standing in each counter in
a queue (column numbers are not fixed can vary on different rows).
4. Create an Indexer class named myIndexer and access the class in the main method of
the main program. It can be generic or overloaded.
36
LESSON 4
REVIEW OF METHODS AND PARAMETERS

Learning Outcomes

After successful completion of the lesson you should be able to:


1. Define static fields and methods and parameters.
2. Define the process of overloading methods
3. Use methods and parameters in Machine problems.

Course Materials

4.1 Static Fields and Methods

In C#, static means something which cannot be instantiated. You cannot create an object
of a static class and cannot access static members using an object.

C# classes, variables, methods, properties, operators, events, and constructors can be


defined as static using the static modifier keyword.

4.1.1 Static Field

A static field is a class field, which means that its data is stored in one location in
memory, no matter how many objects are created from its class. In fact, you can use a static field
to keep track of how many objects have been created from a particular class.

Static fields in a non-static class can be defined using the static keyword. Static fields
of a non-static class is shared across all the instances. So, changes done by one instance would
reflect in others.

Example:

using System;

public class Program


{
static int counter = 0;
string name = "Demo Program";

public static void Main()


{
StopWatch sw1 = new StopWatch();
StopWatch sw2 = new StopWatch();
Console.WriteLine(StopWatch.NoOfInstances);

StopWatch sw3 = new StopWatch();


StopWatch sw4 = new StopWatch();
Console.WriteLine(StopWatch.NoOfInstances);

}
37

public class StopWatch


{
public static int NoOfInstances = 0;

public StopWatch()
{
StopWatch.NoOfInstances++;
}
}

4.1.2 Static Methods

You can define one or more static methods in a non-static class. Static methods can be
called without creating an object. You cannot call static methods using an object of the non-static
class.

The static methods can only call other static methods and access static members. You
cannot access non-static members of the class in the static methods.

Static methods are called by using the class name, not the instance of the class.

Example

using System;

public class Program


{
public static void withoutObj()
{
Console.WriteLine("Hello");
}
public static void Main()
{

Program.withoutObj();
Console.ReadKey();
}

Using Static Method


Usually we define a set of data members for a class and then every object of that class
will have a separate copy of each of those data members. Let's have an example.
38
Example

using System;

public class Program


{
public int myVar; //a non-static field

public static void Main()


{
Program p1 = new Program(); //a object of class
p1.myVar = 10;
Console.WriteLine(p1.myVar);
Console.ReadKey();
}

In the above example, myVar is a non-static field so to use this field we first need to create
the object of that class. On the other hand, static data is shared among all the objects of that
class. That is, for all the objects of a class, there will be only one copy of static data.

Example

using System;

public class Program


{
public int myVar; //a non-static field

public static void Main()


{
//Program p1 = new Program(); //a object of class
myVar = 10;
Console.WriteLine(myVar);
Console.ReadKey();
}

Points to Remember are:

1. A static method can be invoked directly from the class level


2. A static method does not require any class object
3. Any main() method is shared through the entire class scope so it always appears with
static keyword.
39
4.2 Using Methods

A method is a group of statements that together perform a task. Every C# program has at
least one class with a method named Main.

To use the method you need to:

• Define the method


• Call the method

4.2.1 Defining Methods

When defining a method, we basically declare the elements of its structure. The syntax is below.

<AccessSpecifier><ReturnType><MethodName>(Parameter List)
{
Method Body
}

Where:

• Access Specifier: This determines the visibility of a variable or a method from another
class.

• Return type: A method may return a value. The return type is the data type of the value
the method returns. If the method is not returning any values, then the return type is void.

• Method name: Method name is a unique identifier and it is case sensitive. It cannot be
same as any other identifier declared in the class.

• Parameter list: Enclosed between parentheses, the parameters are used to pass and
receive data from a method. The parameter list refers to the type, order, and number of
the parameters of a method. Parameters are optional; that is, a method may contain no
parameters.

• Method body: This contains the set of instructions needed to complete the required
activity.

Example

class NumberManipulator {

public int FindMax(int num1, int num2) {


/* local variable declaration */
int result;

if (num1 > num2)


result = num1;
else
40
result = num2;

return result;
}
...
}

4.2.2 Calling Methods

The method is called using the name of the method as shown in the example below.

Example 1

using System;

public class Program


{
public static void NameandAddress()
{
Console.WriteLine("Guido Van Rossum");
Console.WriteLine("Netherlands");
}

public static void Main()


{

//Calling the method inside the class


NameandAddress();
Console.ReadKey();
}

Example 2

using System;

public class Program


{

class NumberManipulator {

public int FindMax(int num1, int num2) {


/* local variable declaration */
int result;

if (num1 > num2)


result = num1;
41
else
result = num2;

return result;
}

}
public static void Main()
{

/* local variable definition */


int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();

//calling the FindMax method


ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();

You can also You can also call public method from other classes by using the instance of
the class. For example, the method FindMax belongs to the NumberManipulator class, you can
call it from another class Test.

Example

using System;

namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
}
42
class Test
{
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();

//calling the FindMax method


ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret);
Console.ReadLine();
}
}
}

4.2.3 Recursive Method Call

A method can call itself. This is known as recursion. Following is an example that calculates
factorial for a given number using a recursive function.

Example

using System;

namespace CalculatorApplication
{
class NumberManipulator
{
public int factorial(int num)
{
/* local variable declaration */
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
//calling the factorial method {0}", n.factorial(6));
43
Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
Console.ReadLine();
}
}
}

4.3 Using Parameters

A method’s parameters can be of any type, but there are several kinds of parameter
passing. When you define a method that you specify the parameters the method should have,
and these parameters are called the formal parameters and specify the values that the method
should operate on. When you call the method, you must specify the values (parameters) to be
transferred to the method, and they are called for the actual parameters.

Information can be passed to methods as parameter. Parameters act as variables inside


the method.

Value parameters

In general, the parameters are value parameters, for example.

static int Max(int a, int b)


{
return a < b ? b : a;
}

When this method is called, there must be transmitted two actual parameters. Exactly
what happens is that on the stack the system creates a so-called activation block, which contains
four basic things

• the return address, so the system knows where the program will continue after the method
is terminated
• a copy of each actual parameter
• a place to the return value corresponding to the method’s type
• the method’s local variables, if it has local variables.
44
Example

using System;

namespace ParameterExample
{
class Program
{
static int AddNumbers(int a, int b)
{
int sum;
sum = a + b;
Console.WriteLine("The Answer is " + sum);
return sum;
}
static void Main(string[] args)
{

int n1, n2;

Console.WriteLine("Enter Integer 1: ");


n1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Integer 2: ");
n2 = Convert.ToInt32(Console.ReadLine());
AddNumbers(n1,n2);
Console.ReadKey();
}
}
}

In the above example we declared a method name AddNumbers(int a, int b) with


parameters int a and int b. In the main method we called AddNumbers(int a, int b)
methods the by supplying arguments n1 and n2.

Example

The example below demonstrates the use of different methods with parameters.

using System;

namespace ParameterExample
{
class Program
{
static int Sum(int a, int b)
{
int sum;
sum = a + b;
Console.WriteLine("The Answer is " + sum);
return sum;
45
}

static int Difference(int a, int b)


{
int diff;
diff = a - b;
Console.WriteLine("The Answer is " + diff);
return diff;
}

static int Product(int a, int b)


{
int prod;
prod = a + b;
Console.WriteLine("The Answer is " + prod);
return prod;
}

static int Quotient(int a, int b)


{
int div;
div = a + b;
Console.WriteLine("The Answer is " + div);
return div;
}

static void Main(string[] args)


{

int n1, n2;

Console.WriteLine("Enter Integer 1: ");


n1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Integer 2: ");
n2 = Convert.ToInt32(Console.ReadLine());
Sum(n1,n2);
Difference(n1, n2);
Product(n1, n2);
Quotient(n1, n2);
Console.ReadKey();
}
}
}

Note: The void keyword, used in the examples above, indicates that the method should not return
a value. If you want the method to return a value, you can use a primitive data type (such as int
or double) instead of void, and use the return keyword inside the method:
46
4.4 Overloading methods

With method overloading, multiple methods can have the same name with different parameters:

Example

using System;

namespace ParameterExample
{
class Program
{
static int PlusMethodInt(int x, int y)
{
return x + y;
}

static double PlusMethodDouble(double x, double y)


{
return x + y;
}

static void Main(string[] args)


{

int myNum1 = PlusMethodInt(8, 5);


double myNum2 = PlusMethodDouble(4.3, 6.26);
Console.WriteLine("Int: " + myNum1);
Console.WriteLine("Double: " + myNum2);

Console.ReadKey();
}
}
}

Instead of defining two methods that should do the same thing, it is better to overload one.

In the example below, we overload the PlusMethod method to work for both int and double:

Example

using System;

namespace ParameterExample
{
class Program
{
static int PlusMethod(int x, int y)
{
47
return x + y;
}

static double PlusMethod(double x, double y)


{
return x + y;
}

static void Main(string[] args)


{

int myNum1 = PlusMethod(8, 5);


double myNum2 = PlusMethod(4.3, 6.26);
Console.WriteLine("Int: " + myNum1);
Console.WriteLine("Double: " + myNum2);

Console.ReadKey();
}
}
}

Activities/Assessments

All class assignments and activities should be submitted via google classroom website on
or before the due date. The solutions to the programming problems must include full working
code, not just an output of your program.

1. What is static field and static method and how they are used in a program? Provide your
own example of this.
2. How a method is overloaded in a program? Demonstrate this by creating your own
methods which are overloaded in the main class.
3. Create the following machine problems.

a. Create a program with a method that will accept as input a number of N seconds and
determine from this number how many days, hours, minutes, and seconds it represents.

Sample Output:

How many seconds do you want to be converted? 100000100000 Seconds is equal to:

1Day
3Hours
46Minutes
40 Seconds

b. Create a Jack n Poy Game that implements the conditional statement, methods and
parameters in a program.
48
LESSON 5
OBJECT-ORIENTED PROGRAMMING CONCEPTS

Learning Outcomes

After successful completion of the lesson you should be able to:


1. Define classes in object-oriented programming.
2. Use the constructors and initialization.
3. Define and use encapsulation in a program.
4. Define and use inheritance in a program.
5. Instantiate an object from a class.

Course Materials

5.1 Classes and Objects

Procedural programming is about writing procedures or methods that perform operations


on the data, while object-oriented programming is about creating objects that contain both data
and methods.

Object-oriented programming has several advantages over procedural programming:

• OOP is faster and easier to execute


• OOP provides a clear structure for the programs
• OOP helps to keep the C# code DRY "Don't Repeat Yourself", and makes the code easier
to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less code and shorter
development time.

Class is a template or a blueprint of which an object (instantiation of class) is created.


Below is the representation of this.

5.1.1. Creating Classes

To create a class, use the class keyword:

Example

class Car
{
string color = "red";
}

When a variable is declared directly in a class, it is often referred to as a field (or


attribute). It is not required, but it is a good practice to start with an uppercase first letter when
naming classes. Also, it is common that the name of the C# file and the class matches, as it
makes our code organized. However, it is not required (like in Java).
49
5.1.2 Create an Object

An object is created from a class. In the above example, the class Car was created. This
time we are going to create an object from the class Car.

Example

using System;
class Car
{
string color = "red";

static void Main(string[] args)


{
Car myObj = new Car();
Console.WriteLine(myObj.color);
Console.ReadKey();
}
}

Note that the (.) is used to separate class from an object, or to access variables/fields inside a
class. The class Car is instantiated by creating object myObj and the field color is used.

5.1.3 Multiple Objects

Multiple objects can be created out of one single class.

Example

class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj1 = new Car();
Car myObj2 = new Car();
Console.WriteLine(myObj1.color);
Console.WriteLine(myObj2.color);
}
}

5.1.4 Multiple Classes

An object of class can also be created and can be accessed it in another class. Usually,
this is done for better organization of classes. In other words (one class has all the fields and
methods, while other class holds the Main() method.

• Car.cs
50
• Program.cs

1. Upon creating new project in the file tab. It will automatically generate a class name Program.cs
that contains the main() method.

2. Navigate to the right of the window under the Solution explorer right click and Add and then
click class and name it whatever you want but usually it starts with a capital letter.

The Program.cs contains the main method that invoke the Car.cs with fields in it.

Car.cs

using System;

namespace ObjectOrientedProgramming
{
class Car
{
public string color = "red";
}
}

Program.cs

using System;

namespace ObjectOrientedProgramming
{
class Program
{
static void Main(string[] args)
{
51
Car myObj = new Car();
Console.WriteLine(myObj.color);
Console.ReadKey();
}
}
}

5.2 Constructors and Initialization

A constructor is a special method that is used to initialize objects. The advantage of a


constructor is that it is called when an object of a class is created. It can be used to set initial
values for fields:

Example

Below is the Car class

using System;

namespace ObjectOrientedProgramming
{ //Create class Car
class Car
{
public string model; //Create a Field
//Create a class Constructor for the Car class
public Car()
{
model = "Mustang"; // Set the initial value for model
}
}
}

Then the Program.cs which invokes the Car class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ObjectOrientedProgramming
{
class Program
{
static void Main(string[] args)
{
Car Ford = new Car(); // Create an object of the Car Class (this
will call the constructor)
Console.WriteLine(Ford.model); // Print the value of model
Console.ReadKey();
52
}
}
}

Note that the constructor name must match the class name, and it cannot have a return type
(like void or int). The constructor is called upon object is created. All classes have constructors
by default: if you do not create a class constructor yourself, C# creates one for you. However,
then you are not able to set initial values for fields.

5.2.1 Constructor with Parameters

Constructors can also take parameters, which is used to initialize fields.

The following example adds a string modelName parameter to the constructor. Inside
the constructor we set model to modelName (model=modelName). When we call the
constructor, we pass a parameter to the constructor ("Mustang"), which will set the value of
model to "Mustang":

Car.cs

using System;

namespace ObjectOrientedProgramming
{ //Create class Car
class Car
{
public string model;
// Create a class constructor with a parameter
public Car(string modelName)
{
model = modelName;
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ObjectOrientedProgramming
{

class Program
{
static void Main(string[] args)
{
53
Car Ford = new Car("Mustang");
Console.WriteLine(Ford.model);
Console.ReadKey();
}
}
}

Making constructors saves time as shown below:

Example: Without Constructor

class Program
{
static void Main(string[] args)
{
Car Ford = new Car();
Ford.model = "Mustang";
Ford.color = "red";
Ford.year = 1969;

Car Opel = new Car();


Opel.model = "Astra";
Opel.color = "white";
Opel.year = 2005;

Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}

Example: With Constructor

class Program
{
static void Main(string[] args)
{
Car Ford = new Car("Mustang", "Red", 1969);
Car Opel = new Car("Astra", "White", 2005);

Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}

5.3 Encapsulation

Encapsulation is defined 'as the process of enclosing one or more items within a physical
or logical package'. Encapsulation, in object-oriented programming methodology, prevents
access to implementation details.
54

Abstraction and encapsulation are related features in object-oriented programming.


Abstraction allows making relevant information visible and encapsulation enables a programmer
to implement the desired level of abstraction.

Encapsulation is implemented by using access specifiers. An access specifier defines the


scope and visibility of a class member. C# supports the following access specifiers:

• Public
• Private
• Protected
• Internal
• Protected internal

5.3.1 Public Access Specifier

Public access specifier allows a class to expose its member variables and member
functions to other functions and objects. Any public member can be accessed from outside the
class.

Example

using System;

namespace EncapsulationExample
{
class Rectangle
{
//member variables
public double length;
public double width;

public double GetArea()


{
return length * width;
}
//End of class Rectangle
public void Display()
{
Console.WriteLine("Length {0} ", length);
Console.WriteLine("Width {0} ", width);
Console.WriteLine("Area {0} ", GetArea());
}
}
class Program
{
static void Main(string[] args)
{
55

Rectangle r = new Rectangle(); // Creating instance of Rectangle

r.length = 4.5;
r.width = 3;

r.Display();

Console.ReadKey();

}
}
}

In the preceding example, the member variables length and width are declared public, so
they can be accessed from the function Main using an instance of the Rectangle class, named r.

The member function Display and GetArea can also access these variables directly
without using any instance of the class.

The member functions Display is also declared public, so it can also be accessed from
Main using an instance of the Rectangle class, named r.

5.3.2 Private Access Specifier

Private access specifier allows a class to hide its member variables and member functions
from other functions and objects. Only functions of the same class can access its private
members. Even an instance of a class cannot access its private members.

Example

using System;

namespace EncapsulationExample
{
class Rectangle
{
//member variables
private double length;
private double width;

public void AcceptDetails()


{
Console.WriteLine("Enter Length: ");
56
length = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Width: ");
width = Convert.ToDouble(Console.ReadLine());
}

public double GetArea()


{
return length * width;
}

public void Display()


{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
//End of class Rectangle

}
class Program
{
static void Main(string[] args)
{

Rectangle r = new Rectangle(); // Creating instance of Rectangle


r.AcceptDetails();
r.Display();
Console.ReadKey();

}
}
}

In the preceding example, the member variables length and width are declared private, so
they cannot be accessed from the function Main. The member functions AcceptDetails and
Display can access these variables. Since the member functions AcceptDetails and Display are
declared public, they can be accessed from Main using an instance of the Rectangle class, named
r.

5.3.3 Protected Access Specifier

Protected access specifier allows a child class to access the member variables and
member functions of its base class. This way it helps in implementing inheritance. This will be
covered in Inheritance.

5.3.4 Internal Access Specifier

Internal access specifier allows a class to expose its member variables and member
functions to other functions and objects in the current assembly. In other words, any member with
57
internal access specifier can be accessed from any class or method defined within the application
in which the member is defined.

Example

using System;

namespace EncapsulationExample
{
class Rectangle {
//member variables
internal double length;
internal double width;

double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle

class Program
{
static void Main(string[] args)
{

Rectangle r = new Rectangle();


r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();

}
}
}

In the preceding example, notice that the member function GetArea() is not declared with any
access specifier. The default access modifier of a class member is private since no access
specifier is declared.

Protected Internal Access Specifier

The protected internal access specifier allows a class to hide its member variables and
member functions from other class objects and functions, except a child class within the same
application. This is also used while implementing inheritance.
58

5.4 Inheritance

Inheritance allows us to define a class in terms of another class, which makes it easier to
create and maintain an application. This also provides an opportunity to reuse the code
functionality and speeds up implementation time.

When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the members of an
existing class. This existing class is called the base class, and the new class is referred to as the
derived class.

The idea of inheritance implements the IS-A relationship. For example, mammal IS A
animal, dog IS-A mammal hence dog IS-A animal as well, and so on.

5.4.1 Base and Derived Classes

A class can be derived from more than one class or interface, which means that it can inherit data
and functions from multiple base classes or interfaces.

Syntax

<acess-specifier> class <base_class> {


...
}

class <derived_class> : <base_class> {


...
}

Example

Consider a base class Shape and its derived class Rectangle.

using System;

namespace RectangleApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
59
protected int height;
}

// Derived class
class Rectangle : Shape
{
public int getArea()
{
return (width * height);
}
}

class Program
{
static void Main(string[] args)
{

Rectangle Rect = new Rectangle();

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}

5.4.2 Multiple Inheritance

C# does not support multiple inheritance. However, you can use interfaces to
implement multiple inheritance. This will be covered in lesson for Interfaces.

Example

using System;

namespace RectangleApplication
{
class Shape {
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
protected int width;
60
protected int height;
}

// Base class PaintCost


public interface PaintCost {
int getCost(int area);
}

// Derived class
class Rectangle : Shape, PaintCost {
public int getArea() {
return (width * height);
}
public int getCost(int area) {
return area * 70;
}
}

class Program
{
static void Main(string[] args)
{

Rectangle Rect = new Rectangle();


int area;

Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();

// Print the area of the object.


Console.WriteLine("Total area: {0}", Rect.getArea());
Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));
Console.ReadKey();
}
}
}

5.5 Class Instantiation

Instantiation is the process of creating object of a defined class and the instance is the
object itself, which is created in runtime. This instance is characterized by state–set of values,
associated with class attributes. In the context of such behavior the object consists of two things:
current state and behavior defined in the class of the object. The state is specific for the instance
(the object), but the behavior is common for all objects which are instances of this class.
61
Example

The class Cat models the real-world object "cat" and has the properties name and color.
The given class defines several fields, properties and methods.

Class Cat

public class Cat


{
//Field name
private string name;
//Field color
private string color;

//Name

public string Name


{
//Getter of the Property name
get
{
return this.name;
}
set
{
this.name = value;
}

}
//Name ends
//Color

public string Color


{ //getter of property Color
get
{
return this.color;
}
set
{
this.color = value;
}
}

//Default Constructor

public Cat()
{
this.name = "Unnamed";
this.color = "gray";
62
}

//Constructor with Parameter

public Cat(string name, string color)


{
this.name = name;
this.color = color;
}
//Method for Sound
public void Say()
{
Console.WriteLine("Cat {0} said: Miauuuuuuuu!", name);
}
}

The example class Cat defines the properties Name and Color, which keep their values
in the hidden (private) fields name and color. Furthermore, two constructors are defined for
creating instances of the class Cat, respectively with and without parameters, and a method of
the class Say().

class Program
{
static void Main(string[] args)
{

Cat firstCat = new Cat();


firstCat.Name = "Tony";
firstCat.Say();

Cat secondCat = new Cat("Pepy", "red");


secondCat.Say();
Console.WriteLine("Cat {0} is {1}.", secondCat.Name,
secondCat.Color);

}
}
63
Activities/Assessments

All class assignments and activities should be submitted via google classroom website on
or before the due date. The solutions to the programming problems must include full working
code, not just an output of your program. For items 4 and 5 you can work in a group with
maximum members of three.

1. What is a class in object-oriented programming and how it is instantiated?


2. Create program that uses constructors and initialize it in the main method.
3. What is encapsulation and how it is used in a program?
4. Define a class Human with properties "first name" and "last name". Define the class
Student inheriting Human, which has the property "mark". Define the class Worker
inheriting Human with the property "wage" and "hours worked". Implement a "calculate
hourly wage" method, which calculates a worker’s hourly pay rate based on wage and
hours worked. Write the corresponding constructors and encapsulate all data in
properties.
5. We are given a school. The school has classes of students. Each class has a set of
teachers. Each teacher teaches a set of courses. The students have a name and unique
number in the class. Classes have a unique text identifier. Teachers have names. Courses
have a name, count of classes and count of exercises. The teachers as well as the
students are people. Your task is to model the classes (in terms of OOP) along with their
attributes and operations define the class hierarchy and create a class diagram with Visual
Studio.
64
LESSON 6
INHERITANCE
Learning Outcomes

After successful completion of the lesson you should be able to:


1. Define the broader concept of inheritance.
2. Identify the Access Controls.
3. Demonstrate the ability to use Inheritance
4. Demonstrate the ability to use Method Hiding.
5. Use initialization.

Course Materials

6.1 Inheritance

Inheritance is a fundamental principle of object-oriented programming. It allows a class


to "inherit" (behavior or characteristics) of another, more general class. Inheritance is described
as is-kind-of, e.g. Employee is a kind of Person.

Example

Below is a class that represents a person by first name and last name.

public class Person


{
private string fname;
private string lname;

public Person(string fname, string lname)


{
this.fname = fname;
this.lname = lname;
}

public string FirsName


{
get { return fname; }
}
public string LastName
{
get { return lname; }
}
public override string ToString()
{
return fname + "" + lname;
}
}

The another class Employee (of a company) is person with two additional properties in the
form of a title and salary. Below is a class that inherits the Person class.
65

Class Employee

//Start of class Employee

public class Employee : Person


{
private string position;
private int monthly;

public Employee(string fname, string lname, string position, int


monthly)
: base (fname, lname)
{
this.position = position;
this.monthly = monthly;
}

public string Position


{
get { return position; }
}
public int Monthly
{
get { return monthly; }
}

public override string ToString()


{
return base.ToString() + "\n" + position;
}

//End of Employee class

You notice the:

: Person

It denotes that the Employee inherits the Person. That Employee inherits Person means
an Employee gets (inherits) all the properties that a Person has and expands with new properties.
In this case extends an Employee a Person with two new instance variables and associated
properties. The Employee class has a constructor that initializes the two new instance variables,
position and monthly, but it must also initialize the instance variables fname and lname in the
base class. This requires that the constructor in Person is called, but when as a programmer you
can’t call it directly, it is necessary to have a syntax that performs the constructor in the base
class. It happens in the following:

: base (fname, lname)


66
Here, the colon and base() after constructor declaration means that the constructor in the
Person is performed by fname and lname as the actual parameters. Specifically, what happens
is when you create an Employee object the constructor in Person is performed, and then the
constructor in Employee is performed. When an Employee is specifically a Person, one can say
that Person has to be created first, before the Employee can be created. An Employee object can
then refer to the two properties fname and lname. An Employee object can refer to fname, since
it is a public property in Person and because Employee inherits Person. Employee objects can
refer to all public members in both Person and Employee. Private members can still only be
referenced from within the class where they are defined. For example, the variable fname in
Person can’t be referred from methods in Employee.

A Director is just a special kind of Employee, and the class can be defined as a class that
inherits Employee. A class that represent a Director will define like this:

//Class Director

public class Director : Employee


{
public Director(string fname, string lname, int monthly)
: base(fname, lname, "Director", monthly)
{

}
}

The class is very simple and consists solely of a constructor, which transmit parameters
to the constructor in the Employee class. All the other services as a director does occur (inherited)
come from Employee and Person.

The class Bookkeeper can define the same way as class Director:

//Class Bookkeeper

public class Bookkeeper : Employee


{
public Bookkeeper(string fname, string lname, int monthly)
: base(fname, lname, "Bookkeeper", monthly)
{

}
}

Now consider the following method:

//Method that prints


static void Print(Employee e)
{
Console.WriteLine(e);
Console.WriteLine("Montly {0}", e.Monthly);
Console.WriteLine("{0}, {1}", e.lname, e.fname);
67
}//Method that prints ends

The first statement prints the result of ToString() from the class Employee. The parameter
e has the type Employee, and you can thus especially use what is defined public in Person.

Now Consider the following method:

static void Tes1()


{
Director d = new Director("Olga", "Jensen", 8000);
Bookkeeper b = new Bookkeeper("Karlo", "Hansen", 500);

Print(d);
Print(b);
}

You should particularly note that the method calls Print() with the two objects d and b as
actual parameters. It makes sense for d have the type Director, which specifically is an Employee

Above, there are defined four classes that are linked in a hierarchy, as you can illustrate
in the following way:

When a class inherits another class, the class you inherit from is called the base class and
the inheriting class is called a derived class. For example, is Person the base class for Employee
while Employee derives from Person. Sometimes Person instead of is called a super class, while
the Employee is called a subclass. We say also that Person is a generalization of Employee and
that Employee is a specialization of Person. This saying better reflected the relationship between
Employee, Director and Bookkeeper in which Employee is a generalization of the Director and
Bookkeeper and Director are specializations of Employee. Sometimes we talk also about the
class that inherits as an extension of the base class corresponding to Employee extends Person
with new properties.

6.2 Access Control

In the previous lessons, the basic access modifiers such as public, private, and internal.
This time we will cover the protected and protected internal.
68

6.2.1 Protected Access Control

Protected defines class members which are not visible to users of the class (those who
initialize and use it) but are visible to all inheriting classes(descendants).

Example: Protected Access Modifier

using System;

namespace AccessControlExample
{
class User
{

protected string Name;

protected string Location;

protected int Age;

protected void GetUserDetails()


{

Console.WriteLine("Name: {0}", Name);

Console.WriteLine("Location: {0}", Location);

Console.WriteLine("Age: {0}", Age);

}
class Program
{
static void Main(string[] args)
{
User u = new User();

// Complier Error

// These are inaccessible due to protected specifier

u.Name = "Suresh Dasari";

u.Location = "Hyderabad";

u.Age = 32;
69
u.GetUserDetails();

Console.WriteLine("\nPress Enter Key to Exit..");

Console.ReadLine();
}
}
}

When the above code is executed the following errors occur:

If you observe the above result, we are getting compile-time errors because
the protected modifier members of the User class referred in another class.

As discussed, the protected members of a base class can be accessible in the


derived class, only when access occurs through the derived class type.

Below is the implementation of accessing a base class protected members in derived class
through derived class type.

Example

using System;

namespace AccessControlExample
{

class User
{

protected string Name;

protected string Location;

protected int Age;

protected void GetUserDetails()


{

Console.WriteLine("Name: {0}", Name);


70

Console.WriteLine("Location: {0}", Location);

Console.WriteLine("Age: {0}", Age);

class Program : User


{

static void Main(string[] args)


{

User u = new User();

Program p = new Program();

// Complier Error

// protected members can only accessible with derived classes

//u.Name = "Suresh Dasari";

p.Name = "Suresh Dasari";


p.Location = "Hyderabad";
p.Age = 32;
p.GetUserDetails();

Console.WriteLine("\nPress Enter Key to Exit..");


Console.ReadLine();

6.2.3 Protected Internal

Protected internal defines class members which are both internal, i.e. visible within the
entire assembly, and protected, i.e. not visible outside the assembly, but visible to classes who
inherit it (even outside the assembly).
71
Example

using System;

namespace AccessControlExample
{

class User
{

protected internal string Name;

protected internal string Location;

protected internal int Age;

protected internal void GetUserDetails()


{

Console.WriteLine("Name: {0}", Name);

Console.WriteLine("Location: {0}", Location);

Console.WriteLine("Age: {0}", Age);

class Program
{

static void Main(string[] args)


{

User u = new User();


u.Name = "Suresh Dasari";
u.Name = "Suresh Dasari";
u.Location = "Hyderabad";
u.Age = 32;
u.GetUserDetails();

Console.WriteLine("\nPress Enter Key to Exit..");


Console.ReadLine();

}
72
6.3 Method Hiding

C# also provides a concept to hide the methods of the base class from derived class, this
concept is known as Method Hiding. It is also known as Method Shadowing. In method hiding,
you can hide the implementation of the methods of a base class from the derived class using the
new keyword.

Example

using System;

namespace MethodHidingExample
{
// Base Class
public class My_Family
{

public void member()


{
Console.WriteLine("Total number of family members: 3");
}
}

// Derived Class
public class My_Member : My_Family
{

// Reimplement the method of the base class


// Using new keyword
// It hides the method of the base class
public new void member()
{
Console.WriteLine("Name: Rakesh, Age: 40 \nName: Somya, " +
"Age: 39 \nName: Rohan, Age: 20 ");
}
}
class Program
{
static void Main(string[] args)
{
// Creating the object of the derived class
My_Member obj = new My_Member();

// Access the method of derived class


obj.member();
Console.ReadKey();
}
}
}
73
In the above example, My_Family is the base class and My_Member is a derived class.
In both the classes we have the same name method, i.e. member() method. But in the derived
class, the member() method is declared with the new keyword. When this method is called, it
prints the name and the age of the family members not the total number of family members. Which
means when we call the member() method with the help of the derived class object, it hides the
same name method present in the base class due to the presence of the new keyword. When the
new keyword is not used compiler will give run the code without giving an error, but it will give
warning that if you want to hide a method then use the new keyword.

6.4 Initialization

The derived class inherits the base class member variables and member methods.
Therefore, the super class object should be created before the subclass is created. You can give
instructions for superclass initialization in the member initialization list.

Example

using System;

namespace RectangleApplication
{
class Rectangle
{

//member variables
protected double length;
protected double width;

public Rectangle(double l, double w)


{
length = l;
width = w;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle

class Tabletop : Rectangle


{
private double cost;
public Tabletop(double l, double w) : base(l, w) { }
74

public double GetCost()


{
double cost;
cost = GetArea() * 70;
return cost;
}

public void Display()


{
base.Display();
Console.WriteLine("Cost: {0}", GetCost());
}
}

class Program
{
static void Main(string[] args)
{

Tabletop t = new Tabletop(4.5, 7.5);


t.Display();
Console.ReadLine();
}
}
}

Activities/Assessments

All class assignments and activities should be submitted via google classroom website on
or before the due date. The solutions to the programming problems must include full working
code, not just an output of your program. For items 3 to 5 you can work in a group with maximum
members of three.

1. Discuss the concept of Inheritance and how it benefits the coding process?
2. What are the different access controls and how it is used?
3. Based on the following UML Diagram implement the concept of Inheritance. The example
provided in lesson 6.1 is your guide.
75

4. Based on Activity number 3 implement the concept of Method Hiding or Method


Shadowing.
5. Based on the following UML Diagram, implement initialize a base class Bank Account and
Derived classes such as current account and deposit account. You will be the one who
will supply the variables and methods.
76
LESSON 7
VIRTUAL METHODS AND POLYMORPHISM

Learning Outcomes

After successful completion of the lesson you should be able to:


1. Discuss Virtual Methods and Dynamic Binding
2. Define Method Overriding
3. Identify Fragile Base Class Problem
4. Define the underlying concepts of Polymorphism
5. Familiarize with Abstract Classes, Sealed Classes
6. Answer machine problems

Course Materials

7.1 Virtual Methods and Dynamic Binding

A method, which can be overridden in a derived class, is called a virtual method.


If we want to make a method virtual, we mark it with the keyword virtual. Then the derived
class can declare and define a method with the same signature.

Dynamic Binding

A polymorphic variable can be defined in a class that is able to reference (or point to)
objects of the class and objects of any of its descendants.

When a class hierarchy includes classes that override methods and such methods are
called through a polymorphic variable, the binding to the correct method will be dynamic.

Allows software systems to be more easily extended during both development and
maintenance
77
Dynamic Binding Concepts

An abstract method is one that does not include a definition (it only defines a protocol). An
abstract classis one that includes at least one virtual method. An abstract class cannot be
instantiated

7.2 Fragile Base Class Problem

Inheritance is a great power by which developers can increase reusability in parent-child


relationship. One of the problems which creeps in is the “Fragile parent class problem”.

Take a simple scenario (below is the image) where we have a simple parent child class
relationship. Assume that this child class is used in lot of projects and installed in lot of places.
Now assume after the child class has been deployed across locations, after some months, there
are some changes in the parent class.

These changes can have cascading and unexpected behavior in child class as well. This
unexpected behavior on child classes is termed as “Fragile class problem”.

Consider the below scenario where we have a parent class called as “DbParent” with a virtual
method “Insert”.

class DbParent
{
public virtual void Insert()
{
Console.WriteLine("Parent insert");
}
}

Below is a simple child class with his own “Insert” implementation which is installed across
various locations.

class DbChildClass : DbParent


{
public void Insert()
{
Console.WriteLine("Child inserts");
78
}
}

Now let’s say after some months of deployment parent class developers without
understanding the impact on child classes go and add a new method “Add”. This “Add” method
calls the “Insert” method internally (below is the code snippet for the same).

class DbParent
{
public void Add() // Adds method without consulting
{
this.Insert();
}
public virtual void Insert()
{
Console.WriteLine("Parent insert");
}
}

Now client programs who invoke the “Add” method by creating child class objects expect that the
“Child” class “Insert” implementation should be called.

DbChildClass o = new DbChildClass();


o.Add();
Console.Read();

When you execute the code, you will see the parent class “Insert” is called which is not
EXPECTED.

The base class is very fragile (will change from time to time) then the inheritance should
not be allowed. By making the class sealed or the fragile methods “sealed”, this problem can be
solved.

7.3 Polymorphism

The term polymorphism (from the Greek meaning "having multiple forms") in OO is the
characteristic of being able to assign a different meaning or usage to something in different
contexts - specifically, to allow a variable to refer to more than one type of object.

Inheritance lets us inherit fields and methods from another class. Polymorphism uses
those methods to perform different tasks. This allows us to perform a single action in different
ways.

Example

For example, think of a base class called Animal that has a method called
animalSound(). Derived classes of Animals could be Pigs, Cats, Dogs, Birds - And they also
have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):
79
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}

class Pig : Animal // Derived class (child)


{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}

class Dog : Animal // Derived class (child)


{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}

Now we can create Pig and Dog objects and call the animalSound() method on both of them:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MethodOverridingExample
{
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}

class Pig : Animal // Derived class (child)


{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}

class Dog : Animal // Derived class (child)


80
{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}

class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object

myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();

Console.ReadKey();
}
}
}

The output from the example above was probably not what you expected. That is because
the base class method overrides the derived class method, when they share the same name.
Below is an example of Method Overriding.

7.4 Method Overriding

C# provides an option to override the base class method, by adding the virtual keyword
to the method inside the base class, and by using the override keyword for each derived class
methods. Only if a method is declared virtual, derived classes can override this method if they are
explicitly declared to override the virtual base class method with the override keyword.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MethodOverridingExample
{
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
81
}
}

class Pig : Animal // Derived class (child)


{
public override void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}

class Dog : Animal // Derived class (child)


{
public override void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object

myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
}

7.5 Abstract Classes

Data abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved with either abstract classes or interfaces.

The abstract keyword is used for classes and methods:

• Abstract class: is a restricted class that cannot be used to create objects (to access it, it
must be inherited from another class).

• Abstract method: can only be used in an abstract class, and it does not have a body.
The body is provided by the derived class (inherited from).
82
Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MethodOverridingExample
{
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}

// Derived class (inherit from Animal)


class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}

class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound(); // Call the abstract method
myPig.sleep(); // Call the regular method
Console.ReadKey();
}
}
}

7.6 Sealed Classes

Classes can be declared as sealed by putting the keyword sealed before the class definition. If
you don't want other classes to inherit from a class, use the sealed keyword:
83
Syntax

public sealed class D


{
// Class members here.
}

Sealed class cannot be used as a base class. For this reason, it cannot also be an
abstract class. Sealed classes prevent derivation. Because they can never be used as a base
class, some run-time optimizations can make calling sealed class members slightly faster.

Activities/Assessments

All class assignments and activities should be submitted via google classroom website on
or before the due date. The solutions to the programming problems must include full working
code, not just an output of your program.
1. What are Virtual Methods and Dynamic Binding? Create your own virtual method and
implement it in a class.
2. What is method overloading? Why is method overloading implemented?
3. What is fragile base class problem? How it is solved?
4. What is polymorphism?
5. Discuss the abstract classes and sealed classes
6. Answer the following machine problems:

Using the concept of Polymorphism. Create a base class named Employee with the with
method Salary that has fields numberofHours, rateperHour and tax then derive classes
such as Regular and Contractual and Part-time then they must their own implementation
of Salary method.
84

LESSON 8
INTERFACES

Learning Outcomes

After successful completion of the lesson you should be able to:


1. Discuss the fundamentals of Interface.
2. Demonstrate programming with interfaces
3. Use Interfaces at runtime.

Course Materials

8.1 Interface Fundamentals

An abstract class is a type that can contain everything that a class can have. That is
variables, constructors, methods, etc. Just may some of the methods be abstract, corresponding
to those not yet been encoded – it is deferred to the concrete classes that have the requisite
knowledge. In contrast, an interface is a type which can contain only abstract methods.

Example

The following interface defines a point:

public interface IPoint


{
int X { get; set; }
int Y { get; set; }
}

Basically, it looks like a class, just stands there instead the word interface. An interface
defines the methods and properties, and in this case two properties. One can think of an interface
as a class that can only contain abstract methods. Note especially that in an interface has no
method visibility – they are by default public.

8.2 Programming with Interfaces

Below is a class that implements the interface:

public class Point : IPoint


{
private int x;
private int y;

public Point(int x, int y)


{
this.x = x;
this.y = y;
}
85

public int X
{
get { return x; }
set { x = value; }

public int Y
{
get { return y; }
set { y = value; }
}

public override string ToString()


{
return string.Format("({0}, {1})", x, y);
}
}

The same syntax for Inheritance is used:

public class Point : IPoint

When a class implements an interface, the class must implement the methods and
properties that are defined in the interface.

The following Main() method uses the interface.

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a value for X-axis");
int x = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter a value for Y-axis");


int y = Convert.ToInt32(Console.ReadLine());

IPoint p = new Point(x, y); //defining an object


Console.WriteLine(p);
Console.ReadKey();
}
}

p is a Point object, but in the program, it is known by its defining interface.


86
8.3 Using Interface at Runtime

If a class implements two interfaces that contain a member with the same signature, then
implementing that member on the class will cause both interfaces to use that member as their
implementation. In the following example, all the calls to Paint invoke the same method. This
first sample defines the types:

public interface IControl


{
void Paint();
}
public interface ISurface
{
void Paint();
}
public class SampleClass : IControl, ISurface
{
// Both ISurface.Paint and IControl.Paint call this method.
public void Paint()
{
Console.WriteLine("Paint method in SampleClass");
}
}

The following sample calls the methods:

SampleClass sample = new SampleClass();


IControl control = sample;
ISurface surface = sample;

// The following lines all call the same method.


sample.Paint();
control.Paint();
surface.Paint();
// Output:
// Paint method in SampleClass
// Paint method in SampleClass
// Paint method in SampleClass

When two interface members don't perform the same function, it leads to an incorrect
implementation of one or both of the interfaces. It's possible to implement an interface member
explicitly — creating a class member that is only called through the interface and is specific to
that interface. Name the class member with the name of the interface and a period. For
example:

public class SampleClass : IControl, ISurface


{
void IControl.Paint()
{
87
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}
The class member IControl.Paint is only available through the IControl interface,
and ISurface.Paint is only available through ISurface. Both method implementations are
separate, and neither are available directly on the class. For example:

// Call the Paint methods from Main.

SampleClass obj = new SampleClass();


//obj.Paint(); // Compiler error.

IControl c = obj;
c.Paint(); // Calls IControl.Paint on SampleClass.

ISurface s = obj;
s.Paint(); // Calls ISurface.Paint on SampleClass.

// Output:
// IControl.Paint
// ISurface.Paint

Explicit implementation is also used to resolve cases where two interfaces each declare
different members of the same name such as a property and a method. To implement both
interfaces, a class has to use explicit implementation either for the property P, or the method P,
or both, to avoid a compiler error. For example:

interface ILeft
{
int P { get; }
}
interface IRight
{
int P();
}

class Middle : ILeft, IRight


{
public int P() { return 0; }
int ILeft.P { get { return 0; } }
}

Beginning with C# 8.0, you can define an implementation for members declared in an
interface. If a class inherits a method implementation from an interface, that method is only
accessible through a reference of the interface type. The inherited member doesn't appear as
88
part of the public interface. The following sample defines a default implementation for an interface
method:

public interface IControl


{
void Paint() => Console.WriteLine("Default Paint method");
}
public class SampleClass : IControl
{
// Paint() is inherited from IControl.
}

The following sample invokes the default implementation:

var sample = new SampleClass();


//sample.Paint();// "Paint" isn't accessible.
var control = sample as IControl;
control.Paint();

Activities/Assessments

All class assignments and activities should be submitted via google classroom website on
or before the due date. The solutions to the programming problems must include full working
code, not just an output of your program. For item 2, you can work with a pair.

1. How is an Interface used within a program?


2. Implement the concepts of Interfaces in the following problem:

a. Create an interface class and name it ITransactions with interface members or


methods void showTransaction() and double getAmount().
b. Create a class Transactions that implements the methods and properties of the
interface class with the following constructor Transaction() that has fields tCode, date
and amount.
c. Create an object in the main method that implements the interface.

3. How is Interface used during runtime?


89
LESSON 9
ADVANCED WINDOW APPLICATION
Learning Outcomes

After successful completion of the lesson you should be able to:


1. Use Visual Studio to design a user interface.
2. Use command and event driven programming.

Course Materials

9.1 Windows Form

You will be presented with a blank form. This document assumes that you have the
Toolbox pane visible on the left of the screen and the Properties on the right. These panes can
be moved around and hidden. This pane contains common controls which make up the elements
on the form.

To make a blank form, click the File tab > New > Project and choose Windows Form Applications
as shown below.

Then type your Form’s name and hit the OK button.


90
9.1.1 Forms Designer

The drag-drop interface is generally referred to as the Forms Designer.

• The Forms Designer will be available any time a Windows Forms class has been added
to a project.
• It can be opened by selecting the View Designer icon from the Solution Explorer window.

9.1.2 Using the Forms Designer

The Forms Designer allows a programmer to drag and drop controls from a toolbox onto a form.
• If the toolbox isn't visible, you can select it from the View | Toolbox menu.

You can modify the properties of a control using the Properties window (shown in the lower right).
• If the Properties Window isn't visible, you can select it from the View | Properties Window
menu.
91
• The properties can be shown by category or alphabetically be selecting an icon from the
Properties Window toolbar.

9.2 Menus, Tabbed windows and Multiple document interface (MDI) programs

The System.Windows.Forms namespace supports multiple document interface (MDI)


applications, and the MenuStrip control supports menu merging. MDI forms can also ToolStrip
controls.

Demonstration

1. We begin by creating a new C# Windows Forms Application project named Calculator in the
Demos directory. Leave unchecked “Create directory for solution.”
92

2. We then rename the source file for the form to MainForm.cs. You will be asked if you want to
rename the corresponding code elements. Say yes.

3. To verify that the required code elements have been renamed, build and run the application.
You should see a bare form, which can be resized.

4. We will use the toolbox to drag a button control to the form. To make everything look nifty, we
will resize the form.
93

5. We want to make sure the following property values are set for the button and form:

Object Name Property Text Property


Label lblNum1 Integer 1:
Label lblNum2 Integer 2:
TextBox txtNum1
TextBox txtNum2
Button btnCalculate Calculate
Label lblResult Result:
TextBox txtResult
Form MainForm Calculator

6. We need to trap the Click event for the btnCalculate button. To do this, we can double-click on
the btnCalculate button. It will write the Click event handler and delegate for us and position us at
the handler function in the code window.
94

7. Finally, when the program is executed it display the following:

The toolbox provides a lot of object that can be used in Graphical User Interface.
95

Useful links for Advance Window Applications

Menus: https://www.youtube.com/watch?v=w1FYv3_asTw
Multiple-Document Interface : https://www.youtube.com/watch?v=-4EYhC9xDHo
ListView and Treeview: https://www.youtube.com/watch?v=AdelSRDZSQI
CheckBox, ListBox, ComboBox : https://www.youtube.com/watch?v=J0_9COVeT4w

Activities/Assessments

All class assignments and activities should be submitted via google classroom website on
or before the due date. The solutions to the programming problems must include full working
code, not just an output of your program. You can work in a group with maximum members
of 4.

1. Design a user Interface the computes the grade of the students using the Toolbox in Visual
Studio.
2. Implement command such as compute, reset and cancel and employ the event driven
programming.
96
LESSON 10
DATA CONNECTION

Learning Outcomes

After successful completion of the lesson you should be able to:


1. Connect the form to a database.
2. Perform Queries to database with user interface.

Course Materials

10.1 Prerequisites

To create the application, you'll need:

• Visual Studio.
• SQL Server Express LocalDB. If you don't have SQL Server Express LocalDB, you can
install it from the SQL Server Express download page.

10.2 Setting up a Database

Create a database name as Employee using SQL SERVER. Create a Table name as
EmployeeDetails in this table create following fields.

10.3 Working with the Data

1. Open VS.net / Select C# / Windows Application / Rename Form1.cs as EmployeeDetails.


2. Make the design of the form as Follows.

3. Add the following Code


97
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace IUDS_SimpleCS
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial
Catalog=Employee;Integrated Security=True");

private void btnAdd_Click(object sender, EventArgs e)


{
try
{
if (txtEmpName.Text == "" || txtEmpDegn.Text == "" || txtSalary.Text ==
"")
{
MessageBox.Show("All Fields Are Compulsory");
}
else
{
SqlCommand cmdinsert = new SqlCommand("Insert into EmployeeDetails
values( ' " + txtEmpName.Text + " ','" + txtEmpDegn.Text + "','" + txtSalary.Text + "'
)", con);
con.Open();
cmdinsert.CommandType = CommandType.Text;
cmdinsert.ExecuteNonQuery();
MessageBox.Show("Data Inserted");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}

private void btnUpdate_Click(object sender, EventArgs e)


{
try
98
{
if (txtempid.Text == "")
{
MessageBox.Show("Enter Employee Id To Update");
}
else
{
SqlCommand cmdupdate = new SqlCommand("Update EmployeeDetails SET
EmpName='" + txtEmpName.Text + "',EmpDesgn='" + txtEmpDegn.Text + "' ,EmpSalary='" +
txtSalary.Text + "' where EmpId=" + txtempid.Text + "", con);
con.Open();
cmdupdate.CommandType = CommandType.Text;
cmdupdate.ExecuteNonQuery();
MessageBox.Show("Data Updated");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
private void btnDel_Click(object sender, EventArgs e)
{
try
{
if (txtempid.Text == "")
{
MessageBox.Show("Enter Employee Id To Delete");
}
else
{
SqlCommand cmddel = new SqlCommand("Delete EmployeeDetails where
EmpId=" + txtempid.Text + "", con);
con.Open();
cmddel.CommandType = CommandType.Text;
cmddel.ExecuteNonQuery();
MessageBox.Show("Data Deleted");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
99

private void btnSelect_Click(object sender, EventArgs e)


{
try
{
if (txtempid.Text == "")
{
MessageBox.Show("Enter Employee Id To Search");
}
else
{
SqlCommand cmd = new SqlCommand("Select * From EmployeeDetails where
EmpId=" + txtempid.Text + "", con);
con.Open();

cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
txtEmpName.Text = dr[1].ToString();
txtEmpDegn.Text = dr[2].ToString();
txtSalary.Text = dr[3].ToString();
}
dr.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}

private void btnReset_Click(object sender, EventArgs e)


{
foreach (Control T in Controls)
{
if (T is TextBox)
{
T.Text = "";
}
}
}
}
}

Video Tutorials

CRUD using C# : https://youtu.be/KZLgVilsqN0


Connecting C# Windows Forms to SQL : https://youtu.be/O6km3N7ECgM
100

Activities/Assessments

All class assignments and activities should be submitted via google classroom website on
or before the due date. The solutions to the programming problems must include full working
code, not just an output of your program. You can work in a group with maximum members
of 4.

1. Using the Interface you designed with calculation in Activity under Lesson 9. Create a
database and connect it with the data source.
2. Now add buttons such as Save, Update, Delete and Select with necessary commands to
manipulate data in the data source created in Item number 1 of this lesson.
101

Projects

Midterm

Case Study – By GROUP (of FOUR)

A hospital supply company wants to market a program to assist with the calculation of intravenous
rates. Design and implement a program that interacts with the user as follows:

INTRAVENOUS RATE ASSISTANT SAMPLE OUTPUT

Enter the number of the problem you wish to solve.


GIVEN A MEDICAL ORDER IN CALCULATE RATE IN
(1) ml/hr & tubing drop factor drops / min
(2) 1 L for n hr ml / hr
(3) mg/kg/hr & concentration in mg/ml ml / hr
(4) units/hr & concentration in units/ml ml / hr
(5) QUIT

Problem =>1
Enter rate in ml/hr=>150
Enter tubing’s drop factor (drops/ml)=> 15
The drop rate per minute is 38.

Enter the number of the problem you wish to solve.


GIVEN A MEDICAL ORDER IN CALCULATE RATE IN
(1) ml/hr & tubing drop factor drops / min
(2) 1 L for n hr ml / hr
(3) mg/kg/hr & concentration in mg/ml ml / hr
(4) units/hr & concentration in units/ml ml / hr
(5) QUIT

Problem => 2
Enter number of hours=> 8
The rate in milliliters per hour is 125.

Enter the number of the problem you wish to solve.


GIVEN A MEDICAL ORDER IN CALCULATE RATE IN
(1) ml/hr & tubing drop factor drops / min
(2) 1 L for n hr ml / hr
(3 )mg/kg/hr & concentration in mg/ml ml / hr
(4) units/hr & concentration in units/ml ml / hr
(5) QUIT
102
Problem => 3
Enter rate in mg/kg/hr=> 0.6
Enter patient weight in kg=> 70
Enter concentration in mg/ml=> 1
The rate in milliliters per hour is 42.

Enter the number of the problem you wish to solve.


GIVEN A MEDICAL ORDER IN CALCULATE RATE IN
(1) ml/hr & tubing drop factor drops / min
(2) 1 L for n hr ml / hr
(3) mg/kg/hr & concentration in mg/ml ml / hr
(4) units/hr & concentration in units/ml ml / hr
(5) QUIT

Problem => 4
Enter rate in units/hr=> 1000
Enter concentration in units/ml=> 25
The rate in milliliters per hour is 40.

Enter the number of the problem you wish to solve.


GIVEN A MEDICAL ORDER IN CALCULATE RATE IN
(1) ml/hr & tubing drop factor drops / min
(2) 1 L for n hr ml / hr
(3) mg/kg/hr & concentration in mg/ml ml / hr
(4) units/hr & concentration in units/ml ml / hr
(5) QUIT

Problem => 5

Implement the following methods

• get_problem – Displays the user menu, then inputs and returns as the function value the
problem number selected.
• get_rate_drop_factor – Prompts the user to enter the data required for problem 1 and
sends this data back to the calling module via output parameters.
• get_kg_rate_conc – Prompts the user to enter the data required for problem3 and sends
this data back to the calling module via output parameters.
• get_units_conc – Prompts the user to enter the data required for problem 4 and sends
this data back to the calling module via output parameters.
• fig_drops_min – Takes rate and drop factor as input parameters and returns drops/min
(rounded to nearest whole drop) as function value.
• fig_ml_hr – Takes as an input parameter the number of hours over which one liter is to
be delivered and returns ml/hr (rounded) as function value.
• by_weight – Takes as input parameters rate in mg/kg/hr, patient weight in kg, and
concentration of drug in mg/ml and returns ml/hr (rounded) as function value.
• by_units – Takes as input parameters rate in units/hr and concentration in units/ml and
returns ml/hr (rounded) as function value.
103
Finals

Create a Windows Applications for a businesses, offices or organization that uses Graphic User
Interface (GUI) objects with database. It should include the following operation:

Modules:

• Create
• Read
• Update
• Delete
• Select
• View
• Login/Logout

You can work in a group with maximum members of 4.


104
GRADING SYSTEM

FIRST GRADING

Class Standing (70%): Online Quizzes, Machine Problems, Activities and Assessments,
Projects
Midterm Examination (30%)

SECOND GRADING

Class Standing (70%): Online Quizzes, Machine Problems, Activities and Assessments,
Projects
Final Examination (30%)

FINAL GRADE = (FIRST GRADING + SECOND GRADING) / 2


105
REFERENCES

Abstract and Sealed Classes and Class Members (C# Programming Guide). (2015, July 20).
Retrieved from microsoft.com: https://docs.microsoft.com/en-
us/dotnet/csharp/programming-guide/classes-and-structs/abstract-and-sealed-classes-
and-class-members
C# - Encapsulation. (n.d.). Retrieved from tutorialspoint.com:
https://www.tutorialspoint.com/csharp/pdf/csharp_encapsulation.pdf
C# - Inheritance. (n.d.). Retrieved September 25, 2020, from tutorialspoint.com:
https://www.tutorialspoint.com/csharp/pdf/csharp_inheritance.pdf
C# - Static Class, Methods, Constructors, Fields. (n.d.). Retrieved September 24, 2020, from
tutorialsteacher.com: https://www.tutorialsteacher.com/csharp/csharp-static
C# Access Modifiers (Public, Private, Protected, Internal). (n.d.). Retrieved September 25, 2020,
from .tutlane.com: https://www.tutlane.com/tutorial/csharp/csharp-access-modifiers-
public-private-protected-internal
C# Classes and Objects. (n.d.). Retrieved September 24, 2020, from w3schools.com:
https://www.w3schools.com/cs/cs_classes.asp
C# Constructors. (n.d.). Retrieved September 24, 2020, from w3schools.com:
https://www.w3schools.com/cs/cs_constructors.asp
C# foreach loop. (n.d.). Retrieved September 24, 2020, from programiz.com:
https://www.programiz.com/csharp-programming/foreach-loop
C# Method Overloading. (n.d.). Retrieved September 24, 2020, from w3schools.com:
https://www.w3schools.com/cs/cs_method_overloading.asp
C# Method Parameters. (n.d.). Retrieved September 24, 2020, from w3schools.com:
https://www.w3schools.com/cs/cs_method_parameters.asp
C# Methods. (n.d.). Retrieved September 24, 2020, from tutorialspoint.com:
http://www.tutorialspoint.com/csharp/csharp_methods.htm
C# Type Casting. (n.d.). Retrieved September 24, 2020, from w3schools.com:
https://www.w3schools.com/cs/cs_type_casting.asp
C# User Input. (n.d.). Retrieved September 24, 2020, from w3schools.com:
https://www.w3schools.com/cs/cs_user_input.asp
C#-Exception Handling. (n.d.). Retrieved September 24, 2020, from tutorialspoint.com:
https://www.tutorialspoint.com/csharp/pdf/csharp_exception_handling.pdf
Control Statements. (n.d.). Retrieved September 23, 2020, from myweb.sabanciuniv.edu:
http://myweb.sabanciuniv.edu/gulsend/files/2009/04/control.pdf
c-sharpcorner.com. (n.d.). Jagged Array in C#. Retrieved September 24, 2020, from c-
sharpcorner.com: https://www.c-sharpcorner.com/UploadFile/puranindia/jagged-arrays-
in-C-Sharp-net/
Jump Statements in C#. (n.d.). Retrieved September 24, 2020, from idc-online.com:
http://www.idc-
online.com/technical_references/pdfs/information_technology/Jump_statements_in_Csh
arp.pdf
Klousen, P. (2012). Introduction to programming and the C# language. Poul Klausen &
bookboon.com. Retrieved September 23, 2020, from bookboon.com
Method Hiding in C#. (n.d.). Retrieved from geeksforgeeks.org:
https://www.geeksforgeeks.org/method-hiding-in-c-sharp/
Polymorphism (C# Programming Guide). (n.d.). Retrieved September 27, 2020, from
microsoft.com: https://docs.microsoft.com/en-us/dotnet/csharp/programming-
guide/classes-and-structs/polymorphism
tutorialspoint.com. (n.d.). C# - Arrays. Retrieved September 24, 2020, from tutorialspoint.com:
https://www.tutorialspoint.com/csharp/csharp_arrays.htm
106
tutorialspoint.com. (n.d.). C# - Multidimensional Arrays. Retrieved September 24, 2020, from
tutorialspoint.com:
https://www.tutorialspoint.com/csharp/csharp_multi_dimensional_arrays.htm
tutorialspoint.com. (n.d.). Jagged Arrays. Retrieved September 24, 2020, from tutorialspoint.:
https://www.tutorialspoint.com/csharp/csharp_jagged_arrays.htm
Vatsa, A. K. (2019, February 24). Static Method In C#. Retrieved September 24, 2020, from .c-
sharpcorner.com: https://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/static-
methods-in-C-Sharp/

(C# Access Modifiers (Public, Private, Protected, Internal), n.d.)


(Method Hiding in C#, n.d.)
(C# - Inheritance)
(C# - Encapsulation)
(C# Constructors, n.d.)
(C# Classes and Objects, n.d.)
(C# Methods, n.d.)
(C# Method Parameters, n.d.)
(C# Method Overloading, n.d.)
(Vatsa, 2019)
(C# - Static Class, Methods, Constructors, Fields, n.d.)
(Klousen, 2012)
(Control Statements)
(C# Type Casting, n.d.)
(C# User Input, n.d.)
(C# foreach loop, n.d.)
(C#-Exception Handling)
(Jump Statements in C#)
(tutorialspoint.com, C# - Arrays)
(tutorialspoint.com, C# - Multidimensional Arrays, n.d.)
(tutorialspoint.com, Jagged Arrays, n.d.)
(c-sharpcorner.com, n.d.)
(Polymorphism (C# Programming Guide), n.d.)
(Abstract and Sealed Classes and Class Members (C# Programming Guide), 2015)
(C# Fragile Classes, n.d.)
(Explicit Interface Implementation (C# Programming Guide), 2020)

You might also like