Sei sulla pagina 1di 228

New Zealand Diploma in Information

Technology Technical Support


Level 5

SOF535
Application Design and Development
20 Credits

Version 1.4 - 2017

Page 1 of 228
Page 2 of 228
Course Book Version Control

This section is used to identify the version of the course book and the history of
development moderation and approval processes.

Programme Name New Zealand Diploma in Information Technology Technical


Support

Course Number and SOF535 Application Design and Development


Title

Level 5

Number of credits 20

Ver. Prepared Proofread Moderated Minor Major Approval Next


by by by amends revisions date revision
accepted approved due
by HOF or by
Academic
Programme Board
Committee

1.0 Athar

Page 3 of 228
Table of Contents
1. Introduction to Application Design and Development .................................................. 7
Introduction .................................................................................................................................. 7
The Software Process, models and methodlogies .......................................................................... 7
Requirement and Design fundamentals ....................................................................................... 16
2. HCI and UI Development for an Application Design and Development....................... 33
Introduction to HCI ...................................................................................................................... 33
HCI Theories and principles.......................................................................................................... 35
Human Centred Software Development ...................................................................................... 51
Hypertext, Multimedia and The World Wide Web ....................................................................... 63
Delivery technology ..................................................................................................................... 64
DYNAMIC WEB CONTENT – CMS (Content Management System) ................................................ 67
3. Introduction to Object Oriented Programming (C#) using integrated development
environments (IDEs) ........................................................................................................... 71
Programming paradigms.............................................................................................................. 71
C# - an objected oriented paradigm ............................................................................................. 79
C# - the programming environment ............................................................................................. 80
From source code to running application ..................................................................................... 83
4. C#- Language Basics & Introduction to Windows Forms ............................................. 89
The first C# program .................................................................................................................... 89
Basic Syntax ................................................................................................................................. 90
C# Types ...................................................................................................................................... 93
Type Conversions ........................................................................................................................ 99
Variables ................................................................................................................................... 102
Operators .................................................................................................................................. 106
Statements ................................................................................................................................ 117
Interfaces .................................................................................................................................. 118
Namespaces .............................................................................................................................. 120
Let’s Start C# Graphical User Interface (GUI) .............................................................................. 121
5. Basic C# Data Structures ............................................................................................ 137
Arrays ........................................................................................................................................ 137
5.2 C# - Array Class .................................................................................................................... 141
ArrayList .................................................................................................................................... 143
Structures .................................................................................................................................. 145
6. Selection Control in C# .............................................................................................. 148
if and if …else and nested if else ................................................................................................ 148
The switch statement ................................................................................................................ 150
7. Implementing iteration in C#..................................................................................... 152
Access levels ..................................................................................... Error! Bookmark not defined.
while and do-while loops ........................................................................................................... 152
for loops .................................................................................................................................... 153

Page 4 of 228
foreach loops............................................................................................................................. 154
Loop Control Statements (aka Jump Statements) ....................................................................... 154
8. Encapsulation ............................................................................................................ 157
9. Methods .................................................................................................................... 159
Defining Methods in C# ............................................................................................................. 159
Example..................................................................................................................................... 160
Calling Methods in C# ................................................................................................................ 160
Recursive Method Call ............................................................................................................... 163
Passing Parameters to a Method ............................................................................................... 165
10. Classes ....................................................................................................................... 169
Defining a Class ......................................................................................................................... 169
Member Functions and Encapsulation ....................................................................................... 171
C# Constructors ......................................................................................................................... 174
C# Destructors ........................................................................................................................... 177
Static Members of a C# Class ..................................................................................................... 178
11. Inheritance and Polymorphism ................................................................................. 181
Inheritance ................................................................................................................................ 181
Polymorphism ........................................................................................................................... 182
Method overriding..................................................................................................................... 187
Method Overloading ................................................................................................................. 189
12. Exception Handling .................................................................................................... 190
Syntax ....................................................................................................................................... 190
Exception Classes in C# .............................................................................................................. 191
Handling Exceptions .................................................................................................................. 192
Creating User-Defined Exceptions.............................................................................................. 193
Throwing Objects ...................................................................................................................... 195
13. Integrating Media Design and Interactivity ............................................................... 196
Introduction .............................................................................................................................. 196
What are affective aspects? ....................................................................................................... 196
Expressive interfaces ................................................................................................................. 196
User frustration ......................................................................................................................... 198
14. Addressing ICT Security and Risks ............................................................................. 209
Introduction .............................................................................................................................. 209
Factors affecting security of ICT systems .................................................................................... 209
The three pillars of ICT security .................................................................................................. 209
Addressing Risk.......................................................................................................................... 211
Risk Acceptance ..................................................................................................................... 211
Quantitative vs. Qualitative Risk Analysis ................................................................................... 211
Quantitative Risk Analysis .......................................................................................................... 211
Qualitative Risk Analysis ............................................................................................................ 212
Quantifying and Qualifying Threats ............................................................................................ 213
15. Testing and Deployment of the Application .............................................................. 217
Introduction .............................................................................................................................. 217
Testing Objectives ..................................................................................................................... 217
Testing Principles ....................................................................................................................... 217
Black Box Testing vs White Box Testing ...................................................................................... 218
Alpha and Beta Testing .............................................................................................................. 218

Page 5 of 228
Manual Testing vs Automation Testing ...................................................................................... 219
What are Test Cases? ................................................................................................................ 220
Unit Testing ............................................................................................................................... 220
System Testing .......................................................................................................................... 224
Software Deployment ................................................................................................................ 225
16. Testing, Publishing and Deployment of the Application.... Error! Bookmark not defined.
Testing principles.............................................................................. Error! Bookmark not defined.
Black box/white box ......................................................................... Error! Bookmark not defined.
Alpha/beta testing ............................................................................ Error! Bookmark not defined.
Manual Testing/Automation testing ................................................. Error! Bookmark not defined.
Overview of popular testing packages .............................................. Error! Bookmark not defined.
Unit Testing/Systems Testing/UAT .................................................... Error! Bookmark not defined.
References ........................................................................................................................ 228

Page 6 of 228
1. Introduction to Application Design and
Development
Introduction
Software engineering can be defined as the establishment and use of sound engineering
principles in order to obtain economically software that is reliable and works efficiently on
real machines.

The IEEE has developed a more comprehensive definition when it states:

Software Engineering: (1) The application of a systematic, disciplined, quantifiable approach


to the development, operation, and maintenance of software; that is, the application of
engineering to software. (2) The study of approaches as in (1).

The Software Process, models and methodlogies


A common software process framework is established by defining a small number of
framework activities that are applicable to all software projects, regardless of their size or
complexity. A number of task sets—each a collection of software engineering work tasks,
project milestones, work products, and quality assurance points—enable the framework
activities to be adapted to the characteristics of the software project and the requirements
of the project team. Finally, umbrella activities—such as software quality assurance,
software configuration management, and measurement2—overlay the process model.
Umbrella activities are independent of any one framework activity and occur throughout
the process.

Now, in the subsequent sections we will describe the popular software development models
and methodologies.

Waterfall Model
Sometimes called the classic life cycle or the waterfall model, the linear sequential model
suggests a systematic, sequential approach to software development that begins at the
system level and progresses through analysis, design, coding, testing, and support. Figure
below illustrates the linear sequential model for software engineering. Modeled after a
conventional engineering cycle, the linear sequential model encompasses the following
activities:

System/information engineering and modeling.


Because software is always part of a larger system (or business), work begins by
establishing requirements for all system elements and then allocating some subset of
these requirements to software. This system view is essential when software must
interact with other elements such as hardware, people, and databases. System
engineering and analysis encompass requirements gathering at the system level with a
small amount of top level design and analysis. Information engineering encompasses
requirements gathering at the strategic business level and at the business area level

Software requirements analysis.


The requirements gathering process is intensified and focused specifically on software.
To understand the nature of the program(s) to be built, the software engineer

Page 7 of 228
("analyst") must understand the information domain for the software, as well as
required function, behavior, performance, and interface. Requirements for both the
system and the software are documented and reviewed with the customer.
Design.

Software design is actually a multistep process that focuses on four distinct


attributes of a program: data structure, software architecture, interface representations,
and procedural (algorithmic) detail. The design process translates requirements into a
representation of the software that can be assessed for quality before coding begins.
Like requirements, the design is documented and becomes part of the software
configuration.

Code generation.
The design must be translated into a machine-readable form. The code generation step
performs this task. If design is performed in a detailed manner, code generation can be
accomplished mechanistically.

Testing.
Once code has been generated, program testing begins. The testing process
focuses on the logical internals of the software, ensuring that all statements have
been tested, and on the functional externals; that is, conducting tests to uncover
errors and ensure that defined input will produce actual results that agree with required
results.

Support.
Software will undoubtedly undergo change after it is delivered to the customer (a
possible exception is embedded software). Change will occur because errors
have been encountered, because the software must be adapted to accommodate
changes in its external environment (e.g., a change required because of a new operating
system or peripheral device), or because the customer requires functional or
performance enhancements. Software support/maintenance reapplies each of the
preceding phases to an existing program rather than a new one

Page 8 of 228
Rapid Application Development (RAD)
Rapid application development (RAD) is an incremental software development process
model that emphasizes an extremely short development cycle. The RAD model is a “high-
speed” adaptation of the linear sequential model in which rapid development is achieved by
using component-based construction. If requirements are well understood and project
scope is constrained, the RAD process enables a development team to create a “fully
functional system” within very short time periods (e.g., 60 to 90 days)

Used primarily for information systems applications, the RAD approach encompasses the
following phases:

Business modeling.
The information flow among business functions is modeled in a way that answers the
following questions: What information drives the business process? What information is
generated? Who generates it? Where does the information go? Who processes it?

Data modeling.
The information flow defined as part of the business modeling phase is refined into a set
of data objects that are needed to support the business. The characteristics (called
attributes) of each object are identified and the relationships between
these objects defined.

Process modeling.
The data objects defined in the data modeling phase are transformed to achieve the
information flow necessary to implement a business function. Processing descriptions
are created for adding, modifying, deleting, or retrieving a
data object.

Application generation.
RAD assumes the use of fourth generation techniques. Rather than creating software
using conventional third generation programming languages the RAD process works to
reuse existing program components (when possible) or create reusable components
(when necessary). In all cases, automated tools are used to facilitate construction of the
software.

Testing and turnover.


Since the RAD process emphasizes reuse, many of the program components have already
been tested. This reduces overall testing time. However, new components must be tested
and all interfaces must be fully exercised

The following figure gives a representation of the RAD model.

Page 9 of 228
Spiral Model
The spiral model, originally proposed by Boehm [BOE88], is an evolutionary software
process model that couples the iterative nature of prototyping with the controlled and
systematic aspects of the linear sequential model. It provides the potential for rapid
development of incremental versions of the software. Using the spiral model, software is
developed in a series of incremental releases. During early iterations, the incremental
release might be a paper model or prototype. During later iterations, increasingly more
complete versions of the engineered system are produced.

A spiral model is divided into a number of framework activities, also called task regions.6
Typically, there are between three and six task regions. Figure <enter figure no.>depicts a
spiral model that contains six task regions:

 Customer communication—tasks required to establish effective communication


between developer and customer.
 Planning—tasks required to define resources, timelines, and other project related
information.
 Risk analysis—tasks required to assess both technical and management risks.
 Engineering—tasks required to build one or more representations of the application.
 Construction and release—tasks required to construct, test, install, and provide user
support (e.g., documentation and training).

Page 10 of 228
 Customer evaluation—tasks required to obtain customer feedback based on
evaluation of the software representations created during the engineering stage and
implemented during the installation stag

Spiral Model Application


The Spiral Model is widely used in the software industry as it is in sync with the natural
development process of any product, i.e. learning with maturity which involves minimum
risk for the customer as well as the development firms.

 The following pointers explain the typical uses of a Spiral Model −


 When there is a budget constraint and risk evaluation is important.
 For medium to high-risk projects.
 Long-term project commitment because of potential changes to economic priorities
as the requirements change with time.
 Customer is not sure of their requirements which is usually the case.
 Requirements are complex and need evaluation to get clarity.
 New product line which should be released in phases to get enough customer
feedback.
 Significant changes are expected in the product during the development cycle.

Spiral Model - Pros and Cons


The advantage of spiral lifecycle model is that it allows elements of the product to be added
in, when they become available or known. This assures that there is no conflict with
previous requirements and design.

This method is consistent with approaches that have multiple software builds and releases
which allows making an orderly transition to a maintenance activity. Another positive aspect

Page 11 of 228
of this method is that the spiral model forces an early user involvement in the system
development effort.

On the other side, it takes a very strict management to complete such products and there is
a risk of running the spiral in an indefinite loop. So, the discipline of change and the extent
of taking change requests is very important to develop and deploy the product successfully.

The advantages of the Spiral SDLC Model are as follows:

 Changing requirements can be accommodated.


 Allows extensive use of prototypes.
 Requirements can be captured more accurately.
 Users see the system early.

Development can be divided into smaller parts and the risky parts can be developed earlier
which helps in better risk management.

The disadvantages of the Spiral SDLC Model are as follows:

 Management is more complex.


 End of the project may not be known early.
 Not suitable for small or low risk projects and could be expensive for small projects.
 Process is complex
 Spiral may go on indefinitely.
 Large number of intermediate stages requires excessive documentation.

Agile Methodology
Agile is a software development methodology to build a software incrementally using short
iterations of 1 to 4 weeks so that the development is aligned with the changing business
needs. This simple tutorial uses appropriate examples to help you understand agile
development in a general and quick way.

You can read the famous Agile Manifesto here --> http://agilemanifesto.org

Agile basics
Agile is a software development methodology to build a software incrementally using
short iterations of 1 to 4 weeks so that the development process is aligned with the
changing business needs. Instead of a single-pass development of 6 to 18 months where
all the requirements and risks are predicted upfront, Agile adopts a process of frequent
feedback where a workable product is delivered after 1 to 4 week iteration.

The following figure below compares the traditional methodology with agile.

Page 12 of 228
Roles in Agile
1. Scrum Master

A Scrum Master is a team leader and facilitator who helps the team members to follow
agile practices so that they can meet their commitments. The responsibilities of a scrum
master are as follows −

To enable close co-operation between all roles and functions.

 To remove any blocks.


 To shield the team from any disturbances.
 To work with the organization to track the progress and processes of the company.
 To ensure that Agile Inspect & Adapt processes are leveraged properly which
includes
o Daily stand-ups,
o Planned meetings,
o Demo
o Review,
o Retrospective Meetings, and
o To facilitate team meetings and decision-making process.

2. Product Owner

A Product Owner is the one who drives the product from business perspective. The
responsibilities or a Product Owner are as follows −

 To define the requirements and prioritize their values.


 To determine the release date and contents.

Page 13 of 228
 To take an active role in iteration planning and release planning meetings.
 To ensure that team is working on the most valued requirement.
 To represent the voice of the customer.
 To accept the user stories that meet the definition of done and defined acceptance
criteria.

Cross-functional Team
Every agile team should be a self-sufficient team with 5 to 9 team members and an
average experience ranging from of 6 to 10 years. Typically, an agile team comprises of 3
to 4 developers, 1 tester, 1 technical lead, 1 product owner and 1 scrum master.

Product Owner and Scrum master are considered to be a part of Team Interface, whereas other members are
part of Technical Interface.

How an Agile Team Plans its Work?


An Agile team works in iterations to deliver user stories where each iteration is of 10 to
15 days. Each user story is planned based on its backlog prioritization and size. The team
uses its capacity − how many hours are available with team to work on tasks − to decide
how much scope they have to plan.

Point:

Page 14 of 228
A Point defines how much a team can commit. A point usually refers to 8 hours. Each
story is estimated in points.

Capacity:
Capacity defines how much an individual can commit. Capacity is estimated in hours.

What is a User Story?


A user story is a requirement which defines what is required by the user as functionality.
A user story can be in two forms −

 As a <User Role> I want <Functionality> so that <Business Value>


 In order to <Business value> as a <User Role> I want <Functionality>

During release planning, a rough estimate is given to a user story using relative scale as
points. During iteration planning, the story is broken down into tasks.

Relationship of User Stories and Tasks


 User story talks about what is to be done. It defines what a user needs.
 Task talks about how it is to be done. It defines how a functionality is to be
implemented.
 Stories are implemented by tasks. Each story is a collection of tasks.
 User story is divided into tasks when it is planned in current iteration.
 Tasks are estimated in hours, typically from 2 to 12 hours.
 Stories are validated using acceptance tests.

When a Story is Done


The team decides what done means. The criteria may be −

 All tasks (development, testing) are completed.


 All acceptance tests are running and are passed.
 No defect is open.
 Product owner has accepted the story.
 Deliverable to the end-user.

What is Acceptance Criteria?


Criteria defines the functionality, behavior, and performance required by a feature so
that it can be accepted by the product owner. It defines what is to be done so that the
developer knows when a user story is complete.

Page 15 of 228
How the Requirements are Defined?
Requirements are defined as

 A User Story,
 With Acceptance Criteria, and
 Tasks to implement the story.

Requirement and Design fundamentals


The software requirements are description of features and functionalities of the target
system. Requirements convey the expectations of users from the software product. The
requirements can be obvious or hidden, known or unknown, expected or unexpected from
client’s point of view.

Requirement Engineering
The process to gather the software requirements from client, analyze and document them is
known as requirement engineering.

The goal of requirement engineering is to develop and maintain sophisticated and


descriptive ‘System Requirements Specification’ document.

Requirement Engineering Process


It is a four step process, which includes –

 Feasibility Study
 Requirement Gathering
 Software Requirement Specification
 Software Requirement Validation

Let us see the process briefly -

Feasibility study
When the client approaches the organization for getting the desired product developed,
it comes up with rough idea about what all functions the software must perform and
which all features are expected from the software.

Referencing to this information, the analysts does a detailed study about whether the
desired system and its functionality are feasible to develop.

This feasibility study is focused towards goal of the organization. This study analyzes
whether the software product can be practically materialized in terms of
implementation, contribution of project to organization, cost constraints and as per
values and objectives of the organization. It explores technical aspects of the project and
product such as usability, maintainability, productivity and integration ability.

The output of this phase should be a feasibility study report that should contain
adequate comments and recommendations for management about whether or not the
project should be undertaken.

Requirement Gathering

Page 16 of 228
If the feasibility report is positive towards undertaking the project, next phase starts
with gathering requirements from the user. Analysts and engineers communicate with
the client and end-users to know their ideas on what the software should provide and
which features they want the software to include.

Software Requirement Specification (SRS)


SRS is a document created by system analyst after the requirements are collected from
various stakeholders.

SRS defines how the intended software will interact with hardware, external interfaces,
speed of operation, response time of system, portability of software across various
platforms, maintainability, speed of recovery after crashing, Security, Quality,
Limitations etc.

Have a look at the IEEE SRS document on the internet

The requirements received from client are written in natural language. It is the responsibility
of system analyst to document the requirements in technical language so that they can be
comprehended and useful by the software development team.

SRS should come up with following features:

 User Requirements are expressed in natural language.


 Technical requirements are expressed in structured language, which is used inside
the organization.
 Design description should be written in Pseudo code.
 Format of Forms and GUI screen prints.
 Conditional and mathematical notations for DFDs etc.

Software Requirement Validation


After requirement specifications are developed, the requirements mentioned in this
document are validated. User might ask for illegal, impractical solution or experts may
interpret the requirements incorrectly. This results in huge increase in cost if not nipped in
the bud. Requirements can be checked against following conditions -

 If they can be practically implemented


 If they are valid and as per functionality and domain of software
 If there are any ambiguities
 If they are complete
 If they can be demonstrated

Requirement Elicitation Process


Requirement elicitation process can be depicted using the following diagram:

Page 17 of 228
 Requirements gathering - The developers discuss with the client and end users and
know their expectations from the software.
 Organizing Requirements - The developers prioritize and arrange the requirements
in order of importance, urgency and convenience.
 Negotiation & discussion - If requirements are ambiguous or there are some
conflicts in requirements of various stakeholders, if they are, it is then negotiated
and discussed with stakeholders. Requirements may then be prioritized and
reasonably compromised. The requirements come from various stakeholders. To
remove the ambiguity and conflicts, they are discussed for clarity and correctness.
Unrealistic requirements are compromised reasonably.
 Documentation - All formal & informal, functional and non-functional requirements
are documented and made available for next phase processing.

Requirement Elicitation Techniques


Requirements Elicitation is the process to find out the requirements for an intended
software system by communicating with client, end users, system users and others who
have a stake in the software system development.

There are various ways to discover requirements

Interviews
Interviews are strong medium to collect requirements. Organization may conduct
several types of interviews such as:

 Structured (closed) interviews, where every single information to gather is decided


in advance, they follow pattern and matter of discussion firmly.
 Non-structured (open) interviews, where information to gather is not decided in
advance, more flexible and less biased.
 Oral interviews
 Written interviews
 One-to-one interviews which are held between two persons across the table.
 Group interviews which are held between groups of participants. They help to
uncover any missing requirement as numerous people are involved.

Surveys
Organization may conduct surveys among various stakeholders by querying about their
expectation and requirements from the upcoming system.

Questionnaires
A document with pre-defined set of objective questions and respective options is
handed over to all stakeholders to answer, which are collected and compiled.

A shortcoming of this technique is, if an option for some issue is not mentioned in the
questionnaire, the issue might be left unattended.

Page 18 of 228
Task analysis
Team of engineers and developers may analyze the operation for which the new system
is required. If the client already has some software to perform certain operation, it is
studied and requirements of proposed system are collected.

Domain Analysis
Every software falls into some domain category. The expert people in the domain can be
a great help to analyze general and specific requirements.

Brainstorming
An informal debate is held among various stakeholders and all their inputs are recorded
for further requirements analysis.

Prototyping
Prototyping is building user interface without adding detail functionality for user to
interpret the features of intended software product. It helps giving better idea of
requirements. If there is no software installed at client’s end for developer’s reference
and the client is not aware of its own requirements, the developer creates a prototype
based on initially mentioned requirements. The prototype is shown to the client and the
feedback is noted. The client feedback serves as an input for requirement gathering.

Observation
Team of experts visit the client’s organization or workplace. They observe the actual
working of the existing installed systems. They observe the workflow at client’s end and
how execution problems are dealt. The team itself draws some conclusions which aid to
form requirements expected from the software.

Software Requirements Characteristics


Gathering software requirements is the foundation of the entire software development
project. Hence they must be clear, correct and well-defined.

A complete Software Requirement Specifications must be:

 Clear
 Correct
 Consistent
 Coherent
 Comprehensible
 Modifiable
 Verifiable
 Prioritized
 Unambiguous
 Traceable
 Credible source

The Two Kinds of Software Requirements


We should try to understand what sort of requirements may arise in the requirement
elicitation phase and what kinds of requirements are expected from the software system.

Page 19 of 228
Broadly software requirements should be categorized in two categories:

Functional Requirements
Requirements, which are related to functional aspect of software fall into this category.

They define functions and functionality within and from the software system.

EXAMPLES -

 Search option given to user to search from various invoices.


 User should be able to mail any report to management.
 Users can be divided into groups and groups can be given separate rights.
 Should comply business rules and administrative functions.
 Software is developed keeping downward compatibility intact.

Non-Functional Requirements
Requirements, which are not related to functional aspect of software, fall into this
category. They are implicit or expected characteristics of software, which users make
assumption of.

Non-functional requirements include -

 Security
 Logging
 Storage
 Configuration
 Performance
 Cost
 Interoperability
 Flexibility
 Disaster recovery
 Accessibility

Requirements are categorized logically as

 Must Have : Software cannot be said operational without them.


 Should have : Enhancing the functionality of software.
 Could have : Software can still properly function with these requirements.
 Wish list : These requirements do not map to any objectives of software.

While developing software, ‘Must have’ must be implemented, ‘Should have’ is a matter of
debate with stakeholders and negation, whereas ‘could have’ and ‘wish list’ can be kept for
software updates.

Requirement Analysis Tools


Now we will discuss two commonly used requirement analysis tools – Use Case Diagram and
UML-Class Diagram.

Use Case Diagram

Page 20 of 228
The purpose of use case diagram is to capture the dynamic aspect of a system. But this
definition is too generic to describe the purpose.

Because other four diagrams (activity, sequence, collaboration and Statechart) are also
having the same purpose. So we will look into some specific purpose which will distinguish it
from other four diagrams.

Use case diagrams are used to gather the requirements of a system including internal and
external influences. These requirements are mostly design requirements. So when a system
is analyzed to gather its functionalities use cases are prepared and actors are identified.

Now when the initial task is complete use case diagrams are modelled to present the
outside view.

So in brief, the purposes of use case diagrams can be as follows:

 Used to gather requirements of a system.


 Used to get an outside view of a system.
 Identify external and internal factors influencing the system.
 Show the interacting among the requirements are actors.

How to draw Use Case Diagram?


Use case diagrams are considered for high level requirement analysis of a system. So when
the requirements of a system are analyzed the functionalities are captured in use cases.

So we can say that use cases are nothing but the system functionalities written in an
organized manner. Now the second things which are relevant to the use cases are the
actors. Actors can be defined as something that interacts with the system.

The actors can be human user, some internal applications or may be some external
applications. So in a brief when we are planning to draw an use case diagram we should
have the following items identified.

 Functionalities to be represented as an use case


 Actors
 Relationships among the use cases and actors.

Use case diagrams are drawn to capture the functional requirements of a system. So after
identifying the above items we have to follow the following guidelines to draw an efficient
use case diagram.

 The name of a use case is very important. So the name should be chosen in such a
way so that it can identify the functionalities performed.
 Give a suitable name for actors.
 Show relationships and dependencies clearly in the diagram.
 Do not try to include all types of relationships. Because the main purpose of the
diagram is to identify requirements.
 Use note when ever required to clarify some important points.

Page 21 of 228
The following is a sample use case diagram representing the order management system. So
if we look into the diagram then we will find three use cases (Order, SpecialOrder and
NormalOrder) and one actor which is customer.

The SpecialOrder and NormalOrder use cases are extended from Order use case. So they
have extends relationship. Another important point is to identify the system boundary
which is shown in the picture. The actor Customer lies outside the system as it is an external
user of the system.

UML-Class Diagrams
The purpose of the class diagram is to show the types being modeled within the system.
In most UML models these types include:

 a class
 an interface
 a data type
 a component.

UML uses a special name for these types: "classifiers." Generally, you can think of a
classifier as a class, but technically a classifier is a more general term that refers to the
other three types above as well.

Class name
The UML representation of a class is a rectangle containing three compartments stacked
vertically, as shown in Figure 1. The top compartment shows the class's name. The
middle compartment lists the class's attributes. The bottom compartment lists the
class's operations. When drawing a class element on a class diagram, you must use the
top compartment, and the bottom two compartments are optional. (The bottom two
would be unnecessary on a diagram depicting a higher level of detail in which the
purpose is to show only the relationship between the classifiers.) Figure below shows an
airline flight modeled as a UML class. As we can see, the name is Flight, and in the

Page 22 of 228
middle compartment we see that the Flight class has three attributes: flightNumber,
departureTime, and flightDuration. In the bottom compartment we see that the Flight
class has two operations: delayFlight and getArrivalTime.

Class attribute list


The attribute section of a class (the middle compartment) lists each of the class's
attributes on a separate line. The attribute section is optional, but when used it contains
each attribute of the class displayed in a list format. The line uses the following format:

1 name : attribute type

1 flightNumber : Integer

Continuing with our Flight class example, we can describe the class's attributes with the
attribute type information, as shown in Table below.

Attribute Attribute Type


Name

flightNumber Integer

departureTime Date

flightDuration Minutes

In business class diagrams, the attribute types usually correspond to units that make
sense to the likely readers of the diagram (i.e., minutes, dollars, etc.). However, a class
diagram that will be used to generate code needs classes whose attribute types are
limited to the types provided by the programming language, or types included in the
model that will also be implemented in the system.

Sometimes it is useful to show on a class diagram that a particular attribute has a default
value. (For example, in a banking account application a new bank account would start
off with a zero balance.) The UML specification allows for the identification of default
values in the attribute list section by using the following notation:
1 name : attribute type = default value
For example:
1 balance : Dollars = 0
Showing a default value for attributes is optional; Figure 2 shows a Bank Account class
with an attribute called balance, which has a default value of 0.

Page 23 of 228
Class operations list
The class's operations are documented in the third (lowest) compartment of the class
diagram's rectangle, which again is optional. Like the attributes, the operations of a class
are displayed in a list format, with each operation on its own line. Operations are
documented using the following notation:
1 name(parameter list) : type of value returned
The Flight class's operations are mapped in Table below.

Operation Parameters Return Value Type


Name

delayFlight N/A
Name Type

numberOfMinutes Minutes

getArrivalTime N/A Date

The Figure below shows that the delayFlight operation has one input parameter —
numberOfMinutes — of the type Minutes. However, the delayFlight operation does not
have a return value. [Note: The delayFlight does not have a return value because I made
a design decision not to have one. One could argue that the delay operation should
return the new arrival time, and if this were the case, the operation signature would
appear as delayFlight(numberOfMinutes : Minutes) : Date.] When an operation has
parameters, they are put inside the operation's parentheses; each parameter uses the
format "parameter name : parameter type".

Page 24 of 228
When documenting an operation's parameters, you may use an optional indicator to
show whether or not the parameter is input to, or output from, the operation. This
optional indicator appears as an "in" or "out" as shown in the operations compartment
in Figure 3. Typically, these indicators are unnecessary unless an older programming
language such as Fortran will be used, in which case this information can be helpful.
However, in C++ and Java, all parameters are "in" parameters and since "in" is the
parameter's default type according to the UML specification, most people will leave out
the input/output indicators.

Inheritance
A very important concept in object-oriented design, inheritance, refers to the ability of
one class (child class) to inherit the identical functionality of another class (super class),
and then add new functionality of its own. (In a very non-technical sense, imagine that I
inherited my mother's general musical abilities, but in my family I'm the only one who
plays electric guitar.) To model inheritance on a class diagram, a solid line is drawn from
the child class (the class inheriting the behavior) with a closed, unfilled arrowhead (or
triangle) pointing to the super class. Consider types of bank accounts: Figure below
shows how both CheckingAccount and SavingsAccount classes inherit from the
BankAccount class.

In the above figure, the inheritance relationship is drawn with separate lines for each
subclass, which is the method used in IBM Rational Rose and IBM Rational XDE.
However, there is an alternative way to draw inheritance called tree notation. You can
use tree notation when there are two or more child classes, as in Figure 4, except that
the inheritance lines merge together like a tree branch. Figure below below is a
redrawing of the same inheritance shown in Figure 4, but this time using tree notation.

Page 25 of 228
An example of inheritance using tree notation

Abstract classes and operations


The observant reader will notice that the diagrams in Figures 4 and 5 use italicized text for
the BankAccount class name and withdrawal operation. This indicates that the BankAccount
class is an abstract class and the withdrawal method is an abstract operation. In other
words, the BankAccount class provides the abstract operation signature of withdrawal and
the two child classes of CheckingAccount and SavingsAccount each implement their own
version of that operation.

However, super classes (parent classes) do not have to be abstract classes. It is normal for a
standard class to be a super class.

Associations
When you model a system, certain objects will be related to each other, and these
relationships themselves need to be modeled for clarity. There are five types of
associations. I will discuss two of them — bi-directional and uni-directional associations —
in this section, and I will discuss the remaining three association types in the Beyond the
basics section. Please note that a detailed discussion of when to use each type of
association is beyond the scope of this article. Instead, I will focus on the purpose of each
association type and show how the association is drawn on a class diagram.

Bi-directional (standard) association


An association is a linkage between two classes. Associations are always assumed to be bi-
directional; this means that both classes are aware of each other and their relationship,
unless you qualify the association as some other type. Going back to our Flight example,
Figure below shows a standard kind of association between the Flight class and the Plane
class.

Page 26 of 228
An example of a bi-directional association between a Flight class and a Plane class

A bi-directional association is indicated by a solid line between the two classes. At either
end of the line, you place a role name and a multiplicity value. Figure 6 shows that the Flight
is associated with a specific Plane, and the Flight class knows about this association. The
Plane takes on the role of "assignedPlane" in this association because the role name next to
the Plane class says so. The multiplicity value next to the Plane class of 0..1 means that
when an instance of a Flight exists, it can either have one instance of a Plane associated with
it or no Planes associated with it (i.e., maybe a plane has not yet been assigned). Figure
above also shows that a Plane knows about its association with the Flight class. In this
association, the Flight takes on the role of "assignedFlights"; the diagram in Figure 6 tells us
that the Plane instance can be associated either with no flights (e.g., it's a brand new plane)
or with up to an infinite number of flights (e.g., the plane has been in commission for the
last five years).

For those wondering what the potential multiplicity values are for the ends of associations,
Table 3 below lists some example multiplicity values along with their meanings.

Table 3: Multiplicity values and their indicators

Potential Multiplicity Values

Indicator Meaning

0..1 Zero or one

1 One only

0..* Zero or more

* Zero or more

1..* One or more

3 Three only

0..5 Zero to Five

5..15 Five to Fifteen

Uni-directional association

Page 27 of 228
In a uni-directional association, two classes are related, but only one class knows that the
relationship exists. Figure 7 shows an example of an overdrawn accounts report with a uni-
directional association.

Figure 7: An example of a uni-directional association: The OverdrawnAccountsReport class knows about the
BankAccount class, but the BankAccount class does not know about the association

A uni-directional association is drawn as a solid line with an open arrowhead (not the closed
arrowhead, or triangle, used to indicate inheritance) pointing to the known class. Like
standard associations, the uni-directional association includes a role name and a multiplicity
value, but unlike the standard bi-directional association, the uni-directional association only
contains the role name and multiplicity value for the known class. In our example in Figure
7, the OverdrawnAccountsReport knows about the BankAccount class, and the BankAccount
class plays the role of "overdrawnAccounts." However, unlike a standard association, the
BankAccount class has no idea that it is associated with the OverdrawnAccountsReport.
[Note: It may seem strange that the BankAccount class does not know about the
OverdrawnAccountsReport class. This modeling allows report classes to know about the
business class they report, but the business classes do not know they are being reported on.
This loosens the coupling of the objects and therefore makes the system more adaptive to
changes.]

Interfaces
Earlier in this article, I suggested that you think of classifiers simply as classes. In fact, a
classifier is a more general concept, which includes data types and interfaces.

A complete discussion of when and how to use data types and interfaces effectively in a
system's structure diagrams is beyond the scope of this article. So why do I mention data
types and interfaces here? There are times when you might want to model these classifier
types on a structure diagram, and it is important to use the proper notation in doing so, or
at least be aware of these classifier types. Drawing these classifiers incorrectly will likely
confuse readers of your structure diagram, and the ensuing system will probably not meet
requirements.

A class and an interface differ: A class can have an actual instance of its type, whereas an
interface must have at least one class to implement it. In UML 2, an interface is considered
to be a specialization of a class modeling element. Therefore, an interface is drawn just like
a class, but the top compartment of the rectangle also has the text "«interface»", as shown
in Figure 10. [Note: When drawing a class diagram it is completely within UML specification
to put «class» in the top compartment of the rectangle, as you would with «interface»;
however, the UML specification says that placing the "class" text in this compartment is
optional, and it should be assumed if «class» is not displayed.]

Page 28 of 228
Figure 10: Example of a class diagram in which the Professor and Student classes implement the Person
interface

In the diagram shown in Figure 10, both the Professor and Student classes implement the
Person interface and do not inherit from it. We know this for two reasons: 1) The Person
object is defined as an interface — it has the "«interface»" text in the object's name area,
and we see that the Professor and Student objects are class objects because they are
labeled according to the rules for drawing a class object (there is no additional classification
text in their name area). 2) We know inheritance is not being shown here, because the line
with the arrow is dotted and not solid. As shown in Figure 10, a dotted line with a closed,
unfilled arrow means realization (or implementation); as we saw in Figure 4, a solid arrow
line with a closed, unfilled arrow means inheritance.

Aggregation
Aggregation is a special type of association used to model a "whole to its parts" relationship.
In basic aggregation relationships, the lifecycle of a part class is independent from
the whole class's lifecycle.

For example, we can think of Car as a whole entity and Car Wheel as part of the overall Car.
The wheel can be created weeks ahead of time, and it can sit in a warehouse before being
placed on a car during assembly. In this example, the Wheel class's instance clearly lives
independently of the Car class's instance. However, there are times when the part class's
lifecycle is not independent from that of the whole class — this is called composition
aggregation. Consider, for example, the relationship of a company to its departments.
Both Company and Departments are modeled as classes, and a department cannot exist
before a company exists. Here the Department class's instance is dependent upon the
existence of the Company class's instance.

Let's explore basic aggregation and composition aggregation further.

Basic aggregation
An association with an aggregation relationship indicates that one class is a part of another
class. In an aggregation relationship, the child class instance can outlive its parent class. To
represent an aggregation relationship, you draw a solid line from the parent class to the

Page 29 of 228
part class, and draw an unfilled diamond shape on the parent class's association end. Figure
12 shows an example of an aggregation relationship between a Car and a Wheel.

Figure 12: Example of an aggregation association

Composition aggregation
The composition aggregation relationship is just another form of the aggregation
relationship, but the child class's instance lifecycle is dependent on the parent class's
instance lifecycle. In Figure 13, which shows a composition relationship between a Company
class and a Department class, notice that the composition relationship is drawn like the
aggregation relationship, but this time the diamond shape is filled.

Figure 13: Example of a composition relationship

In the relationship modeled in Figure 13, a Company class instance will always have at least
one Department class instance. Because the relationship is a composition relationship,
when the Company instance is removed/destroyed, the Department instance is
automatically removed/destroyed as well. Another important feature of composition
aggregation is that the part class can only be related to one instance of the parent class (e.g.
the Company class in our example).

Reflexive associations
We have now discussed all the association types. As you may have noticed, all our examples
have shown a relationship between two different classes. However, a class can also be
associated with itself, using a reflexive association. This may not make sense at first, but
remember that classes are abstractions. Figure 14 shows how an Employee class could be
related to itself through the manager/manages role. When a class is associated to itself, this
does not mean that a class's instance is related to itself, but that an instance of the class is
related to another instance of the class.

Example of a reflexive association relationship

The relationship drawn in Figure 14 means that an instance of Employee can be the
manager of another Employee instance. However, because the relationship role of
"manages" has a multiplicity of 0..*; an Employee might not have any other Employees to
manage.

Page 30 of 228
Visibility
In object-oriented design, there is a notation of visibility for attributes and operations. UML
identifies four types of visibility: public, protected, private, and package.

The UML specification does not require attributes and operations visibility to be displayed
on the class diagram, but it does require that it be defined for each attribute or operation.
To display visibility on the class diagram, you place the visibility mark in front of the
attribute's or operation's name. Though UML specifies four visibility types, an actual
programming language may add additional visibilities, or it may not support the UML-
defined visibilities. Table 4 displays the different marks for the UML-supported visibility
types.

Mark Visibility type


+ Public
# Protected
- Private
~ Package
Table 4: Marks for UML-supported visibility types

Now, let's look at a class that shows the visibility types indicated for its attributes and
operations. In Figure 15, all the attributes and operations are public, with the exception of
the updateBalance operation. The updateBalance operation is protected.

Figure 15: A BankAccount class that shows the visibility of its attributes and operations

Design Levels
Software design yields three levels of results:

 Architectural Design - The architectural design is the highest abstract version of the
system. It identifies the software as a system with many components interacting
with each other. At this level, the designers get the idea of proposed solution
domain.
 High-level Design- The high-level design breaks the ‘single entity-multiple
component’ concept of architectural design into less-abstracted view of sub-systems
and modules and depicts their interaction with each other. High-level design focuses
on how the system along with all of its components can be implemented in forms of
modules. It recognizes modular structure of each sub-system and their relation and
interaction among each other.
 Detailed Design (Low Level Design)- Detailed design deals with the implementation
part of what is seen as a system and its sub-systems in the previous two designs. It is
more detailed towards modules and their implementations. It defines logical
structure of each module and their interfaces to communicate with other modules.

Page 31 of 228
Page 32 of 228
2. HCI and UI Development for an Application Design
and Development.
Introduction to HCI
HCI (human-computer interaction) is the study of how people interact with computers and
to what extent computers are or are not developed for successful interaction with human
beings. As its name implies, HCI consists of three parts: the user, the computer itself, and
the ways they work together.

User
By "user", we may mean an individual user, a group of users working together. An
appreciation of the way people's sensory systems (sight, hearing, touch) relay information is
vital. Also, different users form different conceptions or mental models about their
interactions and have different ways of learning and keeping knowledge and. In addition,
cultural and national differences play a part.

Computer
When we talk about the computer, we're referring to any technology ranging from desktop
computers, to large scale computer systems. For example, if we were discussing the design
of a Website, then the Website itself would be referred to as "the computer". Devices such
as mobile phones or VCRs can also be considered to be “computers”.

Interaction
There are obvious differences between humans and machines. In spite of these, HCI
attempts to ensure that they both get on with each other and interact successfully. In order
to achieve a usable system, you need to apply what you know about humans and
computers, and consult with likely users throughout the design process. In real systems, the
schedule and the budget are important, and it is vital to find a balance between what would
be ideal for the users and what is feasible in reality.

The Goals of HCI


The goals of HCI are to produce usable and safe systems, as well as functional systems. In
order to produce computer systems with good usability, developers must attempt to:

 understand the factors that determine how people use technology


 develop tools and techniques to enable building suitable systems
 achieve efficient, effective, and safe interaction
 put people first

Underlying the whole theme of HCI is the belief that people using a computer system should
come first. Their needs, capabilities and preferences for conducting various tasks should
direct developers in the way that they design systems. People should not have to change
the way that they use a system in order to fit in with it. Instead, the system should be
designed to match their requirements.

Usability

Page 33 of 228
Usability is one of the key concepts in HCI. It is concerned with making systems easy to learn
and use. A usable system is:

 easy to learn
 easy to remember how to use
 effective to use
 efficient to use
 safe to use
 enjoyable to use

Why is usability important?


Many everyday systems and products seem to be designed with little regard to usability.
This leads to frustration, wasted time and errors. This list contains examples of interactive
products:

 mobile phone, computer, personal organizer, remote control, soft drink machine,
coffee machine, ATM, ticket machine, library information system, the web,
photocopier, watch, printer, stereo, calculator, videogame etc¦.
 How many are actually easy, effortless, and enjoyable to use?
 For example, a photocopier might have buttons like these on its control panel.

Imagine that you just put your document into the photocopier and set the photocopier to
make 15 copies, sorted and stapled. Then you push the big button with the "C" to start
making your copies. What do you think will happen?

a) The photocopier makes the copies correctly.


b) The photocopier settings are cleared and no copies are made.

If you selected (b) you are right! The "C" stands for clear, not copy. The copy button is
actually the button on the left with the "line in a diamond" symbol. This symbol is widely
used on photocopiers, but is of little help to someone who is unfamiliar with this.

Factors in HCI
There are a large number of factors which should be considered in the analysis and design
of a system using HCI principles. Many of these factors interact with each other, making the
analysis even more complex. The main factors are listed in the table below:

 Organisation Factors - Training, job design, politics, roles, work organisation


Environmental Factors - Noise, heating, lighting, ventilation
 Health and Safety Factors - The User
 Cognitive processes and capabilities - Motivation, enjoyment, satisfaction,
personality, experience
 Comfort Factors - Seating, equipment, layout.
 User Interface - Input devices, output devices, dialogue structures, use of colour,
icons, commands, navigation, graphics, natural language, user support, multimedia,
 Task Factors - Easy, complex, novel, task allocation, monitoring, skills

Page 34 of 228
 Constraints - Cost, timescales, budgets, staff, equipment, buildings
 System Functionality - Hardware, software, application
 Productivity Factors - Increase output, increase quality, decrease costs, decrease
errors, increase innovation

Disciplines contributing to HCI


The field of HCI covers a wide range of topics, and its development has relied on
contributions from many disciplines. Some of the main disciplines which have contributed to
HCI are:

 Computer Science
 Cognitive Psychology
 Social Psychology
 Ergonomics/Human Factors
 Linguistics
 Artificial Intelligence
 Philosophy, Sociology & Anthropology
 Engineering & Design

HCI Theories and principles


Input Output channels
A person's interaction with the outside world occurs through information being
received and sent: input and output. In an interaction with a computer the user
receives information that is output by the computer, and responds by providing input
to the computer the user's output become the computer's input and vice versa.
Consequently, the use of the terms input and output may lead to confusion so we shall
blur the distinction somewhat and concentrate on the channels involved. This blurring
is appropriate since, although a particular channel may have a primary role as input or
output in the interaction, it is more than likely that it is also used in the other role. For
example, sight may be used primarily in receiving information from the computer, but
it can also be used to provide information to the computer, for example by fixating on
a particular screen point when using an eye gaze system.

Input in human is mainly though the senses and out put through the motor control of
the effectors. There are five major senses:

 Sight
 Hearing
 Touch
 Taste
 Smell

Of these first three are the most important to HCI. Taste and smell do not currently
lay a significant role in HCI, and it is not clear whether they could be exploited at all
in general computer systems, although they could have a role to play in more

Page 35 of 228
specialized systems or in augmented reality systems. However, vision hearing and
touch are central. Similarly there are a number of effectors:

 Limbs
 Fingers
 Eyes
 Head
 Vocal system

In the interaction with computer, the fingers play the primary role, through typing or
mouse control, with some use of voice, and eye, head and body position.
Imagine using a personal computer with a mouse and a keyboard. The application you

are using has a graphical interface, with menus, icons and windows. In your
interaction with this system you receive information primarily by sight, from what
appears on the screen. However, you may also receive information by ear: for
example, the computer may `beep' at you if you make a mistake or to draw attention
to something, or there may be a voice commentary in a multimedia presentation.
Touch plays a part too in that you will feel the keys moving (also hearing the `click')
or the orientation of the mouse, which provides vital feedback about what you have
done. You yourself send information to the computer using your hands either by
hitting keys or moving the mouse. Sight and hearing do not play a direct role in
sending information in this example, although they may be used to receive
information from a third source (e.g., a book or the words of another person) which is
then transmitted to the computer.

Vision
Human vision is a highly complex activity with range of physical and perceptual
limitations, yet it is the primary source of information for the average person. We can
roughly divide visual perception into two stages:

 the physical reception of the stimulus from outside world, and


 the processing and interpretation of that stimulus

On the one hand the physical properties of the eye and the visual system mean that
there are certain things that cannot be seen by the human; on the other interpretative
capabilities of visual processing allow images to be constructed from incomplete
information. We need to understand both stages as both influence what can and can
not be perceived visually by a human being, which is turn directly affect the way that
we design computer system. We will begin by looking at the eye as a physical
receptor, and then go onto consider the processing involved in basic vision.

The human eye


Vision begins with light. The eye is a mechanism for receiving light and transforming
it into electrical energy. Light is reflected from objects in the world and their image is
focused upside down on the back of the eye. The receptors in the eye transform it into
electrical signals, which are passed to brain.

Page 36 of 228
The eye has a number of important components as you can see in the figure. Let us take a
deeper look. The cornea and lens at the front of eye focus the light into a sharp
image on the back of the eye, the retina. The retina is light sensitive and contains two
types of photoreceptor: rods and cones.
Rods
Rods are highly sensitive to light and therefore allow us to see under a low level of
illumination. However, they are unable to resolve fine detail and are subject to light
saturation. This is the reason for the temporary blindness we get when moving from a
darkened room into sunlight: the rods have been active and are saturated by the
sudden light. The cones do not operate either as they are suppressed by the rods. We
are therefore temporarily unable to see at all. There are approximately 120 million
rods per eye, which are mainly situated towards the edges of the retina. Rods therefore
dominate peripheral vision.

Cones
Cones are the second type of receptor in the eye. They are less sensitive to light than
the rods and can therefore tolerate more light. There are three types of cone, each
sensitive to a different wavelength of light. This allows color vision. The eye has
approximately 6 million cones, mainly concentrated on the fovea.

Fovea
Fovea is a small area of the retina on which images are fixated.

Blind spot
Blind spot is also situated at retina. Although the retina is mainly covered with
photoreceptors there is one blind spot where the optic nerve enter the eye. The blind
spot has no rods or cones, yet our visual system compensates for this so that in normal
circumstances we are unaware of it.

Nerve cells
The retina also has specialized nerve cells called ganglion cells. There are two types:

 X-cells -
These are concentrated in the fovea and are responsible for the early detection of
pattern.
 Y-cells -
These are more widely distributed in the retina and are responsible for the early
detection of movement. The distribution of these cells means that, while we may not

Page 37 of 228
be able to detect changes in pattern in peripheral vision, we can perceive movement

Visual perception
Understanding the basic construction of the eye goes some way to explaining the
physical mechanism of vision but visual perception is more than this. The information
received by the visual apparatus must be filtered and passed to processing elements
which allow us to recognize coherent scenes, disambiguate relative distances and
differentiate color. Let us see how we perceive size and depth, brightness and color,
each of which is crucial to the design of effective visual interfaces.

Perceiving size and depth


Imagine you are standing on a hilltop. Beside you on the summit you can see rocks,
sheep and a small tree. On the hillside is a farmhouse with outbuilding and farm
vehicles. Someone is on the track, walking toward the summit. Below in the valley is
a small market town.

Even in describing such a scene the notions of size and distance predominate. Our
visual system is easily able to interpret the images, which it receives to take account
of these things. We can identify similar objects regardless of the fact that they appear

to us to be vastly different sizes. In fact, we can use this information to judge distance.
So how does the eye perceive size, depth and relative distances? To understand this we
must consider how the image appears on the retina. As we mentioned, reflected
light from the object forms an upside-down image on the retina. The size of that
image is specified as visual angle. Figure illustrates how the visual angle is calculated.

If were to draw a line from the top of the object to a central point on the front of the
eye and a second line from the bottom of the object to the same point, the visual angle
of the object is the angle between these two lines. Visual angle is affected by both the
size of the object and its distance from the eye. Therefore if two objects are at the
same distance, the larger one will have the larger visual angle. Similarly, if two
objects of the same size are placed at different distances from the eye, the furthest one
will have the smaller visual angle, as shown in figure.

Page 38 of 228
Visual angle indicates how much of the field of view is taken by the object. The
visual angle measurement is given in either degrees or minutes of arc, where 1 degree
is equivalent to 60 minutes of arc, and 1 minute of arc to 60 seconds of arc.

Visual acuity
So how does an object's visual angle affect our perception of its size? First, if the
visual angle of an object is too small we will be unable to perceive it at all. Visual
acuity is the ability of a person to perceive fine detail. A number of measurements
have been established to test visual acuity, most of which are included in standard eye
tests. For example, a person with normal vision can detect a single line if it has a
visual angle of 0.5 seconds of arc. Spaces between lines can be detected at 30 seconds to
1 minute of visual arc. These represent the limits of human visual perception.

Law of size constancy


Assuming that we can perceive the object, does its visual angle affect our perception
of its size? Given that the visual angle of an object is reduced, as it gets further away,
we might expect that we would perceive the object as smaller. In fact, our perception of
an object's size remains constant even if its visual angel changes. So a person's
height I perceived as constant even if they move further from you. This is the law of
size constancy, and it indicated that our perception of size relies on factors other than

the visual angle.

One of these factors is our perception of depth. If we return to the hilltop scene there are
a number of cues, which can use to determine the relative positions and distances
of the objects, which we see. If objects overlap, the object that is partially covered is
perceived to be in the background, and therefore further away. Similarly, the size and
height of the object in our field of view provides a cue to its distance. A third cue is
familiarity: if we expect an object to be of a certain size then we can judge its distance
accordingly

Perceiving brightness
A second step of visual perception is the perception of brightness. Brightness is in fact
a subjective reaction to level of light. It is affected by luminance, which is the amount

Page 39 of 228
of light emitted by an object. The luminance of an object is dependent on the amount
of light falling on the object's surface and its reflective prosperities. Contrast is
related to luminance: it is a function of the luminance of an object and the luminance
of its background.

Although brightness is a subjective response, it can be described in terms of the


amount of luminance that gives a just noticeable difference in brightness. However,
the visual system itself also compensates for changes in brightness. In dim lighting,
the rods predominate vision. Since there are fewer rods on the fovea, object in low
lighting can be seen easily when fixated upon, and are more visible in peripheral
vision. In normal lighting, the cones take over.

Visual acuity increases with increased luminance. This may be an argument for using
high display luminance. However, as luminance increases, flicker also increases. The
eye will perceive a light switched on and off rapidly as constantly on. But if the speed
of switching is less than 50 Hz then the light is perceived to flicker. In high luminance
flicker can be perceived at over 50 Hz. Flicker is also more noticeable in peripheral
vision. This means that the larger the display, the more it will appear to flicker.

Perceiving color
A third factor that we need to consider is perception of color. Color is usually
regarded as being made up of three components:

 Hue
 Intensity
 Saturation

Hue
Hue is determined by the spectral wavelength of the light. Blues have short
wavelength, greens medium and reds long. Approximately 150 different hues can be
discriminated by the average person.

Intensity
Intensity is the brightness of the color.

Saturation
Saturation is the amount of whiteness in the colors.By varying these two, we can perceive i
n the region of 7 million different colors.
However, the number of colors that can be identified by an individual without training
is far fewer. The eye perceives color because the cones are sensitive to light of different
wavelengths. There are three different types of cone, each sensitive to a different
color (blue, green and red). Color vision is best in the fovea, and worst at the
periphery where rods predominate. It should also be noted that only 3-4 % of the
fovea is occupied by cones which are sensitive to blue light, making blue acuity lower.
Finally, we should remember that around 8% of males and 1% of females suffer from
color blindness, most commonly being unable to discriminate between red and green.
The capabilities and limitations of visual processing

Page 40 of 228
in considering the way in which we perceive images we have already encountered
some of the capabilities and limitations of the human visual processing system.

However, we have concentrated largely on low-level perception. Visual processing


involves the transformation and interpretation of a complete image, from the light that
is thrown onto the retina. As we have already noted, our expectations affect the way
an image is perceived. For example, if we know that an object is a particular size, we
will perceive it as that size no matter how far it is from us.

Visual processing compensates for the movement of the image on the retina which
occurs as we around and as the object which we see moves. Although the retinal
image is moving, the image that we perceive is stable. Similarly, color and brightness
of objects are perceived as constant, in spite of changes in luminance.

This ability to interpret and exploit our expectations can be used to resolve ambiguity.
For example consider the image shown in figure `a'. What do you perceive? Now
consider figure `b' and `c'. the context in which the object appears allow our
expectations to clearly disambiguate the interpretation of the object, as either a B or 13.
However, it can also create optical illusions. Consider figure `d'. Which line is longer?
A similar illusion is the Ponzo illusion as shown in figure

An ambiguous shape?

ABC

Page 41 of 228
12 13 14

The Muller–Lyer illusion – which line is longer?

The Ponzo illusion – are these the same size?

Is this text correct?

Design Principles

Page 42 of 228
Conceptual Model
"The most important thing to design is the user's conceptual model. Every thing else
should be subordinated to making that model clear, obvious, and substantial. That is
almost exactly the opposite of how most software is designed." (David Liddle)

By a conceptual model is meant:

 A description of the proposed system in terms of a set of integrated ideas and


 Concepts about what it should do, behave and look like, that will
be understandable by
 The users in the manner intended.
 To develop a conceptual model involves envisioning the proposed product, based on
 The user's needs and other requirements identified. To ensure that it is designed to
be
 Understandable in the manner intended requires doing iterative testing of the produ
ct
 As it is developed.

A key aspect of this design process is initially to decide what the user will be doing
when carrying out their tasks. For example, will they be primarily searching for
information, creating documents, communicating with other users, recording events,
or some other activity? At this stage, the interaction mode that would best supports
this need to be considered. For example, would allowing the users to browse be
appropriate, or would allowing them to ask questions directly to the system in their
native language be more affective? Decision about which kind of interaction style use
(e.g., whether to use a menu-based system, speech inputs, commands) should be made
in relation to the interaction mode. Thus, decision about which mode of interaction to
support differ from those made about which style of interaction to have; the former
being at a higher level of abstraction. The former are also concerned with determining
the nature of the users' activities to support, while the later are concerned with the
selection of specific kinds of interface.

Once a set of possible ways of interacting with interactive system has been identified,
the design of the conceptual modal then needs to be thought through in term of actual
concrete solution. This entail working out the behavior of the inter face, the particular
interaction style that will be used, and the "look and feel" of the interface. At this
stage of "fleshing out," it is always a good idea to explore a number of possible
designs and to assess the merits and problems of each one.

Another way of designing an appropriate conceptual model is to interface metaphor


this can provide a basic structure for the conceptual model that is couched in
knowledge users are familiar with. Examples of well-known interface metaphors are
the desktop and search engines Software has a behavioral face it shows to the world that is
created by the programmer or designer. This representation is not necessarily an
accurate description
of what is really going on inside the computer, although unfortunately, it frequently is.

Page 43 of 228
This ability to represent the computer functioning independent of its true actions is far
more pronounced in software than in any other medium. It allows a clever designer to
hide some of the more unsavory facts of how the software is really getting the job
done. This disconnection between what is implemented and what it offered as
explanation gives rise to a third model in the digital world, the designer's represented
model--the way the designer chooses to represent a program's functioning to the
user. Donald Norman refers to this simply as the designer's model.

In the world of software, a program's represented model can be quite different from
the actual processing structure of the program. For example, an operating system can
make a network file server look as though it were a local disk. The model does not
represent the fact that the physical disk drive may be miles away. This concept of the
represented model has no widespread counterpart in the mechanical world. The
representation between the three models is shown in Figure.

The closer the represented model comes to the user's mental model, the easier he will
find the program to use and to understand. Generally, offering a represented model
that follows the implementation model too closely significantly reduces the user's
ability to learn and use the program, assuming that the user's mental model of his
tasks differs from the implementation model of the software.

We tend to form mental models that are simpler than reality; so if we create
represented models that are simpler than the actual implementation model, we help
the user achieve a better understanding. Pressing the brake pedal in your car, for
example, may conjure a mental image of pushing a lever that rubs against the wheels
to slow you down. The actual mechanism includes hydraulic cylinders, tubing, and
metal pads that squeeze on a perforated disk, but we simplify all that out of our minds,
creating a more effective, albeit less accurate, mental model. In software, we imagine
that a spreadsheet scrolls now cells into view when we click on the scrollbar. Nothing
of the sort actually happens. There is no sheet of cells out there, but a tightly packed
data structure of values, with various pointers between them, from which the program
synthesizes a new image to display in real-time.

Another important thing is that there are several gulfs that separate mental states from
physical ones. Each gulf reflects one aspect of the distance between the mental

Page 44 of 228
representation of the person and the physical components and states of the
environment. And these gulfs present major problems for users.

The Gulf of Execution


Does the system provide actions that correspond to the intentions of the person? The
difference between the intentions and allowable actions is the gulf of execution. One
measure of this gulf is how well the system allows the person to do the intended
actions directly, without extra effort: do the action provided by the system match
those intended by the person?

The Gulf of Evaluation


Does the system provide a physical representation that can be directly perceived and
that is directly interpretable in terms of the intentions and expectations of the person?
The Gulf of evaluation reflects the amount of effort that the person must exert to
interpret the physical state of the system and to determine how well the expectations
and intentions have been met. The gulf is small when the system provides information
about its state in a form that is easy to get, is easy to interpret, and matches the way
the person thinks of the system.

The Seven Stages of Action as Design aids


The seven-stage structure can be a valuable design aid, for it provides a basic checklist
of questions to ask to ensure that the Gulfs of evaluation and execution are bridged.
In general each stage of action requires its own special design strategies and, in turn,
provides its own opportunity for disaster. It would be fun were it not also so frustrating,
to look over the world and gleefully analyse each deficiency. On the whole, as you can
see in figure the questions for each stage are relatively simple. And these, in turn, boil
down to the principles of good design. Principles of good design are discussed bellow

Design Principles

Page 45 of 228
A number of design principles have been promoted. The best known are concerned
with how to determine what users should see and do when carrying out their tasks
using an interactive product. Here we briefly describe the most common ones

 Visibility
 Affordance
 Constraints
 Mapping
 Consistency
 Feedback

Visibility
The more visible functions are, the more likely users will be able to know what to do
next. In contrast, when functions are "out of sight," it makes them more difficult to fit
and knows how to use. Norman describes the controls of a car to emphasize this point.
The controls for different operations are clearly visible (e.g., indicator, headlights,
horn, hazard warning lights), indicating what can be done. The relationship between
the way the controls have been positioned in the car and what they do makes it easy
for the deriver to find the appropriate control for the task at hand. For example, one
problem that I often encounter, in word processing software I often needed to set the
properties of a word document. For this logically option of properties should be in the
File menu, and I have often seen it there. But once, I opened the file menu I could not
find it there, I was confused. Look at the figure

In confusion, I looked through all the menus but in vain. At last, surprisingly I was
again looking at the file menu when I noticed the arrow at the bottom of the menu,
when I clicked on that I was able to see that option again on the menu. Look at the
figure bellow.

Page 46 of 228
Affordance
Affordance is a term used to refer to an attribute of an object that allows people to
know how to use it. For example, a mouse button invites pushing by the way it is
physically constrained in its plastic shell. At a very simple level, to afford means "to
give a clue." When the affordances of a physical object are perceptually obvious it is
easy to know how to interact with it. For example, a door handle affords pulling, a
cup handle affords grasping, and a mouse button affords pushing. Norman introduced
this concept in the late 80s in his discussion of the design of everyday objects. Since
then, it has been much popularized, being what can be done to them.

For example,graphical elements like button, icon, links, and scroll bars are talked about with
respect to how to make it appear obvious how they should be used: icons should be
designed to afford clicking, scroll bars to afford moving up and down, buttons to
afford pushing.

There are two kind of affordance:

 Perceived
 Real

Real
Physical objects are said to have real affordances, like grasping, that are perceptually
obvious and do not have to be learned.

Perceived
User interfaces that are screen-based are virtual and do not make sense to try to design
for real affordances at the interface---except when designing physical devices, like
control consoles, where affordance like pulling and pressing are helpful in guiding the
user to know what to do. Alternatively screen based interfaces are better
conceptualized as perceived affordances, which are essentially learned conventions.

Page 47 of 228
Constraints
The design concept of constraining refers to determining ways of restricting the kind
of user interaction that can take place at a given moment. There are various ways this
can be achieved. A common design practice in graphical user interfaces is to
deactivate certain menu options by shading them, thereby restricting the user to only
actions permissible at that stage of the activity. One of the advantages of this form of
constraining is it prevents the user from selecting incorrect options and thereby
refuses the chances of making a mistake. The use of different kinds of graphical
representations can also constrain a person's interpretation of a problem or
information space. For example flow chart diagram show which objects are related to
which thereby constraining the way the information can be perceived.
Norman classified constraints into three categories: physical, logical, and cultural.

Physical constraints
Physical constraints refer to the way physical objects restrict the movement of things.
For example, the way a external disk can be placed into a disk drive is physically
constrained by its shape and size, so that it can be inserted in only one way. Likewise,
keys on a pad can usually be pressed in only one way.

Logical constraints
Logical constraints rely on people's understanding of the way the world works. They
rely on people's common-sense reasoning about actions and their consequences.
Picking up a physical marble and placing it in another location on the phone would be
expected by most people to trigger something else to happen. Making actions and
their effects obvious enables people to logically deduce what further actions are
required. Disabling menu options when not appropriate for the task in hand provides
logical constraining. It allows users to reason why (or why not) they have been
designed this way and what options are available.

Culture constraints
Culture constraints rely on learned conventions, like the use of red for warning, the
use of certain kinds of signals for danger, and the use of the smiley face to represent
happy emotions. Most cultural constraints are arbitrary in the sense that their
relationship with what is being represented is abstract, and could have equally
evolved to be represented in another form (e.g., the use of yellow instead of red for
warning). Accordingly, they have to be learned. Once learned and accepted by a
cultural group, they become universally accepted conventions. Two universally
accepted interface conventions are the use of windowing for displaying information
and the use icons on the desktop to represent operations and documents.

Page 48 of 228
Mapping
This refers to the relationship between controls and their effects in the world. Nearly
all artifacts need some kind of mapping between controls and effects, whether it is a
flashlight, car, power plant, or cockpit. An example of a good mapping between
controls are effect is the up and down arrows used to represent the up and down
movement of the cursor, respectively, on a computer keyboard. The mapping of the
relative position of controls and their effects is also important. Consider the various
musical playing devices. How are the controls of playing rewinding, and fast forward
mapped onto the desired effects? They usually follow a common convention of
providing a sequence of buttons,
with the play button in the middle, the rewind button on the left and the fast-forward
on the right. This configuration maps directly onto the directionality of the actions

Imagine how difficult it would be if the mapping in figure (a) were used

Consistency
This refers to designing interfaces to have similar operations and use similar elements
for achieving similar tasks. In particular, a consistent interface is one that follows

Page 49 of 228
rules, such as using the same operation to select all objects. For example, a consistent
operation is using the same input action to highlight any graphical object at the
interfaces, such as always clicking the left mouse button. Inconsistent interfaces, on
the other hand, allow exceptions to a rule. An example of this is where certain
graphical objects (e.g., email messages presented in a table) can be highlighted using
the right mouse button, while all other operations are highlighted using the left button.
A problem with this kind of inconsistency is that is quite arbitrary, making it difficult
for users to remember and making the users more prone to mistakes.

On of the benefits of consistent interfaces, therefore, is that they are easier to learn
and use. Users have to learn only a single mode of operation that is applicable to all
objects. This principle worked well for simple interfaces with limited operations, like
mini CD player with small number of operations mapped onto separate buttons. Here
all the user has to do is learn what each button represents and select accordingly.

However, it can be more problematic to apply the concept of consistency to more


complex interfaces, especially when many different operations need to be designed
for. For example, consider how to design an interface for an application that offers
hundreds of operations. There is simply not enough space for a thousand buttons, each
of which maps onto an individual operation. Even if there were, it would be extremely
difficult and time consuming for the user to search through them all to find the desired
operation.

A much more effective design solution is to create categories of commands that can
be mapped into subsets of operations. For the word-processing application, the
hundreds of operation available are categorized into subsets of different menus. All
commands that are concerned with file operations are placed together in the same file
menu

Another problem with consistency is determining what aspect of an interface to make


consistent with what else. There are often many choices, some of which can be
inconsistent with other aspects of the interface or ways of carrying out actions.

Consider the design problem of developing a mechanism to let users lock their files on
a shared server. Should the designer try to design it to be consistent with the way
people lock things in the outside world (called external consistency) or with the way
they lock objects in the existing system (called internal consistency)? However, there
are many different ways of locking objects in the physical world (e.g., placing in a
safe, using a padlock,
using a key, using a child safety lock), just as there are different ways of locking
electronically. The problem facing designer is knowing which one to be consistent with.

Feedback
Related to the concept of visibility is feedback. This is best illustrated by an analogy
to what everyday life would be like without it. Imagine trying to play a guitar, slice
bread using knife, or write a pen if none of the actions produced any effect for several
seconds. There would be an unbearable delay before the music was produced, the
bread was cut, or the words appeared on the paper, making it almost impossible for
the person to continue with the next strum, saw, or stroke.

Page 50 of 228
Feedback is about sending back information about what action has been done and
what has been accomplished, allowing the person to continue with the activity.
Various kinds of feedback are available for interaction design--audio, tactile, verbal,
visual, and combinations of these. Deciding which combinations are appropriate for
different kinds of activities and interactivities is central. Using feedback in the right
way can also provide the necessary visibility for user interaction

Human Centred Software Development


The design goal is to provide reliable techniques for the repeated design of successful and
usable interactive systems. It is therefore necessary that we go beyond the exercise of
identifying paradigms and examine the process of interactive system design. In the previous
chapter we introduced some of the elements of a user-centered design process. Here we
expand on that process, placing the design of interactive systems within the established
frameworks of software development. 


Within computer science there is already a large subdiscipline that addresses the
management and technical issues of the development of software systems – called software
engineering. One of the cornerstones of software engineering is the software life cycle,
which describes the activities that take place from the initial concept formation for a
software system up until its eventual phasing out and replacement. This is not intended to
be a software engineering textbook, so it is not our major concern here to discuss in depth
all of the issues associated with software engineer- ing and the myriad life-cycle models. 


The important point that we would like to draw out is that issues from HCI affect- ing the
usability of interactive systems are relevant within all the activities of the software life cycle.
Therefore, software engineering for interactive system design is not simply a matter of
adding one more activity that slots in nicely with the existing activities in the life cycle.
Rather, it involves techniques that span the entire life cycle. 


The Software Life Cycle 



One of the claims for software development is that it should be considered as an
engineering discipline, in a way similar to how electrical engineering is considered for
hardware development. One of the distinguishing characteristics of any engineering
discipline is that it entails the structured application of scientific techniques to the
development of some product. A fundamental feature of software engineering, therefore, is
that it provides the structure for applying techniques to develop soft- ware systems. The
software life cycle is an attempt to identify the activities that occur in software
development. These activities must then be ordered in time in any development project and
appropriate techniques must be adopted to carry them through.

In the development of a software product, we consider two main parties: the customer who
requires the use of the product and the designer who must provide the product. Typically,
the customer and the designer are groups of people and some people can be both customer
and designer. It is often important to distinguish between the customer who is the client of
the designing company and the customer who is the eventual user of the system. These two
roles of customer can be played by different people. The group of people who negotiate the
features of the intended system with the designer may never be actual users of the system.
This is often par- ticularly true of web applications. In this chapter, we will use the term

Page 51 of 228
‘customer’ to refer to the group of people who interact with the design team and we will
refer to those who will interact with the designed system as the user or end-user.

Activities in the life cycle

The graphical representation is reminiscent of a waterfall, in which each activity naturally


leads into the next. The analogy of the waterfall is not completely faithful to the real
relationship between these activities, but it provides a good starting point for dis- cussing
the logical flow of activity.

Requirements specification
In requirements specification, the designer and customer try to capture a description of
what the eventual system will be expected to provide. This is in contrast to deter- mining
how the system will provide the expected services, which is the concern of later activities.

Architectural design
As we mentioned, the requirements specification concentrates on what the system is
supposed to do. The next activities concentrate on how the system provides the services
expected from it. The first activity is a high-level decomposition of the sys- tem into
components that can either be brought in from existing software products or be developed
from scratch independently. An architectural design performs this decomposition. It is not
only concerned with the functional decomposition of the system, determining which
components provide which services. It must also describe

the interdependencies between separate components and the sharing of resources that will
arise between components.

Detailed design
The architectural design provides a decomposition of the system description that allows for
isolated development of separate components which will later be integrated. For those
components that are not already available for immediate integration, the designer must
provide a sufficiently detailed description so that they may be implemented in some

Page 52 of 228
programming language. The detailed design is a refinement of the component description
provided by the architectural design. The behavior implied by the higher-level description
must be preserved in the more detailed description.

Coding and unit testing


The detailed design for a component of the system should be in such a form that it is
possible to implement it in some executable programming language. After coding, the
component can be tested to verify that it performs correctly, according to some test criteria
that were determined in earlier activities. Research on this activity within the life cycle has
concentrated on two areas. There is plenty of research that is geared towards the
automation of this coding activity directly from a low-level detailed design. Most of the
work in formal methods operates under the hypothesis that, in theory, the transformation
from the detailed design to the implementation is from one mathematical representation to
another and so should be able to be entirely automated. Other, more practical work
concentrates on the automatic generation of tests from output of earlier activities which
can be performed on a piece of code to verify that it behaves correctly.

Integration and testing


Once enough components have been implemented and individually tested, they must be
integrated as described in the architectural design. Further testing is done to ensure correct
behavior and acceptable use of any shared resources. It is also possible at this time to
perform some acceptance testing with the customers to ensure that the system meets their
requirements. It is only after acceptance of the integrated system that the product is finally
released to the customer.

Maintenance
After product release, all work on the system is considered under the category of
maintenance, until such time as a new version of the product demands a total redesign or
the product is phased out entirely. Consequently, the majority of the lifetime of a product is
spent in the maintenance activity. Maintenance involves the correction of errors in the
system which are discovered after release and the revision of the system services to satisfy
requirements that were not realized during previous development.

Validation and verification


Throughout the life cycle, the design must be checked to ensure that it both satisfies the
high-level requirements agreed with the customer and is also complete and internally
consistent. These checks are referred to as validation and verification, respectively.
Verification of a design will most often occur within a single life-cycle activity or between
two adjacent activities.

Page 53 of 228
The formality gap means that validation will always rely to some extent on sub- jective
means of proof. We can increase our confidence in the subjective proof by effective use of
real-world experts in performing certain validation chores. These experts will not necessarily
have design expertise, so they may not understand the esign notations used. Therefore, it is
important that the design notations narrow the formality gap, making clear the claims that
the expert can then validate. For interactive systems, the expert will have knowledge from a
cognitive or psycholo- gical domain, so the design specification must be readily
interpretable from a psy- chological perspective in order to validate it against interactive
requirements of the system.

Iterative Design And Prototyping


an interactive system cannot be completely specified from the beginning of the life cycle.
The only way to be sure about some features of the potential design is to build them and
test them out on real users. The design can then be modified to correct any false
assumptions that were revealed in the testing. This is the essence of iterative design, a
purposeful design process which tries to overcome the inherent problems of incomplete

Page 54 of 228
requirements specification by cycling through several designs, incrementally improving
upon the final product with each pass.

The problems with the design process, which lead to an iterative design philo- sophy, are
not unique to the usability features of the intended system. The problem holds for
requirements specification in general, and so it is a general software engineering problem,
together with technical and managerial issues.

On the technical side, iterative design is described by the use of prototypes, artifacts that
simulate or animate some but not all features of the intended system. There are three main
approaches to prototyping:

Throw-away: The prototype is built and tested. The design knowledge gained from this
exercise is used to build the final product, but the actual prototype is discarded. Figure 6.5
depicts the procedure in using throw-away prototypes to arrive at a final requirements
specification in order for the rest of the design process to proceed.

Incremental: The final product is built as separate components, one at a time. There is one
overall design for the final system, but it is partitioned into inde- pendent and smaller
components. The final product is then released as a series of products, each subsequent
release including one more component.

Page 55 of 228
Evolutionary Here the prototype is not discarded and serves as the basis for the next
iteration of design. In this case, the actual system is seen as evolving from a very limited
initial version to its final release, as depicted in Figure below Evolutionary prototyping also
fits in well with the modifications which must be made to the system that arise during the
operation and maintenance activity in the life cycle.

On the management side, there are several potential problems:

 Time
 Planning
 Non-functional features
 Contracts
 Techniques for prototyping

Page 56 of 228
Here we will describe some of the techniques that are available for producing rapid
prototypes.

Storyboards
Probably the simplest notion of a prototype is the storyboard, which is a graphical depiction
of the outward appearance of the intended system, without any accom- panying system
functionality. Storyboards do not require much in terms of computing power to construct; in
fact, they can be mocked up without the aid of any computing resource. The origins of
storyboards are in the film industry, where a series of panels roughly depicts snapshots from
an intended film sequence in order to get the idea across about the eventual scene.
Similarly, for interactive system design, the storyboards provide snapshots of the interface
at particular points in the interaction. Evaluating customer or user impressions of the
storyboards can deter- mine relatively quickly if the design is heading in the right direction.

Limited functionality simulations


More functionality must be built into the prototype to demonstrate the work that the
application will accomplish. Storyboards and animation techniques are not sufficient for this
purpose, as they cannot portray adequately the interactive aspects of the system. To do
this, some portion of the functionality must be simulated by the design team.

Programming support for simulations means a designer can rapidly build graph- ical and
textual interaction objects and attach some behavior to those objects, which mimics the
system’s functionality. Once this simulation is built, it can be evaluated and changed rapidly
to reflect the results of the evaluation study with various users.

For example, we might want to build a prototype for the VCR with undo described earlier
using only a workstation display, keyboard and mouse. We could draw a picture of the VCR
with its control panel using a graphics drawing package, but then we would want to allow a
subject to use the mouse to position a finger cursor over one of the buttons to ‘press’ it and
actuate some behavior of the VCR. In this way, we could simulate the programming task and
experiment with different options for undoing.

There are now plenty of prototyping tools available which allow the rapid develop- ment of
such simulation prototypes. These simulation tools are meant to provide a quick
development process for a very wide range of small but highly interactive applications. A
well-known and successful prototyping tool is HyperCard, a simula- tion environment for the
Macintosh line of Apple computers. HyperCard is similar to the animation tools described
above in that the user can create a graphical depic- tion of some system, say the VCR, with
common graphical tools. The graphical images are placed on cards, and links between cards
can be created which control the sequencing from one card to the next for animation
effects. What HyperCard pro- vides beyond this type of animation is the ability to describe
more sophisticated interactive behavior by attaching a script, written in the HyperTalk
programming language, to any object. So for the VCR, we could attach a script to any
control panel button to highlight it or make an audible noise when the user clicks the mouse
cur- sor over it. Then some functionality could be associated to that button by reflecting
some change in the VCR display window. Similar functionality is provided through tools such
as Macromedia Flash and Director.

Page 57 of 228
One technique for simulation, which does not require very much computer- supported
functionality, is the Wizard of Oz technique. With this technique, the designers can develop
a limited functionality prototype and enhance its functionality in evaluation by providing the
missing functionality through human intervention.

High-level programming support


HyperTalk was an example of a special-purpose high-level programming language which
makes it easy for the designer to program certain features of an interactive sys- tem at the
expense of other system features like speed of response or space efficiency. HyperTalk and
many similar languages allow the programmer to attach functional behavior to the specific
interactions that the user will be able to do, such as position and click on the mouse over a
button on the screen. Previously, the difficulty of interactive programming was that it was
so implementation dependent that the programmer would have to know quite a bit of
intimate detail of the hardware sys- tem in order to control even the simplest of interactive
behavior. These high-level programming languages allow the programmer to abstract away
from the hardware specifics and think in terms that are closer to the way the input and
output devices are perceived as interaction devices.

Warning about iterative design


First, it is often the case that design decisions made at the very beginning of the prototyping
process are wrong and, in practice, design inertia can be so great as never to overcome an
initial bad decision.

The second problem is slightly subtler, and serious. If, in the process of evalu- ation, a
potential usability problem is diagnosed, it is important to understand the reason for the
problem and not just detect the symptom.

Design Rationale
In designing any computer system, many decisions are made as the product goes from a set
of vague customer requirements to a deliverable entity. Often it is difficult to recreate the
reasons, or rationale, behind various design decisions. Design rationale is the information
that explains why a computer system is the way it is, including its structural or architectural
description and its functional or behavioural description. In this sense, design rationale does
not fit squarely into the software life cycle described in this chapter as just another phase or
box. Rather, design rationale relates to an activity of both reflection (doing design rationale)
and documentation (creating a design rationale) that occurs throughout the entire life cycle.

It is beneficial to have access to the design rationale for several reasons:

 In an explicit form, a design rationale provides a communication mechanism among


the members of a design team so that during later stages of design and/or
maintenance it is possible to understand what critical decisions were made, what
alternatives were investigated (and, possibly, in what order) and the reason why one
alternative was chosen over the others. This can help avoid incorrect assumptions
later.
 Accumulated knowledge in the form of design rationales for a set of products can be
reused to transfer what has worked in one situation to another situation which has
similar needs. The design rationale can capture the context of a design decision in

Page 58 of 228
order that a different design team can determine if a similar rationale is appropriate
for their product.
 The effort required to produce a design rationale forces the designer to deliberate
more carefully about design decisions. The process of deliberation can be assisted by
the design rationale technique by suggesting how arguments justifying or discarding
a particular design option are formed.
 In the area of HCI, design rationale has been particularly important, again for several
reasons:
 There is usually no single best design alternative.

Even if an optimal solution did exist for a given design decision, the space of alternatives is
so vast that it is unlikely a designer would discover it. The usability of an interactive system
is very dependent on the context of its use.

Process-oriented design rationale


Much of the work on design rationale is based on Rittel’s issue-based information system, or
IBIS, a style for representing design and planning dialog developed in the 1970s [308]. In IBIS
(pronounced ‘ibbiss’), a hierarchical structure to a design rationale is created.

Design space analysis


MacLean and colleagues have proposed a more deliberative approach to design rationale
which emphasizes a post hoc structuring of the space of design alternatives that have been
considered in a design project. Their approach, embodied in the Questions, Options and
Criteria (QOC) notation, is characterized as design space analysis

Page 59 of 228
Psychological design rationale
Psychological design rationale make explicit the psychological claims of usability inherent in
any interactive system in order better to suit a product for the tasks users have. Carroll and
Rosson have introduced this psychological design rationale, and before we describe the
application of the technique, it is important to understand some of its theoretical
background.

Interactive UI Design
So what is design? A simple definition is: achieving goals within constraints

This does not capture everything about design, but helps to focus us on certain things:

 Goals What is the purpose of the design we are intending to produce? Who is it for?
Why do they want it? For example, if we are designing a wireless personal movie
player, we may think about young affluent users wanting to watch the lat- est
movies whilst on the move and download free copies, and perhaps wanting to share
the experience with a few friends.
 Constraints What materials must we use? What standards must we adopt? How
much can it cost? How much time do we have to develop it? Are there health and
safety issues? In the case of the personal movie player: does it have to withstand
rain? Must we use existing video standards to download movies? Do we need to
build in copyright protection?
 Of course, we cannot always achieve all our goals within the constraints. So perhaps
one of the most important things about design is:
 Trade-off Choosing which goals or constraints can be relaxed so that others can be
met. For example, we might find that an eye-mounted video display, a bit like those
used in virtual reality, would give the most stable image whilst walking along.
However, this would not allow you to show friends, and might be danger- ous if you
were watching a gripping part of the movie as you crossed the road.
Often the most exciting moments in design are when you get a radically different idea that
allows you to satisfy several apparently contradictory constraints. However, the more

Page 60 of 228
common skill needed in design is to accept the conflict and choose the most appropriate
trade-off. The temptation is to focus on one or other goal and opti- mize for this, then tweak
the design to make it just satisfy the constraints and other goals. Instead, the best designs
are where the designer understands the trade-offs and the factors affecting them.
Paradoxically, if you focus on the trade-off itself the more radical solutions also become
more apparent.

The golden rule of design


Part of the understanding we need is about the circumstances and context of the particular
design problem. We will return to this later in the chapter. However, there are also more
generic concepts to understand. The designs we produce may be different, but often the
raw materials are the same.

This leads us to the golden rule of design:

 The case of a physical design this is obvious. Look at a chair with a steel frame and
one with a wooden frame. They are very different: often the steel frames are tubular
or thin L or H section steel. In contrast, wooden chairs have thicker solid legs. If you
made a wooden chair using the design for a metal one, it would break; if you made
the metal one in the design for the wooden one it would be too heavy to move.

For Human–Computer Interaction the obvious materials are the human and the computer.
That is we must:

 understand computers
– limitations, capacities, tools, platforms


 understand people
– psychological, social aspects, human error.

The Process of Design


Often HCI professionals complain that they are called in too late. A system has been
designed and built, and only when it proves unusable do they think to ask how to do it right!
In other companies, usability is seen as equivalent to testing – checking whether people can
use it and fixing problems, rather than making sure they can from the beginning. In the best
companies, however, usability is designed in from the start.

User Focus

As we’ve already said, the start of any interaction design exercise must be the

intended user or users. This is often stated as:

Page 61 of 228
“Know your users”

So, how do you get to know your users?

 Who are they?


 Probably not like you!
 Talk to them.
 Watch them.

Scenarios
Scenarios are stories for design: rich stories of interaction. They are perhaps the simplest
design representation, but one of the most flexible and powerful.

Navigation Design
As we stressed, the object of design is not just a computer system or device, but the socio-
technical intervention as a whole. However, as design progresses we come to a point where
we do need to consider these most tangible outputs of design.

You interact at several levels:

 Widgets The appropriate choice of widgets and wording in menus and buttons will
help you know how to use them for a particular selection or action.
 Screens or windows You need to find things on the screen, understand the logical
grouping of buttons.
 Navigation within the application You need to be able to understand what will
happen when a button is pressed, to understand where you are in the interaction.
 Environment The word processor has to read documents from disk, perhaps some
are on remote networks. You swap between applications, perhaps cut and paste.

Screen Design and Layout


We have talked about the different elements that make up interactive applications, but not
about how we put them together. A single screen image often has to present information
clearly and also act as the locus for interacting with the system.

Tools for layout


We have a number of visual tools available to help us suggest to the user appropriate ways
to read and interact with a screen or device.

 Grouping and structure


 Order of groups and items
 Decoration
 Alignment
 White space
 User action and control
 Entering information
 Knowing what to do
 Affordances
 Appropriate appearance
 Presenting information

Page 62 of 228
 Aesthetics and utility
 Making a mess of it: color and 3D
 Localization / internationalization

Iteration and Prototyping


Because human situations are complex and designers are not infallible it is likely that our
first design will not be perfect! For this reason, almost all interaction design includes some
form of iteration of ideas. This often starts early on with paper designs and storyboards
being demonstrated to colleagues and potential users.

Role of prototyping

Moving little by little . . . but to where?

From this we can see that there are two things you need in order for prototyping methods
to work:

1. To understand what is wrong and how to improve.


2. A good start point.

A really good designer might guess a good initial design based on experience and judgment.
However, the complexity of interaction design problems means that this insight is hard.
Another approach, very common in graphical design, is to have several initial design ideas
and drop them one by one as they are developed further.

Hypertext, Multimedia and The World Wide Web


Increases in desktop computing power have enabled the rapid growth of the multi- media
industry. CD-ROMs, stereo sound and often video input/output are now part of the
specification of standard personal computers. 


Page 63 of 228
Understanding Hypertext

Hypertext definition – text, hypertext and multimedia 

A hypertext system comprises a number of pages and a set of links that are used to
connect pages together. The links can join any page to any other page, and there can be
more than one link per page. Thus a hypertext document does not simply start a linear
progression and follow it to an end, but goes in lots of different directions, some of
which terminate, while others link back into different parts of the document

Typical structures of linear text and hypertext

Rich content
As well as static material – text and static diagrams and photographs – hypertext sys- tems
may also include more dynamic material such as animation, video and audio clips, and even
full computer applications.

Talking heads
One use of animation is to produce talking heads. These are images of human
faces
either completely computer generated or derived from photographs of real people.
They are based on models of human anatomy so that realistic lip movement can be
synchronized with generated speech. Surprisingly, this is not just a fun activity but is
actually useful! One important use is for deaf or partially deaf users who can lip read the
image. Another application is to synchronize the lips with telephone speech allowing a
form of video phone over low-bandwidth telephone lines.

These faces can also express emotion. Users have imputed personality to computers since
they only had flashing lights. By simulating human expressions the designer can express
intended affective states rather than leaving this to the user. For example, this could be
useful in a learning environment where the students might naturally view the computer
as a harsh, unforgiving teacher, but by means of a suitable face and expressions could be
induced to regard it as a colleague or facilitator in learning.

Delivery technology
On the computer
Some hypertexts, in particular help systems, are downloaded or installed perman- ently on a
computer. This has the advantage of instant access and such applications need not use a
standard viewer but may include their own bespoke browsing soft- ware. However, with
media-rich hypertexts containing substantial graphics, video and audio clips it may be

Page 64 of 228
impractical to store everything on hard disk. Also, for copy- right protection, some systems
will deliberately not allow themselves to be copied from their original distribution media.

Many hypermedia systems are supplied on CD-ROM. This has the advantage of reasonably
large capacity (650–700 Mbytes), but access is slower than with installed systems. For highly
dynamic material, such as educational media, a special player is installed; alternatively,
material such as software documentation may use a standard format such as web pages.

DVD delivered material is interesting as it is not text enriched with video, but instead a
movie that has been ‘made interactive’. As older computers tend to have only CD-ROM
drives, it is not possible yet to supply, for example, tutorial material on DVD and know that
it could be used on any machine.

On the web
Of course, the world wide web is the best-known multimedia hypertext system of all. The
world wide web offers a rich environment for the presentation of information. Documents
can be constructed that are very different from paper versions; basic text can be augmented
through the use of hypertext links to other documents, while graphics can easily be
incorporated as pictures, photographs, icons, page dividing bars, or backgrounds. Pages can
also have hypertext links embedded into different regions, which take the user to a different
page or graphic if they are clicked on; these are known as active image maps. These features
allow web pages to become interactive, acting as the interface to the information as well as
its holder. Dynamic material in the form of movies and sounds is also available to the
designer; all these features push web page design well away from the conventional paper-
based kind.

However, the fact that the web has many more technological features than a book doesn’t
mean that web pages are necessarily better than their paper counterparts. Also, the fact
that a web page is packed full of features doesn’t imply that it gets its message across
effectively. Designing web pages is a developing art, and should be viewed in much the
same way as designing any other interactive system. Good pages have been developed with
the reader as the focus, and act as effective interaction tools or presentation tools to allow
the user to obtain the information he is looking for most effectively.

The web is an example of the usability of the medium being paramount rather than the
technological supremacy of certain aspects of it. For any single aspect of the web, there are
custom multimedia systems that are far superior in terms of quality, usability, speed and so
on. However, the common availability of web browsers on multiple platforms and the low-
tech and usable nature of the system have ensured the web’s popularity and made it
ubiquitous.

The web allows the user to browse documents and follow links transparently, with the
underlying system taking care of the details of fetching the data from different parts of the
world. Theoretically, as far as the user is concerned, any page can be reached as easily as
any other; geographical location ceases to become important, whereas linking by content is
crucial. The ability for anyone to publish information on the web is one factor in its success
as a multimedia system, but the fact that any- one can create a page and, by linking it to

Page 65 of 228
others already in existence, immediately integrate their opinions seamlessly into the
information space is another.

On the move
Mobile phones, PDAs (personal digital assistants), and notebook computers have all
increased the demand to have hypermedia available on the move. Furthermore, across
many countries governments have sold franchises for high-bandwidth mobile services. After
spending billions on these franchises the telecommunications giants really want people to
use new mobile services!

Application areas
There are many applications of hypermedia, too many to describe in detail here. However, it
is worth noting the type of domains in which hypermedia systems have proved successful,
looking briefly at some example systems.

 Rapid prototyping
 Help and documentation
 Education and e-learning
 Collaboration and community
 E-commerce

State Transition Network (STNs)


State transition networks (STNs) have long been used for dialog description.

Consider a simple mouse-based drawing tool depicted by the above figure. It has a menu with two
options, ‘circle’ and ‘line’, and a drawing surface. If you select circle you are allowed to click on two
further points on the drawing surface. The first of these is the circle’s center and the second any point
on the circumference. After the first point is selected, the system draws a ‘rubber band’ line between
the center and the current mouse position. After the second point is chosen, the circle is drawn. The

Page 66 of 228
‘line’ option in the menu is to draw a polyline. That is, the user can select any number of points on the
drawing surface which the system connects with straight lines. The last point is denoted by a double
click on the mouse. Again the system ‘rubber bands’ between successive mouse positions. In the
above figure, each circle denotes a ‘state’ the system can be in. For example, Menu is the state where
the system is waiting for the user to select either ‘circle’ or ‘line’ from the menu, and Circle 2 is the
state after the user has entered the circle center and is waiting for the point on the circumference.
Between the states are arrows, the transitions. These are labeled with the user actions that triggered
the particular transition and the response the system makes. For instance, state Circle 1 is where the
system is waiting for the user to select the circle’s center. If the user clicks on a point, the system
moves into state Circle 2 and responds by drawing the rubber band between the point and the current
mouse position. From this state, the user can click on another point, upon which the system draws
the circle and then moves into the special Finish state. We can see from this that the STN is able to
represent a sequence of user actions and system responses. When in state Circle 1, the user has no
other options: there is only one arc coming from it, corresponding to selecting a point. In other states,
the user has several options. For example, from state Menu the user can select ‘circle’ from the menu,
upon which the system moves into state Circle 1 and highlights the ‘circle’ option on the menu, or
alternatively, the user can select ‘line’ from where the system moves into state Line 1. That is, the STN
is able to describe user choice. There is a choice from state Line 2 also: the user can double click on a
point and finish the polyline, moving to the Finish state, or he can single click, which adds a new point
to the polyline. In the latter case, the transition points back into state Line 2. This represents iteration
– the system stays in state Line 2 accepting any number of points on the polyline, until the user double
clicks on a point. Iterations need not involve just one state. The dialog as it stands only allows you to
draw one circle. You presumably have to go through the menu selection again for each circle drawn.
We could imagine altering the dialog to allow any number of circles to be drawn. To do this, we would
make the arc from state Circle 2 loop back to state Circle 1. This is shown in the figure below. There
are some problems with this arrangement as it stands which we will discuss later. However, note that
already we are using the STN to discuss different dialog options.

Dynamic Web Content – CMS (Content Management System)


A content management system (CMS) is a computer application that supports the creation
and modification of digital content. It is often used to support multiple users working in a
collaborative environment. CMS features vary widely. Most CMSs include Web-based
publishing, format management, history editing and version control, indexing, search, and
retrieval. By their nature, content management systems support the separation of content
and presentation.

A web content management system (WCM or WCMS) is a CMS designed to support the
management of the content of Web pages. Most popular CMSs are also WCMSs. Web

Page 67 of 228
content includes text and embedded graphics, photos, video, audio, maps, and program
code (e.g., for applications) that displays content or interacts with the user.

Such a content management system (CMS) typically has two major components:

 A content management application (CMA) is the front-end user interface that allows
a user, even with limited expertise, to add, modify, and remove content from a
website without the intervention of a webmaster.
 A content delivery application (CDA) compiles that information and updates the
website.

Digital asset management systems are another type of CMS. They manage things such as
documents, movies, pictures, phone numbers, and scientific data. CMSs can also be used for
storing, controlling, revising, and publishing documentation.

Based on market share statistics, the most popular content management system is
WordPress, used by over 27% of all websites on the internet, and by 59% all websites using
a known content management system. Other popular content management systems include
Joomla and Drupal.

Common Features

Content management systems will often contain the following features:

 SEO-friendly URLs
 Integrated and online help
 Modularity and extensibility
 User and group functionality
 Templating support for changing designs
 Install and Upgrade wizards
 Integrated audit logs
 Compliancy with various accessibility frameworks and standards, such as WAI-ARIA

Advantages

 Reduced need to code from scratch


 The ability to create a unified look and feel
 Version control
 Edit permission management
 Disadvantages
 Limited or no ability to create functionality not envisioned in the CMS (e.g., layouts,
web apps, etc.)
 Increased need for special expertise and training for content authors

Wordpress
WordPress is a free and open-source content management system (CMS) based on PHP and
MySQL. WordPress is installed on a web server that is either part of an Internet hosting

Page 68 of 228
service or a network host in its own right. The first case may be a service like
WordPress.com, for example, and the second case could be a computer running the
software package WordPress.org. A local computer may be used for single-user testing and
learning purposes. Features include a plugin architecture and a template system. WordPress
was used by more than 27.5% of the top 10 million websites as of February 2017.
WordPress is reportedly the most popular website management or blogging system in use
on the Web, supporting more than 60 million websites.

https://wordpress.org/

Joomla
Joomla is a free and open-source content management system (CMS) for publishing web
content. It is built on a model–view–controller web application framework that can be used
independently of the CMS.

Joomla is written in PHP, uses object-oriented programming (OOP) techniques (since version
1.5) and software design patterns, stores data in a MySQL, MS SQL (since version 2.5), or
PostgreSQL (since version 3.0) database, and includes features such as page caching, RSS
feeds, printable versions of pages, news flashes, blogs, search, and support for language
internationalization.

https://www.joomla.org/

Drupal
Drupal is a free and open source content-management framework written in PHP and
distributed under the GNU General Public License, provides a back-end framework for at
least 2.2% of all Web sites worldwide – ranging from personal blogs to corporate, political,
and government sites. Systems also use Drupal for knowledge management and for
business collaboration.

The standard release of Drupal, known as Drupal core, contains basic features common to
content-management systems. These include user account registration and maintenance,
menu management, RSS feeds, taxonomy, page layout customization, and system
administration. The Drupal core installation can serve as a simple Web site, a single- or
multi-user blog, an Internet forum, or a community Web site providing for user-generated
content.

"The Drupal Overview", a feature of the project web site, describes it as a content
management framework.Drupal also describes itself as a Web application framework, as it
meets the generally accepted.

As of January 2017 the Drupal community is composed of more than one million members,
including 105,400 users actively contributing, resulting in more than 35,800 free modules
that extend and customize Drupal functionality, over 2,300 free themes that change the

Page 69 of 228
look and feel of Drupal, and at least 1,100 free distributions that allow users to quickly and
easily set up a complex, use-specific Drupal in fewer steps.

Although Drupal offers a sophisticated API for developers, basic Web-site installation and
administration of the framework require no programming skills.

Drupal runs on any computing platform that supports both a Web server capable of running
PHP and a database to store content and configuration.

https://www.drupal.org/

Page 70 of 228
3. Introduction to Object Oriented Programming (C#)
using integrated development environments (IDEs)
Programming paradigms
History of Programming
In this section, we will discuss the backgrounds of the different categories of programming
languages to build a base for the subsequent sections and chapters.

Generations of Programming Languages

1st Generation Languages

The first generation languages are also called Machine Languages. Central Processing Units
(CPUs) identify instructions encoded as bit patterns. A machine language is a collection of
instructions along with the encoding system. An example of a machine language instruction
could be
4056

Which represents the moving of contents from Register 5 to Register 6 of the CPU .

What are registers?


Registers are used for temporarily storing information within the CPU.

Unfortunately, writing programs in a machine language is a tedious task that often leads to
errors that must be located and corrected (a process known as debugging) before the job is
finished.

To solve the shortcomings of machine languages, the concepts of mnemonics was


developed.

2nd Generation Languages

To improve code readability and writing mnemonics were introduced. So for example the
above discussed machine language instruction 4056 can be written as-
MOV R5, R6
using mnemonics. Here MOV represents the move instruction and R5 and R6 represent
registers 5 and 6 respectively. For this mnemonic based system programs called assemblers
were developed to convert mnemonic expressions into machine language instructions and
the programming languages was called the Assembly Language.

Even though the assembly language with its mnemonic based syntax improved code
readability, it still had some issues. Since a piece of code written in assembly language has
instructions that are expressed in terms of a particular machine’s

Page 71 of 228
attributes it by default makes it machine dependent. Code portability is also not easily
possible in machine language based programs because the code must be rewritten to
conform to the new computer’s register configuration and instruction set. Moreover,
assembly language causes the programmer to think about detailed aspects of a machine
leading to increase in coding time.

Due to these issues the 3rd generation programming languages were developed.

3rd Generation Languages

Third generation of programming languages offer primitives of higher level, i.e. they
express instructions in larger increments and also they did not completely rely on the
characteristics of a particular machine thus being machine independent. Some examples are
FORTRAN (FORmula TRANslator), which was developed for scientific and engineering
applications, and COBOL (COmmon Business-Oriented Language), which was developed by
the U.S. Navy for business applications.

For example, the statement assign TotalCost the value Price + ShippingCharge is a high-
level activity and doesn’t instruct how a particular machine should perform the task.
However, it can be implemented by the sequence of machine instructions discussed earlier.

The compiler, was written that translated these high-level program primitives into machine-
language programs. Alternatively another means of implementing third-generation
languages, called interpreters came into existence. These programs executed the
instructions as they were translated instead of recording the translated version for future
use. That is, an interpreter actually executed a program from its high-level form rather than
producing a machine-language copy of a program that would be executed later.

Though the 3rd generation languages tried to be machine independent, in reality they were
not fully so. This is because when a compiler is designed, particular characteristics of the
underlying machine are sometimes reflected as conditions on the language being
translated. For example, the different ways in which machines handle I/O operations have
historically caused the “same” language to have different characteristics, or dialects, on
different machines. Consequently, it is often necessary to make at least minor modifications
to a program to move it from one machine to another.

4th Generation Languages

The third generation programming languages couldn’t achieve real machine independence
but the 4th generation languages succeeded in becoming truly machine independence. Some
examples of 4th generation languages are – C++, Java and C#. In this course we will be
learning programming with the help of C#.

These languages are aimed to be more programmer-friendly and enhance programming


efficiency with usage of English-like words and phrases, and when appropriate, the use of
icons, graphical interfaces and symbolical representations as can be seen in Visual Studio
based languages.

Page 72 of 228
Most of these languages are object oriented and adhere to the following concepts of Object
Oriented Programming (OOP) –

 Objects
 Classes
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

We will discuss in detail about these concepts when we start learning about C#.

Programming languages according to programming style


Arranging programming languages according to generations in reality does not give a very
true picture. Programming languages can be better organised according to their
programming approach. Figure below gives a better picture.

*Source: Brookshear, G. G., & Brookshear, J. G. (2015). Computer science: an overview. Addison-Wesley
Longman Publishing Co., Inc..

The imperative programming style, also known as the procedural programming style,
represents the traditional approach to the programming process. It is the paradigm on
which Python as well as the machine language are based. As the name suggests, the
imperative paradigm defines the programming process to be the development of a
sequence of commands that, when followed, manipulate data to produce the desired result.

In contrast to the imperative style is the declarative style, which asks a programmer to
describe the problem to be solved rather than an algorithm to be followed. More precisely,
a declarative programming system applies a pre-established general-purpose problem-
solving algorithm to solve problems presented to it. In such an environment the task of a
programmer becomes that of developing a precise statement of the problem rather than of
describing an algorithm for solving the problem.

Another programming paradigm is the functional programming style. Under this style a
program is viewed as an entity that accepts inputs and produce outputs. Mathematicians

Page 73 of 228
refer to such entities as functions, which is the reason this approach is called the functional
paradigm. Under this style a program is constructed by connecting smaller predefined
program units (predefined Another programming paradigm is the functional paradigm.
Under this style a program is viewed as an entity that accepts inputs and produces outputs.
Mathematicians refer to such entities as functions, which is the reason this approach is
called the functional paradigm.

Still another programming style (and the most prominent one in today’s software
development) is the object-oriented programming style, which is associated with the
programming process called object-oriented programming (OOP). Following this paradigm,
a software system is viewed as a collection of units, called objects, each of which is capable
of performing the actions that are immediately related to itself as well as requesting actions
of other objects. Together, these objects interact to solve the problem at hand. In this
course OOP concepts using C# will be our prime focus.

Writing code if not done with planning can result in many errors and issues. To avoid these
it is advisable to use basic code planning which can be one with the help of tools like –
algorithms, pseudocodes and flowcharts. In the next section we will discuss these in detail

Algorithms, Pseudocode and Flowcharts

Algorithms
An algorithm is a set of steps that define how a task is performed. Whereas,
programming languages allow algorithms to be presented in a format that is readable by
humans and easily convertible to machine instructions.

However, algorithms are not only applicable to programming they can be used in almost
any decision making circumstance. Here is an example of an algorithm for an activity in
daily life –

Obtain a basket of unshelled peas and an empty bowl. As long as

there are unshelled peas in the basket continue to execute the

following steps:

a. Take a pea from the basket.

b. Break open the pea pod.

c. Dump the peas from the pod into the bowl.

d. Discard the pod

Algorithm can be formally defined as “an ordered set of unambiguous, executable steps
that defines a terminating process.”

Page 74 of 228
An algorithm is abstract and distinct from its representation. A single algorithm can be
represented in many ways. As an example, the algorithm for converting temperature
readings from Celsius to Fahrenheit is traditionally represented as the algebraic formula
F= (9/5)C + 32
But it could be represented by the instruction - Multiply the temperature reading in
Celsius by 9⁄5 and then add 32 to the product

or even in the form of an electronic circuit. In each case the underlying algorithm is the
same; only the representations differ.

Pseudocode
In general, a pseudocode is a notational system in which ideas can be expressed
informally during the algorithm development process.

One way to obtain a pseudocode is simply to loosen the rules of a formal


programming language, borrowing the syntax-semantic structures of the language,
intermixed with less formal constructs. There are many such pseudocode variants,
because there are many programming languages in existence. Two particularly popular
choices are loose versions of the languages Algol and Pascal, largely because these were
widely used in textbooks and academic papers for decades. More recently, pseudocode
reminiscent of the Java and C languages has proliferated, again because most
programmers will have at least a reading knowledge of these languages. Regardless of
where a pseudocode borrows its syntax from, one essential property is required for it to
serve its purpose in expressing algorithms:

A pseudocode must have a consistent, concise notation for representing recurring


semantic structures.

For example the following algorithm –

Depending on whether the year is a leap year, divide the total by 366 or 365,
respectively can be converted to the following pseudocode –

if (year is leap year):

daily total = total / 366

else

daily total = total / 365

A picture speaks a thousand words and sometimes a diagram can explain a piece of code
more clearly than algorithms and pseudocodes. One such diagram is a flowchart about
which we will learn in the next.

Flowchart
A flowchart is a visual representation of the sequence of steps and decisions needed to
perform a process. Each step in the sequence is noted within a diagram shape. Steps are

Page 75 of 228
linked by connecting lines and directional arrows. This allows anyone to view the flowchart
and logically follow the process from beginning to end.

The following figure below explains the symbols used in a flowchart.

* Source: http://www.owlnet.rice.edu/~ceng303/manuals/fortran/FOR3_3.html

Page 76 of 228
Let us see some more flowchart examples along with their pseudo codes:

Page 77 of 228
Page 78 of 228
C# - an objected oriented paradigm
C# sharp will be the language of choice used in this course and throughout all the examples
used in this book. Like, other objected oriented languages C# shares the common concepts
like - objects, classes, encapsulation, abstraction, inheritance and polymorphism.

Now, we will briefly describe these concepts and then will discuss them in detail as we move
along the concepts in this course.

Class
A class is the core of C# as it is for other object oriented programming (OOP) languages. In
OOP languages it is mandatory to create a class for representing data.

A class is a blueprint of an object that contains variables for storing data and functions to
perform operations on the data.

A class will not occupy any memory space and hence it is only a logical representation of
data.

To create a class, you simply use the keyword "class" followed by the class name:

e.g. class Employee


{

}
Objects
Objects are the basic run-time entities of an object oriented system. They may represent a
person, a place or any item that the program must handle.

"An object is a software bundle of related variable and methods."

"An object is an instance of a class"

Abstraction
Abstraction is "To represent the essential feature without representing the background
details."

Abstraction lets you focus on what the object does instead of how it does it.

Abstraction provides you a generalized view of your classes or objects by providing relevant
information.

Abstraction is the process of hiding the working style of an object, and showing the
information of an object in an understandable manner.

Encapsulation

Wrapping up a data member and a method together into a single unit (in other words class)
is called Encapsulation.

Page 79 of 228
Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data
related to an object into that object.

Encapsulation is like your bag in which you can keep your pen, book etcetera. It means this
is the property of encapsulating members and functions.

class Bag
{
book;
pen;
ReadBook();
}
Encapsulation means hiding the internal details of an object, in other words how an object
does something.

Inheritance
When a class includes a property of another class it is known as inheritance.

Inheritance is a process of object reusability.

For example, a child includes the properties of its parents.

Polymorphism
Polymorphism means one name, many forms.

One function behaves in different forms.

In other words, "Many forms of a single object is called Polymorphism."

C# - the programming environment


The C# language is platform-neutral, but it was written to work well with the Microsoft .NET
Framework. Before delving in to the C# language, in this section we will discuss the
environment in which C# is compiled and run.

Memory Management
C# relies on the runtime to perform automatic memory management. The Common
Language Runtime (CLR) has a garbage collector that executes as part of your program,
reclaiming memory for objects that are no longer referenced. This frees programmers from
explicitly deallocating the memory for an object, eliminating the problem of incorrect
pointers encountered in languages such as C++.

C# does not eliminate pointers: it merely makes them unnecessary for most programming
tasks. For performance-critical hotspots and interoperability, pointers may be used, but they
are permitted only in blocks that are explicitly marked unsafe.

Platform Support
Historically, C# was used almost entirely for writing code to run on Windows platforms.
Recently, however, Microsoft and other companies have invested in otherplatforms,

Page 80 of 228
including Mac OS X and iOS, and Android. Xamarin™ allows cross-platform C# development
for mobile applications, and Portable Class

Libraries are becoming increasingly widespread. Microsoft’s ASP.NET 5 is a new web hosting
framework that can run either on the .NET Framework or on .NET Core, a new small, fast,
open source, cross-platform runtime.

The .NET Framework and CLR


The .NET Framework is a technology that supports building and running the next generation
of applications and XML Web services. The .NET Framework is designed to fulfill the
following objectives:

 To provide a consistent object-oriented programming environment whether object


code is stored and executed locally, executed locally but Internet-distributed, or
executed remotely.
 To provide a code-execution environment that minimizes software deployment and
versioning conflicts.
 To provide a code-execution environment that promotes safe execution of code,
including code created by an unknown or semi-trusted third party.
 To provide a code-execution environment that eliminates the performance problems
of scripted or interpreted environments.
 To make the developer experience consistent across widely varying types of
applications, such as Windows-based applications and Web-based applications.
 To build all communication on industry standards to ensure that code based on the
.NET Framework can integrate with any other code.

The .NET Framework consists of the CLR plus a vast set of libraries. The libraries consist of
core libraries and applied libraries, which depend on the core libraries.

The CLR is the runtime for executing managed code. C# is one of several managed
languages that get compiled into managed code. Managed code is packaged into an
assembly, in the form of either an executable file (an .exe) or a library (a .dll), along with
type information, or metadata. Managed code is represented in intermediate language or
IL. When the CLR loads an assembly, it converts the IL into the native code of the machine,
such as x86. This conversion is done by the CLR’s JIT (just-in-time) compiler. An assembly
retains almost all of the original source language constructs, which makes it easy to inspect
and even generate code dynamically.

The CLR performs as a host for numerous runtime services. Examples of these services
include memory management, the loading of libraries, and security services. The CLR is
language-neutral, allowing developers to build applications in multiple languages (e.g., C#,
F#, Visual Basic .NET and Managed C++).

The .NET Framework contains Core base class libraries (BCL) libraries for writing just about
any Windows- or web-based application.

Some of the components of the .Net framework

 Common Language Runtime (CLR)

Page 81 of 228
 The .Net Framework Class Library
 Common Language Specification
 Common Type System
 Metadata and Assemblies
 Windows Forms
 ASP.Net and ASP.Net AJAX
 ADO.Net
 Windows Workflow Foundation (WF)
 Windows Presentation Foundation (WPF)
 Windows Communication Foundation (WCF)
 LINQ

We will be focussing on Windows Forms in this book.

The figure below below gives a high level overview of the .net framework environment.

*Source: https://blogs.msdn.microsoft.com/bethmassi/2015/02/25/understanding-net-2015/

The following figure below gives the representation of the core of .net framework.

Page 82 of 228
*Source: https://blogs.msdn.microsoft.com/bethmassi/2015/02/25/understanding-net-2015/

From source code to running application


The following figure below gives an overview of how your code is built and run.

*Source: https://blogs.msdn.microsoft.com/bethmassi/2015/02/25/understanding-net-2015/

You write code taking very modular references to the parts of the BCL and App Model you
need. Roslyn is the compiler that takes your code and produces platform independent
Intermediate Language (IL). Besides the compiler pipeline, there is a rich set of APIs you can
use to do all sorts of analysis on your code. If you’re using Visual Studio, there are a ton of

Page 83 of 228
new IDE features that utilize these APIs to give you a much more productive coding
experience.

If you’re building a universal Windows app, the .NET Native tool chain takes it from there.
References are built with your app into a native image deployed locally with a minimal
runtime. If you’re building an ASP.NET 5 app, references and the CoreCLR are deployed with
your app locally to the server. JIT compilation then happens on startup using RyuJIT.

Additionally, ASP.NET 5 allows you to make changes in your code, save the changes, and
refresh the browser without explicitly re-building the project. Visual Studio uses Roslyn to
enable this dynamic compilation. You still have all of the structure and power of a compiled
framework, but the development experience feels more like an interpreted language.

Integrated Development Environments (IDEs)


Most programming languages can be written in a simple text editor (e.g. notepad) and can
be compiled and run using the command line. However, creating large applications using a
text editor and command line is an arduous task in terms of code management and often
results in many errors. To overcome these issues an Integrated Development Environment
(IDE) can be used. IDEs help organise code into projects, contains a code editor, a compiler
or interpreter and a debugger that the developer accesses through a single graphical user
interface (GUI). The IDE we will use is called Visual Studio. The latest version being Visual
Studio 2017. You can download the latest available version from your Microsoft Dream
Spark account.

Apart from a powerful IDE like Visual Studio there are many IDEs which are similar in
appearance to notepad but they have some limited code organisation, compilation and
running features. For example: notepad++ and brackets (this is popular for web
development).

The name of the C# compiler is csc.exe. You can either use Visual Studio to compile, or call
csc manually from the command line. We will see how to run a C# code using command line
and IDE in the next section of this chapter. Now let’s have a brief overview of the important
Visual Studio features.

Visit Microsoft Developer Network (MSDN)-


It contains a plethora of tutorials, tutorial-videos, documentation and downloads related to the
Microsoft Technologies

Visual Studio – an overview


Here we give an overview of the main functionalities of Visual Studio. Do not worry if it
looks a bit overwhelming, you will use it most of the time during this course and will
become very comfortable with it.

Page 84 of 228
You can use Visual Studio to create many kinds of applications, from simple store apps and
games for mobile clients, to large, complex systems that power enterprises and data
centres. You can create

 apps and games that run not only on Windows, but also Android and iOS.
 websites and web services based on ASP.NET, JQuery, AngularJS, and other popular
frameworks
 applications for platforms and devices as diverse as Azure, Office, Sharepoint,
Hololens, Kinect, and Internet of Things, to name just a few examples
 games and graphics-intensive applications for a variety of Windows devices,
including Xbox, using DirectX.

The following image shows the Visual Studio IDE with an open project, and the Solution
Explorer window for navigating in the project files, and the Team Explorer window for
navigating source control and work item tracking. The features in the title bar that are called
out are explained below in more detail. The following figure below shows the interface.

*Source: https://msdn.microsoft.com/en-us/library/dn762121.aspx#IDE Basics

Page 85 of 228
Creating solutions and projects:
Although you can use Visual Studio to browse individual code files, more commonly you will
be working in a project. A Visual Studio project is a collection of files and resources that are
compiled to a single binary executable file for applications (for example, an .exe, DLL, or
appx). Click in File and then choose the New Project option. From there you can select the
kind of project you want to work on, in this course we will mostly work on Windows Forms
projects.

Writing, navigating and understanding code:


You can edit individual files in the text editor by clicking File | Open | File. To edit files in an
open project, click on the file name in Solution Explorer. The code is colorized, and you can
personalize the color scheme by typing “Colors” in Quick Launch. You can have lots of text
editor tabbed windows open at once. You can split each window independently. You can
also run the text editor in full-screen mode. The figure below shows a code editor.

The text editor is highly interactive (if you want it to be) with many productivity features
that help you write better code faster. The features vary by language, and you don’t have to
use any of them (Type "Editor" in Quick Launch) to turn features on or off: Some of the
common productivity features are:

 Refactoring: includes operations such as intelligent renaming of variables, moving


selected lines of code into a separate function, moving code to other locations,
reordering function parameters, and more.
 IntelliSense: is an umbrella term for a set of popular features that display type
information about your code directly in the editor and, in some cases, write small
bits of code for you. It’s like having basic documentation inline in the editor, which
saves you from having to look up type information in a separate help window.
IntelliSense features vary by language. For more information, see Visual C#
IntelliSense, Visual C++ Intellisense, JavaScript IntelliSense, Visual Basic-Specific
IntelliSense. The following illustration shows some IntelliSense features at work:

Page 86 of 228
 Squiggles: alert you to errors or potential problems in your code in real time as you
type, which enables you to fix them immediately without waiting for the error to be
discovered during compilation or run time. If you hover over the squiggle, you see
additional information about the error. A light bulb may also appear in the left
margin with suggestions for how to fix the error. For more information, see Perform
quick actions with light bulbs.

 Bookmarks: enable you to navigate quickly to specific lines in files that you are
actively working on.
 The Call Hierarchy window: can be invoked in the text editor context menu to show
the methods that call, and are called by, the method under the caret.
 Code Lens: enables you to find references and changes to your code, linked bugs,
work items, code reviews, and unit tests, all without leaving the editor. For more
information, see Find code changes and other history.
 The Peek to Definition: window shows a method or type definition inline, without
navigating away from your current context. This window now works for XAML, too.
 The Go To Definition: context menu option takes you directly to the place where the
function or object is defined. Other navigation commands are also available by right-
clicking in the editor.
 The Object Browser: enables you to inspect .NET or Windows Runtime assemblies
on your system to see what types they contain and what methods and properties
those types contain.

Page 87 of 228
Compiling and building your code:
To compile and run your code with a single keystroke, press F5.

The Build toolbar enables you to specify whether to build a debug version of your program,
with symbols and extra error checking enabled to support breakpoints and single stepping
in the debugger, or a release build, which is what you will ultimately give to customers. You
can configure more build settings and many other settings on the property page for a
project. Right-click on the project node in Solution Explorer and choose Properties. You can
also run builds from the command line.

The output from the build, including an error or success messages, appear in the Output
Window. The Error List window (shown below) gives detailed information on build errors.

Page 88 of 228
4. C#- Language Basics & Introduction to Windows
Forms
The first C# program
A C# program consists of the following parts:

 Namespace declaration
 A class
 Class methods
 Class attributes
 A Main method
 Statements and Expressions
 Comments

Following the tradition of programming, let’s write a ‘Hello World’ program.

using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}

To write, compile and run this follow the following steps-

 Open a text editor (just good old notepad would do) and add type the above
mentioned code.
 Save the file as helloworld.cs
 Open the command prompt and go to the directory where you saved the file.
 Type csc helloworld.cs and press enter to compile your code.
 If there are no errors in your code, the command prompt takes you to the next line
and generates helloworld.exe executable file.
 Type helloworld to execute your program.
 You can see the output Hello World printed on the screen.

Now let us understand this code


 The first line of the program using System; - the using keyword is used to include the
System namespace in the program. A program generally has multiple using
statements.

Page 89 of 228
 The next line has the namespace declaration. A namespace is a collection of classes.
The HelloWorldApplication namespace contains the class HelloWorld.
 The next line has a class declaration, the class HelloWorld contains the data and
method definitions that your program uses. Classes generally contain multiple
methods. Methods define the behavior of the class. However, the HelloWorld class
has only one method Main.
 The next line defines the Main method, which is the entry point for all C# programs.
The Main method states what the class does when executed.
 The next line /*...*/ is ignored by the compiler and it is put to add comments in the
program.
 The Main method specifies its behavior with the statement Console.WriteLine("Hello
World");
 WriteLine is a method of the Console class defined in the System namespace. This
statement causes the message "Hello, World!" to be displayed on the screen.
 The last line Console.ReadKey(); is for the VS.NET Users. This makes the program
wait for a key press and it prevents the screen from running and closing quickly
when the program is launched from Visual Studio .NET.

Since we have already discussed about Visual Studio, follow the proceeding steps to run the
above Hello World code in it.

 Start Visual Studio.


 On the menu bar, choose File -> New -> Project.
 Choose Visual C# from templates, and then choose Windows.
 Choose Console Application.
 Specify a name for your project and click OK button.
 This creates a new project in Solution Explorer.
 Write code in the Code Editor.
 Click the Run button or press F5 key to execute the project. A Command Prompt
window appears that contains the line Hello World.

Basic Syntax
Identifiers and Keywords
Identifiers are names that programmers (yes that’s you!!) choose for their classes, methods,
variables, and so on.

The basic rules for naming classes in C# are as follows:

 A name must begin with a letter that could be followed by a sequence of letters,
digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
 It must not contain any embedded space or symbol such as ? - + ! @ # % ^ & * ( ) [ ] {
} . ; : " ' / and \. However, an underscore ( _ ) can be used.
 It should not be a C# keyword.

Page 90 of 228
Keywords are names that mean something special to the compiler. Keywords cannot be
used as identifiers. However, if you want to use these keywords as identifiers, you may
prefix the keyword with the @ character.

In C#, some identifiers have special meaning in context of code, such as get and set are
called contextual keywords.

The following table lists the reserved keywords and contextual keywords in C#:

Reserved Keywords

abstract as base bool break byte case

catch char checked class const continue decimal

default delegate do double else enum event

explicit extern false finally fixed float for

foreach goto if implicit in in (generic int


modifier)

interface internal is lock long namespace new

null object operator out out (generic override params


modifier)

private protected public readonly ref return sbyte

sealed short sizeof stackalloc static string struct

switch this throw true try typeof uint

ulong unchecked unsafe ushort using virtual void

volatile while

Contextual Keywords

add alias ascending descending dynamic from get

global group into join let orderby partial


(type)

partial remove select set


(method)

What are identifiers and keywords in the Hello World code?

Page 91 of 228
Literals, Punctuators, and Operators

Literals are primitive pieces of data lexically embedded into the program. Consider the
following piece of code-

using System;
class Test
{
static void Main()
{
int x = 12 * 30;
Console.WriteLine (x);
}
}

The literals we used in the following program are – 12 and 30.

Punctuators help demarcate the structure of the program. These are the punctuators we
used in our example program:
{ } ;
The braces group multiple statements into a statement block. The semicolon terminates a
statement. (Statement blocks, however, do not require a semicolon.) Statements can wrap
multiple lines:
Console.WriteLine (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10);

An operator transforms and combines expressions. Most operators in C# are denoted with a
symbol, such as the multiplication operator, *. We will discuss operators in more detail later
in this chapter. These are the operators we used in our example program:
. () * =
A period denotes a member of something (or a decimal point with numeric literals).

Parentheses are used when declaring or calling a method; empty parentheses are used
when the method accepts no arguments. An equals sign performs assignment. (The double
equals sign, ==, performs equality comparison, as we’ll see later.)

Comments

C# offers two different styles of source-code documentation: single-line comments and


multiline comments. A single-line comment begins with a double forward slash and
continues until the end of the line. For example:
int x = 3; // Comment about assigning 3 to x
A multiline comment begins with /* and ends with */. For example:
int x = 3; /* This is a comment that
spans two lines */

Page 92 of 228
C# Types
A type defines the blueprint for a value. In our example, we used two literals of type int with
values 12 and 30. We also declared a variable of type int whose name was x:

using System;
class Test
{
static void Main()
{
int x = 12 * 30;
Console.WriteLine (x);
}
}

A variable denotes a storage location that can contain different values over time. In
contrast, a constant always represents the same value (more on this later):

const int y = 360;

All values in C# are instances of a type. The meaning of a value, and the set of possible
values a variable can have, is determined by its type.

The main C# types are:

 Value types
 Reference types
 Pointer types

Value Type
Value type variables can be assigned a value directly. They are derived from the class
System.ValueType.

The value types directly contain data. Some examples are int, char, and float, which stores
numbers, alphabets, and floating point numbers, respectively. When you declare an int
type, the system allocates memory to store the value.

The value Value types are:

 Numeric
o Signed integer (sbyte, short, int, long)
o Unsigned integer (byte, ushort, uint, ulong)
o Real number (float, double, decimal)
 Logical (bool)
 Character (char)

Page 93 of 228
Numeric Value Type
C# has the predefined numeric types shown in table below.

Numeric Literals
Integral literals can use decimal or hexadecimal notation; hexadecimal is denoted with
the 0x prefix. For example:
int x = 127;
long y = 0x7F;
Real literals can use decimal and/or exponential notation. For example:
double d = 1.5;
double million = 1E06;

Numeric literal type inference


By default, the compiler infers a numeric literal to be either double or an integral type:

 If the literal contains a decimal point or the exponential symbol (E), it is a double.
 Otherwise, the literal’s type is the first type in this list that can fit the literal’s value:
int, uint, long, and ulong

Page 94 of 228
Modify the Hello World Code and add the following statements to it and run it-

Console.WriteLine ( 1.0.GetType()); // Double (double)


Console.WriteLine ( 1E06.GetType()); // Double (double)
Console.WriteLine ( 1.GetType()); // Int32 (int)
Console.WriteLine ( 0xF0000000.GetType()); // UInt32 (uint)
Console.WriteLine (0x100000000.GetType()); // Int64 (long)

Numeric suffixes
Numeric suffixes explicitly define the type of a literal. Suffixes can be either lower- or
uppercase, and are as follows:

double Versus decimal


double is useful for scientific computations (such as computing spatial coordinates).
decimal is useful for financial computations and values that are “man-made” rather than
the result of real-world measurements. Here’s a summary of the differences:

Real-Number Rounding Errors

Page 95 of 228
float and double internally represent numbers in base 2. For this reason, only numbers
expressible in base 2 are represented precisely. Practically, this means most literals with a
fractional component (which are in base 10) will not be represented precisely. For example:
float tenth = 0.1f; // Not quite 0.1
float one = 1f;
Console.WriteLine (one - tenth * 10f); // -1.490116E-08
This is why float and double are bad for financial calculations. In contrast, decimal works in
base 10 and so can precisely represent numbers expressible in base 10 (as well as its factors,
base 2 and base 5). Since real literals are in base 10, decimal can precisely represent
numbers such as 0.1. However, neither double nor decimal can precisely represent a
fractional number whose base 10 representation is recurring:
decimal m = 1M / 6M; // 0.1666666666666666666666666667M
double d = 1.0 / 6.0; // 0.16666666666666666
This leads to accumulated rounding errors:
decimal notQuiteWholeM = m+m+m+m+m+m; //1.0000000000000000000000000002M
double notQuiteWholeD = d+d+d+d+d+d;
// 0.99999999999999989
which breaks equality and comparison operations:
Console.WriteLine (notQuiteWholeM == 1M); // False
Console.WriteLine (notQuiteWholeD < 1.0); // True

Logical (Boolean) Value Type


C#’s bool type (aliasing the System.Boolean type) is a logical value that can be assigned the
literal true or false. Although a Boolean value requires only one bit of storage, the runtime
will use one byte of memory, since this is the minimum chunk that the runtime and
processor can efficiently work with. To avoid space inefficiency in the case of arrays, the
Framework provides a BitArray class in the System.Collections namespace that is designed
to use just one bit per Boolean value.

Equality and Comparison Operators


== and != test for equality and inequality of any type, but always return a bool value.3
Value types typically have a very simple notion of equality:

Run this code and see the output

int x = 1;
int y = 2;
int z = 1;
Console.WriteLine (x == y); // False
Console.WriteLine (x == z); // True

More about these types will be discussed when we discuss the various Boolean operators.

Page 96 of 228
char Value Type

C#’s char type (aliasing the System.Char type) represents a Unicode character and occupies
2 bytes. A char literal is specified inside single quotes:
char c = 'A'; // Simple character
Escape sequences express characters that cannot be expressed or interpreted literally. An
escape sequence is a backslash followed by a character with a special meaning. For
example:
char newLine = '\n';
char backSlash = '\\';
The escape sequence characters are shown in the following table below:

Enums
An enumeration is a set of named integer constants. An enumerated type is declared using
the enum keyword.

C# enumerations are value data type. In other words, enumeration contains its own values
and cannot inherit or cannot pass inheritance.

Declaring enum Variable


The general syntax for declaring an enumeration is:
enum <enum_name>
{
enumeration list
};
Where,

 The enum_name specifies the enumeration type name.


 The enumeration list is a comma-separated list of identifiers.

Each of the symbols in the enumeration list stands for an integer value, one greater than
the symbol that precedes it. By default, the value of the first enumeration symbol is 0.
For example:

Page 97 of 228
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

Reference types
The reference types do not contain the actual data stored in a variable, but they contain a
reference to the variables.

In other words, they refer to a memory location. Using multiple variables, the reference
types can refer to a memory location. If the data in the memory location is changed by one
of the variables, the other variable automatically reflects this change in value. Example of
built-in reference types are: object, dynamic, and string.

Object Type
The Object Type is the ultimate base class for all data types in C# Common Type System
(CTS). Object is an alias for System.Object class. The object types can be assigned values
of any other types, value types, reference types, predefined or user-defined types.
However, before assigning values, it needs type conversion.

When a value type is converted to object type, it is called boxing and on the other hand,
when an object type is converted to a value type, it is called unboxing.
object obj;
obj = 100; // this is boxing

Dynamic Type
You can store any type of value in the dynamic data type variable. Type checking for
these types of variables takes place at run-time.

Syntax for declaring a dynamic type is:


dynamic d = 20;
Dynamic types are similar to object types except that type checking for object type
variables takes place at compile time, whereas that for the dynamic type variables takes
place at run time.

String Type
The String Type allows you to assign any string values to a variable. The string type is an
alias for the System.String class. It is derived from object type. The value for a string type
can be assigned using string literals in two forms: quoted and @quoted.

For example,
String str = "Hello C#";
A @quoted string literal looks as follows:
@" Hello C#";

Pointer Type
Pointer type variables store the memory address of another type. Pointers in C# have
the same capabilities as the pointers in C or C++.

Syntax for declaring a pointer type is:


type* identifier;

Page 98 of 228
For example,
char* cptr;
int* iptr;

Type Conversions
Type conversion is converting one type of data to another type. It is also known as Type
Casting. In C#, type casting has two forms:

 Implicit type conversion - These conversions are performed by C# in a type-safe


manner. For example, are conversions from smaller to larger integral types and
conversions from derived classes to base classes.
 Explicit type conversion - These conversions are done explicitly by users using the
pre-defined functions. Explicit conversions require a cast operator.
int x = 12345; // int is a 32-bit integral
long y = x; // Implicit conversion to 64-bit integral
short z = (short)x; // Explicit conversion to 16-bit integral

The following example shows an explicit type conversion:

using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
double d = 5673.74;
int i;

// cast double to int.


i = (int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}

Run the above code and check the output.

Page 99 of 228
Floating-point to integral conversions
All integral types may be implicitly converted to all floating-point types:
int i = 1;
float f = i;
The reverse conversion must be explicit:
int i2 = (int)f;

C# Type Conversion Methods


C# provides the following built-in type conversion methods:

Sr.No Methods & Description

1 ToBoolean
Converts a type to a Boolean value, where possible.

2 ToByte
Converts a type to a byte.

3 ToChar
Converts a type to a single Unicode character, where possible.

4 ToDateTime
Converts a type (integer or string type) to date-time structures.

5 ToDecimal
Converts a floating point or integer type to a decimal type.

6 ToDouble
Converts a type to a double type.

7 ToInt16
Converts a type to a 16-bit integer.

8 ToInt32
Converts a type to a 32-bit integer.

9 ToInt64
Converts a type to a 64-bit integer.

10 ToSbyte
Converts a type to a signed byte type.

11 ToSingle
Converts a type to a small floating point number.

Page 100 of 228


12 ToString
Converts a type to a string.

13 ToType
Converts a type to a specified type.

14 ToUInt16
Converts a type to an unsigned int type.

15 ToUInt32
Converts a type to an unsigned long type.

16 ToUInt64
Converts a type to an unsigned big integer.

Page 101 of 228


Run the following code and check the output-

using System;
namespace TypeConversionApplication
{
class StringConversion
{
static void Main(string[] args)
{
int i = 75;
float f = 53.005f;
double d = 2345.7652;
bool b = true;

Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
Console.WriteLine(d.ToString());
Console.WriteLine(b.ToString());
Console.ReadKey();

}
}
}

Variables
A variable is nothing but a name given to a storage area that our programs can manipulate.
Each variable in C# has a specific type, which determines the size and layout of the variable's
memory the range of values that can be stored within that memory and the set of
operations that can be applied to the variable.

The basic value types provided in C# can be categorized as:

Type Example

Page 102 of 228


Integral types sbyte, byte, short, ushort, int, uint, long, ulong, and char

Floating point types float and double

Decimal types decimal

Boolean types true or false values, as assigned

Nullable types Nullable data types

Local variables must be assigned a value before they can be read. For example, the following
code results in a compile-time error:
static void Main()
{
int x;
Console.WriteLine (x); // Compile-time error
}
The following code outputs 0, because fields are implicitly assigned a default value:
class Test
{
static int x;
static void Main() { Console.WriteLine (x); } // 0
}

Default Values
All type instances have a default value. The default value for the predefined types is the
result of a bitwise zeroing of memory:

You can obtain the default value for any type with the default keyword:

decimal d = default (decimal);

Defining Variables
Syntax for variable definition in C# is:
<data_type> <variable_list>;
Here, data_type must be a valid C# data type including char, int, float, double, or any user-
defined data type, and variable_list may consist of one or more identifier names separated
by commas.

Page 103 of 228


Some valid variable definitions are shown here:
int i, j, k;
char c, ch;
float f, salary;
double d;

Initializing Variables
Variables are initialized (assigned a value) with an equal sign followed by a constant
expression. The general form of initialization is:
variable_name = value;
Variables can be initialized in their declaration. The initializer consists of an equal sign
followed by a constant expression as:
<data_type> <variable_name> = value;
Some examples are:
int d = 3, f = 5; /* initializing d and f. */
byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */
It is a good programming practice to initialize variables properly, otherwise sometimes
program may produce unexpected result.

The following example uses various types of variables, run it and check the output:

Page 104 of 228


using System;
namespace VariableDefinition
{
class Program
{
static void Main(string[] args)
{
short a;
int b ;
double c;

/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b,
c);
Console.ReadLine();
}
}
}

Accepting Values from User


The Console class in the System namespace provides a function ReadLine() for accepting
input from the user and store it into a variable.

For example,
int num;
num = Convert.ToInt32(Console.ReadLine());

The function Convert.ToInt32() converts the data entered by the user to int data type,
because Console.ReadLine() accepts the data in string format.
var—Implicitly Typed Local Variables

It is often the case that you declare and initialize a variable in one step. If the compiler is
able to infer the type from the initialization expression, you can use the keyword var
(introduced in C# 3.0) in place of the type declaration. For example:
var x = "hello";

Page 105 of 228


var y = new System.Text.StringBuilder();
var z = (float)Math.PI;

This is precisely equivalent to:


string x = "hello";
System.Text.StringBuilder y = new System.Text.StringBuilder();
float z = (float)Math.PI;

Because of this direct equivalence, implicitly typed variables are statically typed. For
example, the following generates a compile-time error:
var x = 5;
x = "hello"; // Compile-time error; x is of type int

Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C# has rich set of built-in operators and provides the following type of
operators:

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

Arithmetic Operators
Following table shows all the arithmetic operators supported by C#. Assume variable A
holds 10 and variable B holds 20 then:

Operator Description Example

+ Adds two operands A + B = 30

- Subtracts second operand from the first A - B = -10

* Multiplies both operands A * B = 200

/ Divides numerator by de-numerator B/A=2

% Modulus Operator and remainder of after an integer division B%A=0

++ Increment operator increases integer value by one A++ = 11

-- Decrement operator decreases integer value by one A-- = 9

The increment and decrement operators (++, --) increment and decrement numeric types by
1. The operator can either follow or precede the variable, depending on whether you want
its value before or after the increment/decrement. For example:
int x = 0, y = 0;

Page 106 of 228


Console.WriteLine (x++); // Outputs 0; x is now 1
Console.WriteLine (++y); // Outputs 1; y is now 1

Run the following code to understand the arithmetic operators better –

using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 21;
int b = 10;
int c;

c = a + b;
Console.WriteLine("Line 1 - Value of c is {0}", c);
c = a - b;
Console.WriteLine("Line 2 - Value of c is {0}", c);
c = a * b;
Console.WriteLine("Line 3 - Value of c is {0}", c);
c = a / b;
Console.WriteLine("Line 4 - Value of c is {0}", c);
c = a % b;
Console.WriteLine("Line 5 - Value of c is {0}", c);
c = a++;
Console.WriteLine("Line 6 - Value of c is {0}", c);
c = a--;
Console.WriteLine("Line 7 - Value of c is {0}", c);
Console.ReadLine();
}
}
}

Relational Operators
Following table shows all the relational operators supported by C#. Assume variable A holds
10 and variable B holds 20, then:

Operator Description Example

== Checks if the values of two operands are equal or not, if yes then condition (A == B)
becomes true. is not
true.

!= Checks if the values of two operands are equal or not, if values are not equal then (A != B)
condition becomes true. is true.

> Checks if the value of left operand is greater than the value of right operand, if yes (A > B)
then condition becomes true. is not
true.

< Checks if the value of left operand is less than the value of right operand, if yes (A < B)
then condition becomes true. is true.

Page 107 of 228


>= Checks if the value of left operand is greater than or equal to the value of right (A >= B)
operand, if yes then condition becomes true. is not
true.

<= Checks if the value of left operand is less than or equal to the value of right (A <= B)
operand, if yes then condition becomes true. is true.

Page 108 of 228


Run the following code to understand the relational operators better –

using System;
class Program
{
static void Main(string[] args)
{
int a = 21;
int b = 10;

if (a == b)
{
Console.WriteLine("Line 1 - a is equal to b");
}
else
{
Console.WriteLine("Line 1 - a is not equal to b");
}

if (a < b)
{
Console.WriteLine("Line 2 - a is less than b");
}
else
{
Console.WriteLine("Line 2 - a is not less than b");
}

if (a > b)
{
Console.WriteLine("Line 3 - a is greater than b");
}
else
{
Console.WriteLine("Line 3 - a is not greater than
b");
}
/* Lets change value of a and b */
a = 5;
b = 20;

if (a <= b)
{
Console.WriteLine("Line 4 - a is either less than or
equal to b");
}

if (b >= a)
{
Console.WriteLine("Line 5-b is either greater than
or equal to b");
}
}
}

Page 109 of 228


Logical Operators
Following table shows all the logical operators supported by C#. Assume variable A holds
Boolean value true and variable B holds Boolean value false, then:

Operator Description Example

&& Called Logical AND operator. If both the operands are non zero then condition (A &&
becomes true. B) is
false.

|| Called Logical OR Operator. If any of the two operands is non zero then condition (A || B)
becomes true. is true.

! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a !(A &&
condition is true then Logical NOT operator will make false. B) is
true.

Page 110 of 228


Run the following code to understand the relational operators better –

using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
bool a = true;
bool b = true;

if (a && b)
{
Console.WriteLine("Line 1 - Condition is true");
}

if (a || b)
{
Console.WriteLine("Line 2 - Condition is true");
}
/* lets change the value of a and b */
a = false;
b = true;

if (a && b)
{
Console.WriteLine("Line 3 - Condition is true");
}
else
{
Console.WriteLine("Line 3 - Condition is not
true");
}

if (!(a && b))


{
Console.WriteLine("Line 4 - Condition is true");
}
Console.ReadLine();
}
}
}

Page 111 of 228


Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |,
and ^ are as follows:

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; then in the binary format they are as follows:
A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The Bitwise operators supported by C# are listed in the following table. Assume variable A
holds 60 and variable B holds 13, then:

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) = 12,
which is
0000 1100

| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61,


which is
0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) = 49,
which is
0011 0001

~ Binary Ones Complement Operator is unary and has the effect of 'flipping' (~A ) = 61,
bits. which is
1100 0011
in 2's

Page 112 of 228


complement
due to a
signed
binary
number.

<< Binary Left Shift Operator. The left operands value is moved left by the A << 2 =
number of bits specified by the right operand. 240, which
is 1111 0000

>> Binary Right Shift Operator. The left operands value is moved right by the A >> 2 = 15,
number of bits specified by the right operand. which is
0000 1111

Run the following code to understand the bitwise operators better –

using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */


Console.WriteLine("Line 1 - Value of c is {0}", c );

c = a | b; /* 61 = 0011 1101 */
Console.WriteLine("Line 2 - Value of c is {0}", c);

c = a ^ b; /* 49 = 0011 0001 */
Console.WriteLine("Line 3 - Value of c is {0}", c);

c = ~a; /*-61 = 1100 0011 */


Console.WriteLine("Line 4 - Value of c is {0}", c);

c = a << 2; /* 240 = 1111 0000 */


Console.WriteLine("Line 5 - Value of c is {0}", c);

c = a >> 2; /* 15 = 0000 1111 */


Console.WriteLine("Line 6 - Value of c is {0}", c);
Console.ReadLine();
}
}
}

Page 113 of 228


Assignment Operators
There are following assignment operators supported by C#:

Operator Description Example

= Simple assignment operator, Assigns values from right side operands to left side C=A+B
operand assigns
value of A
+ B into C

+= Add AND assignment operator, It adds right operand to the left operand and C += A is
assign the result to left operand equivalent
to C = C +
A

-= Subtract AND assignment operator, It subtracts right operand from the left C -= A is
operand and assign the result to left operand equivalent
to C = C -
A

*= Multiply AND assignment operator, It multiplies right operand with the left C *= A is
operand and assign the result to left operand equivalent
to C = C *
A

/= Divide AND assignment operator, It divides left operand with the right operand C /= A is
and assign the result to left operand equivalent
to C = C /
A

%= Modulus AND assignment operator, It takes modulus using two operands and C %= A is
assign the result to left operand equivalent
to C = C %
A

<<= Left shift AND assignment operator C <<= 2 is


same as C
= C << 2

>>= Right shift AND assignment operator C >>= 2 is


same as C
= C >> 2

&= Bitwise AND assignment operator C &= 2 is


same as C
=C&2

^= bitwise exclusive OR and assignment operator C ^= 2 is


same as C
=C^2

|= bitwise inclusive OR and assignment operator C |= 2 is


same as C
=C|2

Page 114 of 228


Run the following code to understand the arithmetic operators better –

using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 21;
int c;
c = a;
Console.WriteLine("Line 1 - = Value of c = {0}", c);

c += a;
Console.WriteLine("Line 2 - += Value of c = {0}", c);

c -= a;
Console.WriteLine("Line 3 - -= Value of c = {0}", c);

c *= a;
Console.WriteLine("Line 4 - *= Value of c = {0}", c);

}
}
}

Miscellaneous Operators
There are few other important operators including sizeof, typeof and ? : supported by C#.

Operator Description Example

sizeof() Returns the size of a data type. sizeof(int), returns 4.

typeof() Returns the type of a class. typeof(StreamReader);

& Returns the address of an variable. &a; returns actual address of


the variable.

* Pointer to a variable. *a; creates pointer named 'a'


to a variable.

?: Conditional Expression If Condition is true ? Then


value X : Otherwise value Y

is Determines whether an object is of a certain type. If( Ford is Car) // checks if Ford
is an object of the Car class.

as Cast without raising an exception if the cast fails. Object obj = new
StringReader("Hello");
StringReader r = obj as
StringReader;

Page 115 of 228


Operator Precedence in C#

Operator precedence determines the grouping of terms in an expression. This affects


evaluation of an expression. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator.

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so the first evaluation takes place for 3*2 and then 7 is added into it.

Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators are
evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Null Operators
C# provides two operators to make it easier to work with nulls: the null-coalescing operator
and the null-conditional operator.

Null-Coalescing Operator

Page 116 of 228


The ?? operator is the null-coalescing operator. It says “If the operand is non-null, give it
to me; otherwise, give me a default value.” For example:
string s1 = null;
string s2 = s1 ?? "nothing"; // s2 evaluates to "nothing"

If the left-hand expression is non-null, the right-hand expression is never evaluated. The
null-coalescing operator also works with nullable value types.

Null-conditional operator (C# 6)


The ?. operator is the null-conditional or “Elvis” operator, and is new to C# 6. It

allows you to call methods and access members just like the standard dot operator,
except that if the operand on the left is null, the expression evaluates to null instead of
throwing a NullReferenceException:
System.Text.StringBuilder sb = null;
string s = sb?.ToString(); // No error; s instead evaluates to null

The last line is equivalent to:


string s = (sb == null ? null : sb.ToString());

Upon encountering a null, the Elvis operator short-circuits the remainder of


theexpression. In the following example, s evaluates to null, even with a standard dot
operator between ToString() and ToUpper():
System.Text.StringBuilder sb = null;
string s = sb?.ToString().ToUpper(); // s evaluates to null without
error

Statements
Functions comprise statements that execute sequentially in the textual order in which they
appear. A statement block is a series of statements appearing between braces (the {}
tokens).

Declaration Statements
A declaration statement declares a new variable, optionally initializing the variable with an
expression. A declaration statement ends in a semicolon. You may declare multiple variables
of the same type in a comma-separated list. For example:
string someWord = "rosebud";
int someNumber = 42;
bool rich = true, famous = false;

A constant declaration is like a variable declaration, except that it cannot be changed after it
has been declared, and the initialization must occur with the declaration
const double c = 2.99792458E08;
c += 10; // Compile-time Error

Expression Statements

Page 117 of 228


Expression statements are expressions that are also valid statements. An expression
statement must either change state or call something that might change state. Changing
state essentially means changing a variable. The possible expression statements are:

 Assignment expressions (including increment and decrement expressions)


 Method call expressions (both void and nonvoid)
 Object instantiation expressions

Here are some examples:


// Declare variables with declaration statements:
string s;
int x, y;
System.Text.StringBuilder sb;
// Expression statements
x = 1 + 2; // Assignment expression
x++; // Increment expression
y = Math.Max (x, 5); // Assignment expression
Console.WriteLine (y); // Method call expression
sb = new StringBuilder(); // Assignment expression
new StringBuilder(); // Object instantiation expression

Selection Statements
C# has the following mechanisms to conditionally control the flow of program execution:

 Selection statements (if, switch)


 Conditional operator (?:)
 Loop statements (while, do..while, for, foreach)

More of this will be discussed in the subsequent chapters.

Iteration Statements
C# enables a sequence of statements to execute repeatedly with the while, do-while, for,
and foreach statements

More of this will be discussed in the subsequent chapters.

Jump Statements
The C# jump statements are break, continue, goto, return, and throw.

More of this will be discussed in the subsequent chapters.

Interfaces
An interface is defined as a syntactical contract that all the classes inheriting the interface
should follow. The interface defines the 'what' part of the syntactical contract and the
deriving classes define the 'how' part of the syntactical contract.

Interfaces define properties, methods, and events, which are the members of the interface.
Interfaces contain only the declaration of the members. It is the responsibility of the
deriving class to define the members. It often helps in providing a standard structure that
the deriving classes would follow.

Page 118 of 228


Abstract classes to some extent serve the same purpose, however, they are mostly used
when only few methods are to be declared by the base class and the deriving class
implements the functionalities.

Declaring Interfaces
Interfaces are declared using the interface keyword. It is similar to class declaration.
Interface statements are public by default. Following is an example of an interface
declaration:
public interface ITransactions
{
// interface members
void showTransaction();
double getAmount();
}

Example
The following example demonstrates implementation of the above interface:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;

namespace InterfaceApplication
{
public interface ITransactions
{
// interface members
void showTransaction();
double getAmount();
}

public class Transaction : ITransactions


{
private string tCode;
private string date;
private double amount;
public Transaction()
{
tCode = " ";
date = " ";
amount = 0.0;
}

public Transaction(string c, string d, double a)


{
tCode = c;
date = d;
amount = a;
}

public double getAmount()


{
return amount;
}

public void showTransaction()


{

Page 119 of 228


Console.WriteLine("Transaction: {0}", tCode);
Console.WriteLine("Date: {0}", date);
Console.WriteLine("Amount: {0}", getAmount());
}
}
class Tester
{
static void Main(string[] args)
{
Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

Namespaces
A namespace is a domain for type names. Types are typically organized into hierarchical
namespaces, making them easier to find and avoiding conflicts. For example, the RSA type
that handles public key encryption is defined within the following namespace:
System.Security.Cryptography

The namespace keyword defines a namespace for types within that block. For example:
namespace Outer.Middle.Inner
{
class Class1 {}
class Class2 {}
}

The dots in the namespace indicate a hierarchy of nested namespaces. The code that
follows is semantically identical to the preceding example:
namespace Outer
{
namespace Middle
{
namespace Inner
{
class Class1 {}
class Class2 {}
}

Page 120 of 228


You can refer to a type with its fully qualified name, which includes all namespaces from the
outermost to the innermost. For example, we could refer to Class1 in the preceding
example as Outer.Middle.Inner.Class1.

The using Directive


The using directive imports a namespace, allowing you to refer to types without their fully
qualified names. The following imports the previous example’s Outer.Middle.Inner
namespace:
using Outer.Middle.Inner;
class Test
{
static void Main()
{
Class1 c; // Don't need fully qualified name
}
}

Let’s Start C# Graphical User Interface (GUI)


Until now you have been running your program in a console, whether it is the windows
command prompt or the visual studio console. It might have come to your mind that, “how
do we make nice looking applications like the ones we commonly see?” So, now in this
section we will discuss one of the techniques of making a C# GUI based application in Visual
Studio.

There are two popular ways of making powerful GUI based windows application. One being
Windows Presentation Foundation (WPF) and the other being Windows Forms. In this
course we will use Windows Forms. Let’s begin then!

Introduction to Windows Forms- a novel way of building a rich UI

With Windows Forms, you can create powerful Windows-based applications. The following
topics describe in-depth how to harness the power of Windows Forms to display data,
handle user input, and deploy your applications easily and with enhanced security.

In Windows Forms, a form is a visual surface on which you display information to the user.
You ordinarily build Windows Forms applications by adding controls to forms and
developing responses to user actions, such as mouse clicks or key presses. A control is a
discrete user interface (UI) element that displays data or accepts data input.

When a user does something to your form or one of its controls, the action generates an
event. Your application reacts to these events by using code, and processes the events
when they occur. We will see this along our course and lecture in which we will discuss
Event Handlers

Windows Forms contains a variety of controls that you can add to forms: controls that
display text boxes, buttons, drop-down boxes, radio buttons, and even Web pages. If an
existing control does not meet your needs, Windows Forms also supports creating your own
custom controls using the UserControl class.

Page 121 of 228


Windows Forms has rich UI controls that emulate features in high-end applications like
Microsoft Office. When you use the ToolStrip and MenuStrip control, you can create
toolbars and menus that contain text and images, display submenus, and host other
controls such as text boxes and combo boxes.

With the Visual Studio drag-and-drop Windows Forms Designer, you can easily create
Windows Forms applications. Just select the controls with your cursor and add them where
you want on the form. The designer provides tools such as gridlines and snap lines to take
the hassle out of aligning controls.

And whether you use Visual Studio or compile at the command line, you can use the
FlowLayoutPanel, TableLayoutPanel and SplitContainer controls to create advanced form
layouts in less time.

Finally, if you must create your own custom UI elements, the System.Drawing namespace
contains a large selection of classes to render lines, circles, and other shapes directly on a
form.

Windows Forms Coordinates


The coordinate system for a Windows Form is based on device coordinates, and the basic
unit of measure when drawing in Windows Forms is the device unit (typically, the pixel).
Points on the screen are described by x- and y-coordinate pairs, with the x-coordinates
increasing to the right and the y-coordinates increasing from top to bottom. The location of
the origin, relative to the screen, will vary depending on whether you are specifying screen
or client coordinates.

Screen Coordinates
A Windows Forms application specifies the position of a window on the screen in screen
coordinates. For screen coordinates, the origin is the upper-left corner of the screen.
The full position of a window is often described by a Rectangle structure containing the
screen coordinates of two points that define the upper-left and lower-right corners of
the window.

Client Coordinates
A Windows Forms application specifies the position of points in a form or control using
client coordinates. The origin for client coordinates is the upper-left corner of the client
area of the control or form. Client coordinates ensure that an application can use
consistent coordinate values while drawing in a form or control, regardless of the
position of the form or control on the screen.

The dimensions of the client area are also described by a Rectangle structure that
contains client coordinates for the area. In all cases, the upper-left coordinate of the
rectangle is included in the client area, while the lower-right coordinate is excluded.
Graphics operations do not include the right and lower edges of a client area. For
example the FillRectangle method will fill up to the right and lower edge of the specified
rectangle, but will not include these edges.

Mapping From One Type of Coordinate to Another


Occasionally, you may need to map from screen coordinates to client coordinates. You
can easily accomplish this by using the PointToClient and PointToScreen methods

Page 122 of 228


available in the Control class. For example, the MousePosition property of Control is
reported in screen coordinates, but you may want to convert these to client
coordinates.

Create a Windows Forms Application Project

To create a Windows Forms Application project

1. On the menu bar, choose File, New, Project. The dialog box should look like this –

2. Choose either Visual C# or Visual Basic in the Installed Templates list.

3. In the templates list, choose the Windows Forms Application icon. Name the new
form PictureViewer, and then choose the OK button.

4. Visual Studio creates a solution for your program. A solution acts as a container for
all of the projects and files needed by your program. These terms will be explained in
more detail later in this tutorial.

5. The following illustration shows what you should now see in the Visual Studio
interface.

a. Please note that your window layout may not look exactly like this
illustration. The precise window layout depends on the version of Visual
Studio, the programming language you are using, and other factors.
However, you should verify that all three windows appear.

Page 123 of 228


6. The illustration shows the following windows (going clockwise from the upper-left
corner):

a. Main window In this window, you'll do most of your work, such as working
with forms and editing code. In the illustration, the window shows a form in
the Form Editor. At the top of the window, the Start Page tab and the
Form1.cs [Design] tab appear.

b. Solution Explorer window In this window, you can view and navigate to all
items in your solution. If you choose a file, the contents of the Properties
window changes. If you open a code file (which ends in .cs in Visual C# and
.vb in Visual Basic), the code file or a designer for the code file appears. A
designer is a visual surface onto which you can add controls such as buttons
and lists. For Visual Studio forms, the designer is called the Windows Forms
Designer.

c. Properties window In this window, you can change the properties of items
that you choose in the other windows. For example, if you choose Form1,
you can change its title by setting the Text property, and you can change the
background color by setting the Backcolor property.

7. On the menu bar, choose File, Save All.

Run the code


When you created a new solution, you actually built a program that runs. It doesn't do much
yet—it just displays an empty window that shows Form1 in the title bar. But it does run, as
you're about to find out.

Page 124 of 228


To run your program
1. Use one of the following methods to run your program.

o Choose the F5 key.


o On the menu bar, choose Debug, Start Debugging.
o On the toolbar, choose the Start button
2. Visual Studio runs your program, and a window called Form1 appears. The following
diagram shows the program you just built. The program is running, and you will soon
add to it.

Set Your Form Properties


To set your form properties:

1. Be sure you're looking at Windows Forms Designer. In the Visual Studio integrated
development environment (IDE), choose the Form1.cs [Design] tab (or the Form1.vb
[Design] tab in Visual Basic).

2. Choose anywhere inside the form Form1 to select it. Look at the Properties window,
which should now be showing the properties for the form. Forms have various
properties. For example, you can set the foreground and background color, title text
that appears at the top of the form, size of the form, and other properties.

3. After the form is selected, find the Text property in the Properties window.
Depending on how the list is sorted, you might need to scroll down. Choose Text,
type Picture Viewer, and then choose ENTER. Your form should now have the text
Picture Viewer in its title bar, and the Properties window should look similar to the
following picture.

Page 125 of 228


4. Go back to Windows Forms Designer. Choose the form's lower-right drag handle,
which is the small white square in the lower-right of the form and appears as
follows. Drag the handle to resize the form so the form is wider and a bit taller.

5. Look at the Properties window, and notice that the Size property has changed. The
Size property changes each time you resize the form. Try dragging the form's handle
to resize it to a form size of approximately 550, 350 (no need to be exact), which
should work well for this project. As an alternative, you can enter the values directly
in the Size property and then choose the ENTER key.

Layout Your Form with a TableLayoutPanel Control


In this step, you add a TableLayoutPanel control to your form. The TableLayoutPanel helps
properly align controls in the form that you will add later.

To lay out your form with a TableLayoutPanel control:

1. On the left side of the Visual Studio IDE, locate the Toolbox tab. Choose the Toolbox
tab, and the Toolbox appears. (Or, on the menu bar, choose View, Toolbox.)

2. Choose the small triangle symbol next to the Containers group to open it, as shown
in the following picture.

Page 126 of 228


3. You can add controls like buttons, check boxes, and labels to your form. Double-click
the TableLayoutPanel control in the Toolbox. (Or, you can drag the control from the
toolbox onto the form.) When you do this, the IDE adds a TableLayoutPanel control
to your form, as shown in the following picture.

4. Be sure TableLayoutPanel is selected by choosing it. You can verify what control is
selected by looking at the drop-down list at the top of the Properties window, as
shown in the following picture.

Properties window showing TableLayoutPanel control


5. Choose the Alphabetical button on the toolbar in the Properties window. This causes
the list of properties in the Properties window to display in alphabetical order, which
will make it easier to locate properties in this tutorial.

6. The control selector is a drop-down list at the top of the Properties window. In this
example, it shows that a control called tableLayoutPanel1is selected. You can select

Page 127 of 228


controls either by choosing an area in Windows Forms Designer or by choosing from
the control selector. Now that TableLayoutPanel is selected, find the Dock property
and choose Dock, which should be set to None. Notice that a drop-down arrow
appears next to the value. Choose the arrow, and then select the Fill button (the
large button in the middle), as shown in the following picture.

Properties window with Fill selected

7. Docking in Visual Studio refers to when a window is attached to another window or


area in the IDE. For example, the Properties window can be undocked – that is,
unattached and free-floating within Visual Studio – or it can be docked
against Solution Explorer.

8. After you set the TableLayoutPanel Dock property to Fill, the panel fills the entire
form. If you resize the form again, the TableLayoutPanel stays docked, and resizes
itself to fit.

9. Currently, the TableLayoutPanel has two equal-size rows and two equal-size
columns. You need to resize them so the top row and right column are both much
bigger. In Windows Forms Designer, select the TableLayoutPanel. In the upper-right
corner, there is a small black triangle button, which appears as follows.

Triangle button

Page 128 of 228


This button indicates that the control has tasks that help you set its properties
automatically.

10. Choose the triangle to display the control's task list, as shown in the following
picture.

TableLayoutPanel tasks
11. Choose the Edit Rows and Columns task to display the Column and Row
Styles window. Choose Column1, and set its size to 15 percent by being sure
the Percent button is selected and entering 15 in the Percent box. (That's
a NumericUpDown control, which you will use in a later tutorial.)
Choose Column2 and set it to 85 percent. Don't choose the OK button yet, because
the window will close. (But if you do, you can reopen it using the task list.)

TableLayoutPanel column and row styles

12. From the Show drop-down list at the top of the window, choose Rows. Set Row1 to
90 percent and Row2 to 10 percent.

13. Choose the OK button. Your TableLayoutPanel should now have a large top row, a
small bottom row, a small left column, and a large right column. You can resize the
rows and columns in the TableLayoutPanel by choosing tableLayoutPanel1 in the
form and then dragging its row and column borders.

Page 129 of 228


Form1 with resized TableLayoutPanel

Add Controls to Your Form


In this step, you add controls, such as a PictureBox control and a CheckBox control, to your
form. You then add buttons to your form.

To add controls to your form


1. Go to the Toolbox tab (located on the left side of the Visual Studio IDE) and expand
the Common Controls group. This shows the most common controls that you see on
forms.
2. Choose the TableLayoutPanel control on the form. To verify that the
TableLayoutPanel is selected, make sure that its name appears in the dropdown list
box at the top of the Properties window. You can also choose form controls by using
the dropdown list box at the top of the Properties window. Choosing a control this
way can often be easier than choosing a tiny control with a mouse.
3. Double-click the PictureBox item to add a PictureBox control to your form. Because
the TableLayoutPanel is docked to fill your form, the IDE adds the PictureBox control
to the first empty cell (the upper left corner).
4. Choose the new PictureBox control to select it, and then choose the black triangle on
the new PictureBox control to display its task list, as shown in the following picture.

PictureBox tasks

5. Choose the Dock in parent container link. This automatically sets the
PictureBox Dock property to Fill. To see this, choose the PictureBox control to select
it, go to the Properties window, and be sure that the Dock property is set to Fill.
6. Make the PictureBox span both columns by changing its ColumnSpan property.
Choose the PictureBox control and set its ColumnSpan property to 2. Also, when the

Page 130 of 228


PictureBox is empty, you want to show an empty frame. Set its BorderStyle property
to Fixed3D.
7. Choose the TableLayoutPanel on the form and then add a CheckBox control to the
form. Double-click the CheckBox item in the Toolbox to add a new CheckBox control
to the next free cell in your table. Because a PictureBox takes up the first two cells in
the TableLayoutPanel, the CheckBox control is added to the lower-left cell. Choose
the Text property and type in the word Stretch, as shown in the following picture.

TextBox control with Stretch property


8. Choose the TableLayoutPanel on the form, and then go to the Containers group in
the Toolbox (where you got your TableLayoutPanel control) and double-click
the FlowLayoutPanel item to add a new control to the last cell in the PictureBox
(bottom right). Then dock the FlowLayoutPanel in the TableLayoutPanel (either by
choosing Dock in parent container on the FlowLayoutPanel's black triangle task list,
or by setting the FlowLayoutPanel's Dock property to Fill).

To add buttons
1. Choose the new FlowLayoutPanel that you added. Go to Common Controls in the
Toolbox and double-click the Button item to add a button control called button1 to
your FlowLayoutPanel. Repeat to add another button. The IDE determines that
there's already a button called button1 and calls the next one button2.
2. Typically, you add the other buttons using the Toolbox. This time, choose button2,
and then on the menu bar, choose Edit, Copy (or press Ctrl+C). On the menu bar,
choose Edit, Paste (or press Ctrl+V) to paste a copy of your button. Now paste it
again. The IDE has now added button3 and button4 to the FlowLayoutPanel.
3. Choose the first button and set its Text property to Show a picture. Then set
the Text properties of the next three buttons to Clear the picture, Set the
background color, and Close.
4. The next step is to size the buttons and arrange them so they align to the right side
of the panel. Choose the FlowLayoutPanel and look at its FlowDirection property.
Change it so it's set to RightToLeft. As soon as you do, the buttons should align
themselves to the right side of the cell, and reverse their order so that the Show a
picture button is on the right.
5. Choose the Close button to select it. Hold down the CTRL key and choose the other
three buttons, so that they are all selected. While all the buttons are selected, go to
the Properties window and scroll up to the AutoSize property. This property tells the

Page 131 of 228


button to automatically resize itself to fit all of its text. Set it to true. Your buttons
should now be sized properly and be in the right order. (As long as all four buttons
are selected, you can change all four AutoSize properties at the same time.) The
following picture shows the four buttons.

Picture Viewer with four buttons


6. Now run your program again to see your newly laid out form. Choosing the buttons
and the check box doesn't do anything yet, but it will work soon.

Add Dialog Components to Your Form


To enable your program to open picture files and choose a background color, in this step,
you add an OpenFileDialog component and a ColorDialog component to your form.

A component is like a control in some ways. You use the Toolbox to add a component to
your form, and you set its properties using the Properties window. But unlike a control,
adding a component to your form doesn't add a visible item that the user can see on the
form. Instead, it provides certain behaviors that you can trigger with code. It's a component
that opens an Open File dialog box

To add dialog components to your form

1. Choose the Windows Forms Designer (Form1.cs [Design] or Form1.vb [Design]) and
then open the Dialogs group in the Toolbox.

2. To add a component called openFileDialog1 to your form, double-


click OpenFileDialog. To add a component called colorDialog1 to your form, double-
click ColorDialog in the Toolbox. (You use that one in the next tutorial step.) You
should see an area at the bottom of Windows Forms Designer (beneath the Picture
Viewer form) that has an icon for each of the two dialog components that you added,
as shown in the following picture.

a.
Dialog components

b. Choose the openFileDialog1 icon in the area at the bottom of the Windows
Forms Designer. Set two properties:

c. Set the Filter property to the following (you can copy and paste it):

Page 132 of 228


d. JPEG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png|BMP Files (*.bmp)|*.bmp|All
files (*.*)|*.*

e. Set the Title property to the following: Select a picture file

f. The Filter property settings specify the kinds of file types that will display in
the Select a picture file dialog box.

Write Code for the Show a Picture Button Event Handler


In this step, you make the Show a picture button work like this:

 When a user chooses that button, the program opens an Open File dialog box.
 If a user opens a picture file, the program shows that picture in the PictureBox.

To write code for the Show a picture button event handler

1. Go to Windows Forms Designer and double-click the Show a picture button. The IDE
immediately goes to the code designer and moves your cursor so it's inside
the showButton_Click() method that you added previously.

2. Type an i on the empty line between the two braces { }. (In Visual Basic, type on the
empty line between Private Sub… and End Sub.) An IntelliSense window opens, as
shown in the following picture.

IntelliSense with Visual C# code

3. The IntelliSense window should be highlighting the word if. (If not, enter a
lowercase f, and it will.) Notice how a little tooltip box next to the IntelliSense window
appears with the description, Code snippet for if statement. (In Visual Basic, the
tooltip also states that this is a snippet, but with slightly different wording.) You want
to use that snippet, so choose the TAB key to insert if into your code. Then choose the

Page 133 of 228


TAB key again to use the if snippet. (If you chose somewhere else and
your IntelliSense window disappeared, backspace over the i and retype it, and
the IntelliSense window opens again.)

Visual C# code

4. Next, you use IntelliSense to enter more code to open an Open File dialog box. If the
user chose the OK button, the PictureBox loads the file that the user selected. The
following steps show how to enter the code, and although it's numerous steps, it's just
a few keystrokes:

a. Start with the selected text true in the snippet. Type op to overwrite it. (In
Visual Basic, you start with an initial cap, so type Op.)

b. The IntelliSense window opens and displays openFileDialog1. Choose the TAB
key to select it. (In Visual Basic, it starts with an initial cap, so you
see OpenFileDialog1. Ensure that OpenFileDialog1 is selected.)

c. To learn more about OpenFileDialog, see OpenFileDialog.

d. Type a period (.) (Many programmers call this a dot.) Because you typed a dot
right after openFileDialog1, an IntelliSense window opens, filled in with all of
the OpenFileDialog component's properties and methods. These are the same
properties that appear in the Properties window when you choose it in
Windows Forms Designer. You can also choose methods that tell the
component to do things (like open a dialog box).

Method icon

Property icon

Event icon

e. Start to type ShowDialog (capitalization is unimportant to IntelliSense).


The ShowDialog() method will show the Open File dialog box. After the
window has highlighted ShowDialog, choose the TAB key. You can also
highlight “ShowDialog” and choose the F1 key to get help for it.

Page 134 of 228


f. To learn more about the ShowDialog() method, see ShowDialog Method.

g. When you use a method on a control or a component (referred to as calling a


method), you need to add parentheses. So enter opening and closing
parentheses immediately after the "g" in ShowDialog: () It should now look like
"openFileDialog1.ShowDialog()".

h. For Visual C#, add a space, and then add two equal signs (==). For Visual Basic,
add a space, and then use a single equal sign (=). (Visual C# and Visual Basic
use different equality operators.)

i. Add another space. As soon as you do, another IntelliSense window opens.
Start to type DialogResult and choose the TAB key to add it.

j. Type a dot to open the DialogResult value IntelliSense window. Enter the
letter O and choose the TAB key to insert OK.

k. To learn more about DialogResult, see DialogResult.

l. Now add one more line of code. You can type it (or copy and paste it), but
consider using IntelliSense to add it. The more familiar you are with
IntelliSense, the more quickly you can write your own code. Your
final showButton_Click() method looks like the following.

private void showButton_Click(object sender, EventArgs e)


{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Load(openFileDialog1.FileName);
}
}

Page 135 of 228


Write Code for Additional Buttons and a Check Box
Now you're ready to complete the other four methods. You could copy and paste this code,
but if you want to learn the most from this tutorial, type the code and use IntelliSense.

This code adds functionality to the buttons you added earlier. Without this code, the
buttons don't do anything. The buttons use code in their Click events (and the check box
uses the CheckChanged event) to do different things when you activate the controls. For
example, the clearButton_Click event, which activates when you choose the Clear the
picture button, erases the current image by setting its Image property to null (or, nothing).
Each event in the code includes comments that explain what the code does.

private void clearButton_Click(object sender, EventArgs e)


{
// Clear the picture.
pictureBox1.Image = null;
}

private void backgroundButton_Click(object sender, EventArgs e)


{
// Show the color dialog box. If the user clicks OK, change the
// PictureBox control's background to the color the user chose.
if (colorDialog1.ShowDialog() == DialogResult.OK)
pictureBox1.BackColor = colorDialog1.Color;
}

private void closeButton_Click(object sender, EventArgs e)


{
// Close the form.
this.Close();
}

private void checkBox1_CheckedChanged(object sender, EventArgs e)


{
// If the user selects the Stretch check box,
// change the PictureBox's
// SizeMode property to "Stretch". If the user clears
// the check box, change it to "Normal".
if (checkBox1.Checked)
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
else
pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
}

Now you can run the code.

We have been creating and running program for some time now in this course. One
questions should be coming to your mind is – “how do we store data temporarily while
running a code?” To answer this question we will delve into the area of data structures in
the next chapter.

Page 136 of 228


5. Basic C# Data Structures
A data structure is an arrangement of data in a computer’s memory (or sometimes on a
disk). Data structures include arrays, linked lists, stacks, binary trees, and hash tables,
among others. Algorithms manipulate the data in these structures in various ways, such as
searching for a particular data item and sorting the data.

In the subsequent sub sections we will discuss the basic data structures.

Arrays
An array represents a fixed number of variables (called elements) of a particular type. The
elements in an array are always stored in a contiguous block of memory, providing highly
efficient access.

An array is denoted with square brackets after the element type. For example:
char[] vowels = new char[5]; // Declare an array of 5 characters

Square brackets also index the array, accessing a particular element by position:

vowels[0] = 'a';
vowels[1] = 'e';
vowels[2] = 'i';
vowels[3] = 'o';
vowels[4] = 'u';
Console.WriteLine (vowels[1]); // e

This prints “e” because array indexes start at 0. We can use a for loop statement to iterate
through each element in the array. The for loop in this example cycles the integer i from 0 to
4:

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


Console.Write (vowels[i]); // aeiou

The Length property of an array returns the number of elements in the array. Once an array
has been created, its length cannot be changed. The System.Collection namespace and
subnamespaces provide higher-level data structures, such as dynamically sized arrays and
dictionaries.

An array initialization expression lets you declare and populate an array in a single step:

char[] vowels = new char[] {'a','e','i','o','u'};

or simply:

char[] vowels = {'a','e','i','o','u'};

All arrays inherit from the System.Array class, providing common services for all arrays.
These members include methods to get and set elements regardless of the array type. The
figure below gives graphical representation of arrays in memory.

Page 137 of 228


Default Element Initialization
Creating an array always preinitializes the elements with default values. The default value for a type
is the result of a bitwise zeroing of memory. For example, consider creating an array of integers. Since
int is a value type, this allocates 1,000 integers in one contiguous block of memory. The default value
for each element will be 0:

int[] a = new int[1000];


Console.Write (a[123]); // 0

Value types versus reference types


Whether an array element type is a value type or a reference type has important performance
implications. When the element type is a value type, each element value is allocated as part of the
array. For example:

public struct Point { public int X, Y; }


...
Point[] a = new Point[1000];
int x = a[500].X; // 0

Had Point been a class, creating the array would have merely allocated 1,000 null
references:

public class Point { public int X, Y; }


...
Point[] a = new Point[1000];
int x = a[500].X; // Runtime error, NullReferenceException

To avoid this error, we must explicitly instantiate 1,000 Points after instantiating the array:

Point[] a = new Point[1000];


for (int i = 0; i < a.Length; i++) // Iterate i from 0 to 999
a[i] = new Point(); // Set array element i with new point

An array itself is always a reference type object, regardless of the element type. For instance, the
following is legal:

int[] a = null;

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element
within square brackets after the name of the array. For example,

Page 138 of 228


double salary = balance[9];

The following example, demonstrates the above-mentioned concepts declaration, assignment, and
accessing arrays:

using System;
namespace ArrayApplication
{
class MyArray
{
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();
}
}
}

In the previous example, we used a for loop for accessing each array element. You can also use a
foreach statement to iterate through an array. More examples and details about for and foreach will
be discussed when we discuss control statements.

Page 139 of 228


using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n is an array of 10 integers */

/* initialize elements of array n */


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

/* output each array element's value */


foreach (int j in n )
{
int i = j-100;
Console.WriteLine("Element[{0}] = {1}", i, j);

}
Console.ReadKey();
}
}
}

Multidimensional Arrays

Multidimensional arrays come in two varieties: rectangular and jagged. Rectangular arrays represent
an n-dimensional block of memory, and jagged arrays are arrays of arrays.

Rectangular arrays

Rectangular arrays are declared using commas to separate each dimension. The following declares a
rectangular two-dimensional array, where the dimensions are
3 x 3:

int[,] matrix = new int[3,3];

The GetLength method of an array returns the length for a given dimension (starting at 0):

for (int i = 0; i < matrix.GetLength(0); i++)

Page 140 of 228


for (int j = 0; j < matrix.GetLength(1); j++)
matrix[i,j] = i * 3 + j;

A rectangular array can be initialized as follows (to create an array identical to the
previous example):
int[,] matrix = new int[,]
{
{0,1,2},
{3,4,5},
{6,7,8}
}

Jagged arrays

Jagged arrays are declared using successive square brackets to represent each
dimension. Here is an example of declaring a jagged two-dimensional array, where
the outermost dimension is 3:

int[][] matrix = new int[3][];

Interestingly, this is new int[3][] and not new int[][3].The inner dimensions aren’t specified in the
declaration because, unlike a rectangular array, each inner array can be an arbitrary length. Each inner
array is implicitly initialized to null rather than an empty array. Each inner array must be created
manually:

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


{
matrix[i] = new int[3]; // Create inner array
for (int j = 0; j < matrix[i].Length; j++)
matrix[i][j] = i * 3 + j;
}

A jagged array can be initialized as follows (to create an array identical to the previous example with
an additional element at the end):

int[][] matrix = new int[][]


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

5.2 C# - Array Class


The Array class is the base class for all the arrays in C#. It is defined in the System namespace. The
Array class provides various properties and methods to work with arrays.

Page 141 of 228


Properties of the Array Class

The following table describes some of the most commonly used properties of the Array class:

<Table no.>
Sr.No Property

1 IsFixedSize
Gets a value indicating whether the Array has a fixed size.

2 IsReadOnly
Gets a value indicating whether the Array is read-only.

3 Length
Gets a 32-bit integer that represents the total number of elements in all the dimensions
of the Array.

4 LongLength
Gets a 64-bit integer that represents the total number of elements in all the dimensions
of the Array.

5 Rank
Gets the rank (number of dimensions) of the Array.

Methods of the Array Class

The following table describes some of the most commonly used methods of the Array class:

<Table no.>
Sr.No Methods

1 Clear
Sets a range of elements in the Array to zero, to false, or to null, depending on the
element type.

2 Copy(Array, Array, Int32)


Copies a range of elements from an Array starting at the first element and pastes them
into another Array starting at the first element. The length is specified as a 32-bit integer.

3 CopyTo(Array, Int32)
Copies all the elements of the current one-dimensional Array to the specified one-
dimensional Array starting at the specified destination Array index. The index is specified
as a 32-bit integer.

4 GetLength
Gets a 32-bit integer that represents the number of elements in the specified dimension
of the Array.

5 GetLongLength

Page 142 of 228


Gets a 64-bit integer that represents the number of elements in the specified dimension
of the Array.

6 GetLowerBound
Gets the lower bound of the specified dimension in the Array.

7 GetType
Gets the Type of the current instance. (Inherited from Object.)

8 GetUpperBound
Gets the upper bound of the specified dimension in the Array.

9 GetValue(Int32)
Gets the value at the specified position in the one-dimensional Array. The index is
specified as a 32-bit integer.

10 IndexOf(Array, Object)
Searches for the specified object and returns the index of the first occurrence within the
entire one-dimensional Array.

11 Reverse(Array)
Reverses the sequence of the elements in the entire one-dimensional Array.

12 SetValue(Object, Int32)
Sets a value to the element at the specified position in the one-dimensional Array. The
index is specified as a 32-bit integer.

13 Sort(Array)
Sorts the elements in an entire one-dimensional Array using the IComparable
implementation of each element of the Array.

14 ToStringk
Returns a string that represents the current object. (Inherited from Object.)

For complete list of Array class properties and methods, please consult Microsoft
documentation on C#.

ArrayList
The ArrayList maintains an internal object array and provides automatic resizing of the array
as the number of elements added to the ArrayList grows. Because the ArrayList uses an
object array, developers can add any type—strings,
integers, FileInfo objects, Form instances, anything.

While the ArrayList provides added flexibility over the standard array, this flexibility comes
at the cost of performance. Because the ArrayList stores an array of objects, when reading
the value from an ArrayList you need to explicitly cast it to the data type being stored in the
specified location. Recall that an array of a value type—such as

Page 143 of 228


a System.Int32, System.Double, System.Boolean, and so on—is stored contiguously in the
managed heap in its unboxed form. The ArrayList's internal array, however, is an array
of object references. Therefore, even if you have an ArrayList that stores nothing but value
types.

Methods and Properties of ArrayList Class

The following table lists some of the commonly used properties of the ArrayList class:

<table>
Property Description

Capacity Gets or sets the number of elements that the ArrayList can contain.

Count Gets the number of elements actually contained in the ArrayList.

IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.

IsReadOnly Gets a value indicating whether the ArrayList is read-only.

Item Gets or sets the element at the specified index.

The following table lists some of the commonly used methods of the ArrayList class:

Sr.No. Methods

1 public virtual int Add(object value);


Adds an object to the end of the ArrayList.

2 public virtual void AddRange(ICollection c);


Adds the elements of an ICollection to the end of the ArrayList.

3 public virtual void Clear();


Removes all elements from the ArrayList.

4 public virtual bool Contains(object item);


Determines whether an element is in the ArrayList.

5 public virtual ArrayList GetRange(int index, int count);


Returns an ArrayList which represents a subset of the elements in the source ArrayList.

6 public virtual int IndexOf(object);


Returns the zero-based index of the first occurrence of a value in the ArrayList or in a
portion of it.

7 public virtual void Insert(int index, object value);

Page 144 of 228


Inserts an element into the ArrayList at the specified index.

8 public virtual void InsertRange(int index, ICollection c);


Inserts the elements of a collection into the ArrayList at the specified index.

9 public virtual void Remove(object obj);


Removes the first occurrence of a specific object from the ArrayList.

10 public virtual void RemoveAt(int index);


Removes the element at the specified index of the ArrayList.

11 public virtual void RemoveRange(int index, int count);


Removes a range of elements from the ArrayList.

12 public virtual void Reverse();


Reverses the order of the elements in the ArrayList.

13 public virtual void SetRange(int index, ICollection c);


Copies the elements of a collection over a range of elements in the ArrayList.

14 public virtual void Sort();


Sorts the elements in the ArrayList.

15 public virtual void TrimToSize();


Sets the capacity to the actual number of elements in the ArrayList.

Structures
In C#, a structure is a value type data type. It helps you to make a single variable hold
related data of various data types. The struct keyword is used for creating a structure.

Structures are used to represent a record. Suppose you want to keep track of your books in
a library. You might want to track the following attributes about each book:

 Title
 Author
 Subject
 Book ID

Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a
new data type, with more than one member for your program.

For example, here is the way you can declare the Book structure:

struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};

Page 145 of 228


The following program shows the use of the structure:
using System;
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};

public class testStructure


{
public static void Main(string[] args)
{

Books Book1; /* Declare Book1 of type Book */


Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;

/* book 2 specification */
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700;

/* print Book1 info */


Console.WriteLine( "Book 1 title : {0}", Book1.title);
Console.WriteLine("Book 1 author : {0}", Book1.author);
Console.WriteLine("Book 1 subject : {0}", Book1.subject);
Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);

/* print Book2 info */


Console.WriteLine("Book 2 title : {0}", Book2.title);
Console.WriteLine("Book 2 author : {0}", Book2.author);
Console.WriteLine("Book 2 subject : {0}", Book2.subject);
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);

Console.ReadKey();

}
}

When the above code is compiled and executed, it produces the following result:
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

Page 146 of 228


Features of C# Structures
You have already used a simple structure named Books. Structures in C# are quite different
from that in traditional C or C++. The C# structures have the following features:

 Structures can have methods, fields, indexers, properties, operator methods, and
events.
 Structures can have defined constructors, but not destructors. However, you cannot
define a default constructor for a structure. The default constructor is automatically
defined and cannot be changed.
 Unlike classes, structures cannot inherit other structures or classes.
 Structures cannot be used as a base for other structures or classes.
 A structure can implement one or more interfaces.
 Structure members cannot be specified as abstract, virtual, or protected.
 When you create a struct object using the New operator, it gets created and the
appropriate constructor is called. Unlike classes, structs can be instantiated without
using the New operator.
 If the New operator is not used, the fields remain unassigned and the object cannot
be used until all the fields are initialized.

Page 147 of 228


6. Selection Control in C#
Decision making structures requires the programmer to specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition
is determined to be false.

C# provides following types of decision making statements. Click the following links to check their
detail.

<Table no.>
Statement Description

if statement An if statement consists of a boolean expression followed by


one or more statements.

if...else statement An if statement can be followed by an optional else statement,


which executes when the boolean expression is false.

nested if statements You can use one if or else if statement inside another if or else
if statement(s).

switch statement A switch statement allows a variable to be tested for equality


against a list of values.

nested switch statements You can use one switch statement inside
another switch statement(s).

if and if …else and nested if else

The if statement

An if statement executes a statement if a bool expression is true. For example:

if (5 < 2 * 3)
Console.WriteLine ("true"); // true

The statement can be a code block:

if (5 < 2 * 3)
{
Console.WriteLine ("true");
Console.WriteLine ("Let's move on!");
}
The else clause

An if statement can optionally feature an else clause:

if (2 + 2 == 5)

Page 148 of 228


Console.WriteLine ("Does not compute");
else
Console.WriteLine ("False"); // False

Within an else clause, you can nest another if statement:

if (2 + 2 == 5)
Console.WriteLine ("Does not compute");
else
if (2 + 2 == 4)
Console.WriteLine ("Computes"); // Computes

Changing the flow of execution with braces

An else clause always applies to the immediately preceding if statement in the


statement block. For example:

if (true)
if (false)
Console.WriteLine();
else
Console.WriteLine ("executes");

This is semantically identical to:

if (true)
{
if (false)
Console.WriteLine();
else
Console.WriteLine ("executes");
}

We can change the execution flow by moving the braces:

if (true)
{
if (false)
Console.WriteLine();
}
else
Console.WriteLine ("does not execute");

With braces, you explicitly state your intention. This can improve the readability of nested if
statements—even when not required by the compiler. A notable exception is with the following
pattern:
static void TellMeWhatICanDo (int age)
{
if (age >= 35)
Console.WriteLine ("You can be president!");
else if (age >= 21)

Page 149 of 228


Console.WriteLine ("You can drink!");
else if (age >= 18)
Console.WriteLine ("You can vote!");
else
Console.WriteLine ("You can wait!");
}

Here, we’ve arranged the if and else statements to mimic the “elseif ” construct of other languages
(and C#’s #elif preprocessor directive). Visual Studio’s autoformatting recognizes this pattern and
preserves the indentation. Semantically, though, each if statement following an else statement is
functionally nested within the else clause.

The switch statement

switch statements let you branch program execution based on a selection of possible values that a
variable may have. switch statements may result in cleaner code than multiple if statements, since
switch statements require an expression to be evaluated only once. For instance:

static void ShowCard(int cardNumber)


{
switch (cardNumber)
{
case 13:
Console.WriteLine ("King");
break;
case 12:
Console.WriteLine ("Queen");
break;
case 11:
Console.WriteLine ("Jack");
break;
case -1: // Joker is -1
goto case 12; // In this game joker counts as queen
default: // Executes for any other cardNumber
Console.WriteLine (cardNumber);
break;
}
}

You can only switch on an expression of a type that can be statically evaluated,
which restricts it to the built-in integral types, bool, and enum types and string type.
At the end of each case clause, you must say explicitly where execution is to go next, with some kind
of jump statement. Here are the options:

• break (jumps to the end of the switch statement)


• goto case x (jumps to another case clause)
• goto default (jumps to the default clause)
• Any other jump statement—namely, return, throw, continue, or goto label

Page 150 of 228


When more than one value should execute the same code, you can list the common cases
sequentially:

switch (cardNumber)
{
case 13:
case 12:
case 11:
Console.WriteLine ("Face card");
break;
default:
Console.WriteLine ("Plain card");
break;
}

This feature of a switch statement can be pivotal in terms of producing cleaner


code than multiple if-else statements.

Page 151 of 228


7. Implementing iteration in C#

There may be a situation, when you need to execute a block of code several number of times. In
general, the statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution
paths.
A loop statement allows us to execute a statement or a group of statements multiple times

C# provides following types of loop to handle looping requirements. Click the following links to check
their detail.

<table no.>
Loop Type Description

while loop It repeats a statement or a group of statements while a given condition


is true. It tests the condition before executing the loop body.

for loop It executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.

foreach loop This iterates over each element in an enumerable object

do...while loop It is similar to a while statement, except that it tests the condition at the
end of the loop body

nested loops You can use one or more loop inside any another while, for or do..while
loop.

while and do-while loops


while loops repeatedly execute a body of code while a bool expression is true. The expression is tested
before the body of the loop is executed. For example:

int i = 0;
while (i < 3)
{
Console.WriteLine (i);
i++;
}

OUTPUT:
012

do-while loops differ in functionality from while loops only in that they test the
expression after the statement block has executed (ensuring that the block is always executed at least
once). Here’s the preceding example rewritten with a do-while loop:

Page 152 of 228


int i = 0;
do
{
Console.WriteLine (i);
i++;
}
while (i < 3);

for loops
for loops are like while loops with special clauses for initialization and iteration of a loop variable. A
for loop contains three clauses as follows:

for (initialization-clause; condition-clause; iteration-clause)


statement-or-statement-block

Initialization clause

Executed before the loop begins; used to initialize one or more iteration variables

Condition clause

The bool expression that, while true, will execute the body

Iteration clause

Executed after each iteration of the statement block; used typically to update the iteration variable.
For example, the following prints the numbers 0 through 2:

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


Console.WriteLine (i);

The following prints the first 10 Fibonacci numbers (where each number is the sum of the previous
two):

for (int i = 0, prevFib = 1, curFib = 1; i < 10; i++)


{
Console.WriteLine (prevFib);
int newFib = prevFib + curFib;
prevFib = curFib; curFib = newFib;
}

Any of the three parts of the for statement may be omitted. One can implement an infinite loop such
as the following (though while(true) may be used instead):

for (;;)
Console.WriteLine ("interrupt me");

Page 153 of 228


foreach loops
The foreach statement iterates over each element in an enumerable object. Most of the types in C#
and the .NET Framework that represent a set or list of elements are enumerable. For example, both
an array and a string are enumerable. Here is an example of enumerating over the characters in a
string, from the first character
through to the last:

foreach (char c in "cool") // c is the iteration variable


Console.WriteLine (c);

OUTPUT:
c
o
o
l

Loop Control Statements (aka Jump Statements)


Loop control statements change execution from its normal sequence. When execution leaves a scope,
all automatic objects that were created in that scope are destroyed.
The C# jump statements are break, continue, goto, return, and throw. Jump statements obey the
reliability rules of try statements.This means that:

• A jump out of a try block always executes the try’s finally block before reaching the target of the
jump.
• A jump cannot be made from the inside to the outside of a finally block (except via throw).

The break statement

The break statement ends the execution of the body of an iteration or switch
statement:

int x = 0;
while (true)
{
if (x++ > 5)
break ; // break from the loop
}
// execution continues here after break
...

The continue statement

The continue statement forgoes the remaining statements in a loop and makes an
early start on the next iteration. The following loop skips even numbers:

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


{
if ((i % 2) == 0) // If i is even,
continue; // continue with next iteration

Page 154 of 228


Console.Write (i + " ");
}

OUTPUT: 1 3 5 7 9

The goto statement

The goto statement transfers execution to another label within a statement block.
The form is as follows:

goto statement-label;

Or, when used within a switch statement:

goto case case-constant;

A label is a placeholder in a code block that precedes a statement, denoted with a colon suffix. The
following iterates the numbers 1 through 5, mimicking a for loop:

int i = 1;
startLoop:
if (i <= 5)
{
Console.Write (i + " ");
i++;
goto startLoop;
}

OUTPUT: 1 2 3 4 5

The goto case case-constant transfers execution to another case in a switch


block.

The return statement

The return statement exits the method and must return an expression of the method’s return type if
the method is nonvoid:

static decimal AsPercentage (decimal d)


{
decimal p = d * 100m;
return p; // Return to the calling method with value
}

Page 155 of 228


A return statement can appear anywhere in a method (except in a finally block).

The throw statement

The throw statement throws an exception to indicate an error has occurred

if (w == null)
throw new ArgumentNullException (...);

Page 156 of 228


8. 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.
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
o Fully accessible. This is the implicit accessibility for members of an enum
or interface.
 Private
o Accessible only within the containing type. This is the default accessibility for members of
a class or struct.
 Protected
o Accessible only within the containing type or subclasses.
 Internal
o Accessible only within the containing assembly or friend assemblies. This is the default
accessibility for non-nested types.
 Protected internal
o The union of protected and internal accessibility. Eric Lippert explains it
as follows: Everything is as private as possible by default, and each modifier makes the
thing more accessible. So something that is protected internal is made more accessible in
two ways.

Examples

Class2 is accessible from outside its assembly; Class1 is not:

class Class1 {} // Class1 is internal (default)


public class Class2 {}

ClassB exposes field x to other types in the same assembly; ClassA does not:

class ClassA { int x; } // x is private (default)


class ClassB { internal int x; }

Functions within Subclass can call Bar but not Foo:

class BaseClass
{
void Foo() {} // Foo is private (default)
protected void Bar() {}
}

class Subclass : BaseClass


{

Page 157 of 228


void Test1() { Foo(); } // Error - cannot access Foo
void Test2() { Bar(); } // OK
}

Page 158 of 228


9. Methods
A method is a group of statements that together perform a task. A method performs an action in a
series of statements. A method can receive input data from the caller by specifying parameters and
output data back to the caller by specifying a return type. A method can specify a void return type,
indicating that it doesn’t return any value to its caller. A method can also output data back to the caller
via ref/out parameters.
A method’s signature must be unique within the type. A method’s signature comprises its name and
parameter types (but not the parameter names, nor the return type)
Every C# program has at least one class with a method named Main.
Methods allow the following modifiers:

 Static modifier - static


 Access modifiers- public, internal, private, protected
 Inheritance modifiers- new, virtual abstract, override, sealed
 Partial method modifier - partial
 Unmanaged code modifiers - unsafe extern
 Asynchronous code modifier - async

To use a method, you need to:

 Define the method


 Call the method

Defining Methods in C#
When you define a method, you basically declare the elements of its structure. The syntax for defining
a method in C# is as follows:

<Access Specifier> <Return Type> <Method Name>(Parameter List)

Method Body

Following are the various elements of a method:

 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.

Page 159 of 228


Example

Following code snippet shows a method FindMax that takes two integer values and returns the larger
of the two. It has public access specifier, so it can be accessed from outside the class using an instance
of the class.

class NumberManipulator

public int FindMax(int num1, int num2)

/* local variable declaration */

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

...

Calling Methods in C#

You can call a method using the name of the method. The following example illustrates this:

using System;

namespace CalculatorApplication

Page 160 of 228


class NumberManipulator

public int FindMax(int num1, int num2)

/* local variable declaration */

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

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();

Page 161 of 228


}

When the above code is compiled and executed, it produces the following result:

Max value is : 200

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.

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;

class Test

Page 162 of 228


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();

When the above code is compiled and executed, it produces the following result:

Max value is : 200

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:

using System;

namespace CalculatorApplication

class NumberManipulator

public int factorial(int num)

Page 163 of 228


{

/* 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

Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));

Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));

Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));

Console.ReadLine();

When the above code is compiled and executed, it produces the following result:

Factorial of 6 is: 720


Factorial of 7 is: 5040

Page 164 of 228


Factorial of 8 is: 40320

Passing Parameters to a Method

When method with parameters is called, you need to pass the parameters to the method. There are
three ways that parameters can be passed to a method:

<table no.>
Mechanism Description

Value parameters This method copies the actual value of an argument into
the formal parameter of the function. In this case,
changes made to the parameter inside the function have
no effect on the argument.

Reference parameters This method copies the reference to the memory


location of an argument into the formal parameter. This
means that changes made to the parameter affect the
argument.

Output parameters This method helps in returning more than one value.

Passing Parameters by Value

This is the default mechanism for passing parameters to a method. In this mechanism, when
a method is called, a new storage location is created for each value parameter.
The values of the actual parameters are copied into them. Hence, the changes made to the
parameter inside the method have no effect on the argument. The following example
demonstrates the concept:

using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(int x, int y)
{
int temp;

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put temp into y */
}

static void Main(string[] args)


{
NumberManipulator n = new NumberManipulator();
/* local variable definition */

Page 165 of 228


int a = 100;
int b = 200;

Console.WriteLine("Before swap, value of a : {0}", a);


Console.WriteLine("Before swap, value of b : {0}", b);

/* calling a function to swap the values */


n.swap(a, b);

Console.WriteLine("After swap, value of a : {0}", a);


Console.WriteLine("After swap, value of b : {0}", b);

Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there is no change in the values though they had changed inside the function.
Passing Parameters by Reference
A reference parameter is a reference to a memory location of a variable. When you pass parameters
by reference, unlike value parameters, a new storage location is not created for these parameters.
The reference parameters represent the same memory location as the actual parameters that are
supplied to the method.
You can declare the reference parameters using the ref keyword. The following example
demonstrates this:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(ref int x, ref int y)
{
int temp;

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put temp into y */
}

static void Main(string[] args)


{
NumberManipulator n = new NumberManipulator();

/* local variable definition */


int a = 100;
int b = 200;

Page 166 of 228


Console.WriteLine("Before swap, value of a : {0}", a);
Console.WriteLine("Before swap, value of b : {0}", b);

/* calling a function to swap the values */


n.swap(ref a, ref b);

Console.WriteLine("After swap, value of a : {0}", a);


Console.WriteLine("After swap, value of b : {0}", b);

Console.ReadLine();

}
}
}
When the above code is compiled and executed, it produces the following result:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100
It shows that the values have changed inside the swap function and this change reflects in
the Main function.
Passing Parameters by Output
A return statement can be used for returning only one value from a function. However,
using output parameters, you can return two values from a function. Output parameters are
similar to reference parameters, except that they transfer data out of the method rather than
into it.
The following example illustrates this:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void getValue(out int x )
{
int temp = 5;
x = temp;
}

static void Main(string[] args)


{
NumberManipulator n = new NumberManipulator();

/* local variable definition */


int a = 100;

Console.WriteLine("Before method call, value of a : {0}", a);

/* calling a function to get the value */


n.getValue(out a);

Page 167 of 228


Console.WriteLine("After method call, value of a : {0}", a);
Console.ReadLine();

}
}
}
When the above code is compiled and executed, it produces the following result:
Before method call, value of a : 100
After method call, value of a : 5
The variable supplied for the output parameter need not be assigned a value. Output parameters are
particularly useful when you need to return values from a method through the parameters without
assigning an initial value to the parameter. Go through the following example, to understand this:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void getValues(out int x, out int y )
{
Console.WriteLine("Enter the first value: ");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second value: ");
y = Convert.ToInt32(Console.ReadLine());
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();

/* local variable definition */


int a , b;

/* calling a function to get the values */


n.getValues(out a, out b);

Console.WriteLine("After method call, value of a : {0}", a);


Console.WriteLine("After method call, value of b : {0}", b);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Enter the first value:
7
Enter the second value:
8
After method call, value of a : 7
After method call, value of b : 8

Page 168 of 228


10. Classes

When you define a class, you define a blueprint for a data type. This does not actually define any
data, but it does define what the class name means. That is, what an object of the class consists
of and what operations can be performed on that object. Objects are instances of a class. The
methods and variables that constitute a class are called members of the class.
Defining a Class
A class definition starts with the keyword class followed by the class name; and the class body
enclosed by a pair of curly braces. Following is the general form of a class definition:

<access specifier> class class_name

// member variables

<access specifier> <data type> variable1;

<access specifier> <data type> variable2;

...

<access specifier> <data type> variableN;

// member methods

<access specifier> <return type> method1(parameter_list)

// method body

<access specifier> <return type> method2(parameter_list)

// method body

...

<access specifier> <return type> methodN(parameter_list)

// method body

Page 169 of 228


}

Note:

 Access specifiers specify the access rules for the members as well as the class itself. If not
mentioned, then the default access specifier for a class type is internal. Default access for the
members is private.

 Data type specifies the type of variable, and return type specifies the data type of the data the
method returns, if any.

 To access the class members, you use the dot (.) operator.

 The dot operator links the name of an object with the name of a member.

The following example illustrates the concepts discussed so far:

using System;

namespace BoxApplication

class Box

public double length; // Length of a box

public double breadth; // Breadth of a box

public double height; // Height of a box

class Boxtester

static void Main(string[] args)

Box Box1 = new Box(); // Declare Box1 of type Box

Box Box2 = new Box(); // Declare Box2 of type Box

double volume = 0.0; // Store the volume of a box here

// box 1 specification

Page 170 of 228


Box1.height = 5.0;

Box1.length = 6.0;

Box1.breadth = 7.0;

// box 2 specification

Box2.height = 10.0;

Box2.length = 12.0;

Box2.breadth = 13.0;

// volume of box 1

volume = Box1.height * Box1.length * Box1.breadth;

Console.WriteLine("Volume of Box1 : {0}", volume);

// volume of box 2

volume = Box2.height * Box2.length * Box2.breadth;

Console.WriteLine("Volume of Box2 : {0}", volume);

Console.ReadKey();

When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Member Functions and Encapsulation
A member function of a class is a function that has its definition or its prototype within the class
definition similar to any other variable. It operates on any object of the class of which it is a
member, and has access to all the members of a class for that object.
Member variables are the attributes of an object (from design perspective) and they are kept
private to implement encapsulation. These variables can only be accessed using the public
member functions.
Let us put above concepts to set and get the value of different class members in a class:

using System;

Page 171 of 228


namespace BoxApplication

class Box

private double length; // Length of a box

private double breadth; // Breadth of a box

private double height; // Height of a box

public void setLength( double len )

length = len;

public void setBreadth( double bre )

breadth = bre;

public void setHeight( double hei )

height = hei;

public double getVolume()

return length * breadth * height;

class Boxtester

Page 172 of 228


{

static void Main(string[] args)

Box Box1 = new Box(); // Declare Box1 of type Box

Box Box2 = new Box();

double volume;

// Declare Box2 of type Box

// box 1 specification

Box1.setLength(6.0);

Box1.setBreadth(7.0);

Box1.setHeight(5.0);

// box 2 specification

Box2.setLength(12.0);

Box2.setBreadth(13.0);

Box2.setHeight(10.0);

// volume of box 1

volume = Box1.getVolume();

Console.WriteLine("Volume of Box1 : {0}" ,volume);

// volume of box 2

volume = Box2.getVolume();

Console.WriteLine("Volume of Box2 : {0}", volume);

Console.ReadKey();

Page 173 of 228


}

When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
C# Constructors
A class constructor is a special member function of a class that is executed whenever we create
new objects of that class.
A constructor has exactly the same name as that of class and it does not have any return type.
Following example explains the concept of constructor:

using System;

namespace LineApplication

class Line

private double length; // Length of a line

public Line()

Console.WriteLine("Object is being created");

public void setLength( double len )

length = len;

public double getLength()

return length;

Page 174 of 228


}

static void Main(string[] args)

Line line = new Line();

// set line length

line.setLength(6.0);

Console.WriteLine("Length of line : {0}", line.getLength());

Console.ReadKey();

When the above code is compiled and executed, it produces the following result:
Object is being created
Length of line : 6
A default constructor does not have any parameter but if you need, a constructor can have
parameters. Such constructors are called parameterized constructors. This technique helps you
to assign initial value to an object at the time of its creation as shown in the following example:

using System;

namespace LineApplication

class Line

private double length; // Length of a line

public Line(double len) //Parameterized constructor

Console.WriteLine("Object is being created, length = {0}", len);

length = len;

Page 175 of 228


}

public void setLength( double len )

length = len;

public double getLength()

return length;

static void Main(string[] args)

Line line = new Line(10.0);

Console.WriteLine("Length of line : {0}", line.getLength());

// set line length

line.setLength(6.0);

Console.WriteLine("Length of line : {0}", line.getLength());

Console.ReadKey();

When the above code is compiled and executed, it produces the following result:
Object is being created, length = 10
Length of line : 10
Length of line : 6

Page 176 of 228


C# Destructors
A destructor is a special member function of a class that is executed whenever an object of its
class goes out of scope. A destructor has exactly the same name as that of the class with a
prefixed tilde (~) and it can neither return a value nor can it take any parameters.
Destructor can be very useful for releasing memory resources before exiting the program.
Destructors cannot be inherited or overloaded.
Following example explains the concept of destructor:

using System;

namespace LineApplication

class Line

private double length; // Length of a line

public Line() // constructor

Console.WriteLine("Object is being created");

~Line() //destructor

Console.WriteLine("Object is being deleted");

public void setLength( double len )

length = len;

public double getLength()

return length;

Page 177 of 228


}

static void Main(string[] args)

Line line = new Line();

// set line length

line.setLength(6.0);

Console.WriteLine("Length of line : {0}", line.getLength());

When the above code is compiled and executed, it produces the following result:
Object is being created
Length of line : 6
Object is being deleted

Static Members of a C# Class


We can define class members as static using the static keyword. When we declare a member of
a class as static, it means no matter how many objects of the class are created, there is only one
copy of the static member.
The keyword static implies that only one instance of the member exists for a class. Static variables
are used for defining constants because their values can be retrieved by invoking the class
without creating an instance of it. Static variables can be initialized outside the member function
or class definition. You can also initialize static variables inside the class definition.
The following example demonstrates the use of static variables:

using System;

namespace StaticVarApplication

class StaticVar

public static int num;

Page 178 of 228


public void count()

num++;

public int getNum()

return num;

class StaticTester

static void Main(string[] args)

StaticVar s1 = new StaticVar();

StaticVar s2 = new StaticVar();

s1.count();

s1.count();

s1.count();

s2.count();

s2.count();

s2.count();

Console.WriteLine("Variable num for s1: {0}", s1.getNum());

Console.WriteLine("Variable num for s2: {0}", s2.getNum());

Console.ReadKey();

Page 179 of 228


When the above code is compiled and executed, it produces the following result:

Variable num for s1: 6

Variable num for s2: 6

You can also declare a member function as static. Such functions can access only static variables.
The static functions exist even before the object is created. The following example demonstrates
the use of static functions:

using System;

namespace StaticVarApplication

class StaticVar

public static int num;

public void count()

num++;

public static int getNum()

return num;

class StaticTester

static void Main(string[] args)

StaticVar s = new StaticVar();

s.count();

s.count();

Page 180 of 228


s.count();

Console.WriteLine("Variable num: {0}", StaticVar.getNum());

Console.ReadKey();

When the above code is compiled and executed, it produces the following result:
Variable num: 3

11. Inheritance and Polymorphism

Inheritance
One of the most important concepts in object-oriented programming is 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.
A class can inherit from another class to extend or customize the original class. Inheriting from a
class lets you reuse the functionality in that class instead of building it from scratch. A class can
inherit from only a single class but can itself be inherited by many classes, thus forming a class
hierarchy. In this example, we start by defining a class called Asset:
public class Asset
{
public string Name;
}
Next, we define classes called Stock and House, which will inherit from Asset. Stock and House
get everything an Asset has, plus any additional members that they define:
public class Stock : Asset // inherits from Asset
{
public long SharesOwned;
}
public class House : Asset // inherits from Asset
{
public decimal Mortgage;
}
Here’s how we can use these classes:
Stock msft = new Stock { Name="MSFT",
SharesOwned=1000 };
Console.WriteLine (msft.Name); // MSFT
Console.WriteLine (msft.SharesOwned); // 1000
House mansion = new House { Name="Mansion",
Mortgage=250000 };
Console.WriteLine (mansion.Name); // Mansion
Console.WriteLine (mansion.Mortgage); // 250000
The derived classes, Stock and House, inherit the Name property from the base class, Asset.

Page 181 of 228


A derived class is also called a subclass.
A base class is also called a superclass.
Polymorphism
The word polymorphism means having many forms. In object-oriented programming paradigm,
polymorphism is often expressed as 'one interface, multiple functions'.
Polymorphism can be static or dynamic. In static polymorphism, the response to a function is
determined at the compile time. In dynamic polymorphism, it is decided at run-time.
Static Polymorphism
The mechanism of linking a function with an object during compile time is called early binding. It is
also called static binding. C# provides two techniques to implement static polymorphism. They are:

 Function overloading
 Operator overloading

Function Overloading
You can have multiple definitions for the same function name in the same scope. The definition of the
function must differ from each other by the types and/or the number of arguments in the argument
list. You cannot overload function declarations that differ only by return type.
The following example shows using function print() to print different data types:

using System;

namespace PolymorphismApplication

class Printdata

void print(int i)

Console.WriteLine("Printing int: {0}", i );

void print(double f)

Console.WriteLine("Printing float: {0}" , f);

void print(string s)

Page 182 of 228


Console.WriteLine("Printing string: {0}", s);

static void Main(string[] args)

Printdata p = new Printdata();

// Call print to print integer

p.print(5);

// Call print to print float

p.print(500.263);

// Call print to print string

p.print("Hello C++");

Console.ReadKey();

When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing string: Hello C++
Dynamic Polymorphism
C# allows you to create abstract classes that are used to provide partial class implementation of an
interface. Implementation is completed when a derived class inherits from it. Abstract classes contain
abstract methods, which are implemented by the derived class. The derived classes have more
specialized functionality.
Here are the rules about abstract classes:

 You cannot create an instance of an abstract class


 You cannot declare an abstract method outside an abstract class
 When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared
sealed.

The following program demonstrates an abstract class:

Page 183 of 228


using System;

namespace PolymorphismApplication

abstract class Shape

public abstract int area();

class Rectangle: Shape

private int length;

private int width;

public Rectangle( int a=0, int b=0)

length = a;

width = b;

public override int area ()

Console.WriteLine("Rectangle class area :");

return (width * length);

class RectangleTester

static void Main(string[] args)

Page 184 of 228


Rectangle r = new Rectangle(10, 7);

double a = r.area();

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

Console.ReadKey();

When the above code is compiled and executed, it produces the following result:
Rectangle class area :
Area: 70
When you have a function defined in a class that you want to be implemented in an inherited class(es),
you use virtual functions. The virtual functions could be implemented differently in different inherited
class and the call to these functions will be decided at runtime.
Dynamic polymorphism is implemented by abstract classes and virtual functions.
The following program demonstrates this:

using System;

namespace PolymorphismApplication

class Shape

protected int width, height;

public Shape( int a=0, int b=0)

width = a;

height = b;

public virtual int area()

Console.WriteLine("Parent class area :");

return 0;

Page 185 of 228


}

class Rectangle: Shape

public Rectangle( int a=0, int b=0): base(a, b)

public override int area ()

Console.WriteLine("Rectangle class area :");

return (width * height);

class Triangle: Shape

public Triangle(int a = 0, int b = 0): base(a, b)

public override int area()

Console.WriteLine("Triangle class area :");

return (width * height / 2);

class Caller

Page 186 of 228


{

public void CallArea(Shape sh)

int a;

a = sh.area();

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

class Tester

static void Main(string[] args)

Caller c = new Caller();

Rectangle r = new Rectangle(10, 7);

Triangle t = new Triangle(10, 5);

c.CallArea(r);

c.CallArea(t);

Console.ReadKey();

When the above code is compiled and executed, it produces the following result:
Rectangle class area:
Area: 70
Triangle class area:
Area: 25
Method overriding
When an instance method declaration includes an override modifier, the method is said to be an
override method. An override method overrides an inherited virtual method with the same signature.
Whereas a virtual method declaration introduces a new method, an override method

Page 187 of 228


declaration specializes an existing inherited virtual method by providing a new implementation of that
method.
The method overridden by an override declaration is known as the overridden base method. For an
override method M declared in a class C, the overridden base method is determined by examining
each base class of C, starting with the direct base class of C and continuing with each successive direct
base class, until an accessible method with the same signature as M is located. For the purposes of
locating the overridden base method, a method is considered accessible if it is public, if it
is protected, if it is protected internal, or if it is internal and declared in the same program
as C.
A compile-time error occurs unless all of the following are true for an override declaration:

 An overridden base method can be located as described above.


 The overridden base method is a virtual, abstract, or override method. In other words,
the overridden base method cannot be static or non-virtual.
 The overridden base method is not a sealed method.
 The override declaration and the overridden base method have the same return type.
 The override declaration and the overridden base method have the same declared
accessibility. In other words, an override declaration cannot change the accessibility of
the virtual method.

An override declaration can access the overridden base method using a base-access. In the example
class A
{
int x;
public virtual void PrintFields() {
Console.WriteLine("x = {0}", x);
}
}
class B: A
{
int y;
public override void PrintFields() {
base.PrintFields();
Console.WriteLine("y = {0}", y);
}
}
the base.PrintFields() invocation in B invokes the PrintFields method declared in A.
A base-access disables the virtual invocation mechanism and simply treats the base method as a non-
virtual method. Had the invocation in Bbeen written ((A)this).PrintFields(), it would
recursively invoke the PrintFields method declared in B, not the one declared in A,
since PrintFields is virtual and the run-time type of ((A)this) is B.
Only by including an override modifier can a method override another method. In all other cases, a
method with the same signature as an inherited method simply hides the inherited method. In the
example
class A
{
public virtual void F() {}
}
class B: A
{

Page 188 of 228


public virtual void F() {} // Warning, hiding inherited F()
}
the F method in B does not include an override modifier and therefore does not override
the F method in A. Rather, the F method in B hides the method in A, and a warning is reported
because the declaration does not include a newmodifier.
In the example
class A
{
public virtual void F() {}
}
class B: A
{
new private void F() {} // Hides A.F within B
}
class C: B
{
public override void F() {} // Ok, overrides A.F
}
the F method in B hides the virtual F method inherited from A. Since the new F in B has private
access, its scope only includes the class body of B and does not extend to C. Therefore, the declaration
of F in C is permitted to override the F inherited from A.

Method Overloading
A type may overload methods (have multiple methods with the same name), as long as the
signatures are different. For example, the following methods can all coexist in the same type:
void Foo (int x) {...}
void Foo (double x) {...}
void Foo (int x, float y) {...}
void Foo (float x, int y) {...}
However, the following pairs of methods cannot coexist in the same type, since the return type
and the params modifier are not part of a method’s signature:
void Foo (int x) {...}
float Foo (int x) {...} // Compile-time error
void Goo (int[] x) {...}
void Goo (params int[] x) {...} // Compile-time error

Page 189 of 228


12. Exception Handling
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.

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

 catch: A program catches an exception with an exception handler at the place in a


program where you want to handle the problem. The catch keyword indicates the
catching of an exception.

 finally: The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed
whether an exception is raised or not.

 throw: A program throws an exception when a problem shows up. This is done using a
throw keyword.

Syntax
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, and the syntax for using try/catch looks
like the following:

try

// statements causing exception

catch( ExceptionName e1 )

// error handling code

catch( ExceptionName e2 )

// error handling code

Page 190 of 228


catch( ExceptionName eN )

// error handling code

finally

// statements to be executed

You can list down multiple catch statements to catch different type of exceptions in case your try block
raises more than one exception in different situations.
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 System.ApplicationException class supports exceptions generated by application programs.
Hence the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class:
<Tbale no.>
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


deferencing a null object.

System.DivideByZeroException Handles errors generated from


dividing a dividend with zero.

System.InvalidCastException Handles errors generated during


typecasting.

System.OutOfMemoryException Handles errors generated from


insufficient free memory.

Page 191 of 228


System.StackOverflowException Handles errors generated from
stack overflow.

Handling Exceptions
C# provides a structured solution to the exception handling in the form of try and catch blocks. Using
these blocks the core program statements are separated from the error-handling statements.
These error handling blocks are implemented using the try, catch, and finally keywords. Following is
an example of throwing an exception when dividing by zero condition occurs:

using System;

namespace ErrorHandlingApplication

class DivNumbers

int result;

DivNumbers()

result = 0;

public void division(int num1, int num2)

try

result = num1 / num2;

catch (DivideByZeroException e)

Console.WriteLine("Exception caught: {0}", e);

finally

Page 192 of 228


{

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

static void Main(string[] args)

DivNumbers d = new DivNumbers();

d.division(25, 0);

Console.ReadKey();

When the above code is compiled and executed, it produces the following result:

Exception caught: System.DivideByZeroException: Attempted to divide by zero.

at ...

Result: 0

Creating User-Defined Exceptions


You can also define your own exception. User-defined exception classes are derived from
the Exception class. The following example demonstrates this:

using System;

namespace UserDefinedException

class TestTemperature

static void Main(string[] args)

Temperature temp = new Temperature();

try

Page 193 of 228


{

temp.showTemp();

catch(TempIsZeroException e)

Console.WriteLine("TempIsZeroException: {0}", e.Message);

Console.ReadKey();

public class TempIsZeroException: Exception

public TempIsZeroException(string message): base(message)

public class Temperature

int temperature = 0;

public void showTemp()

if(temperature == 0)

throw (new TempIsZeroException("Zero Temperature found"));

Page 194 of 228


}

else

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

When the above code is compiled and executed, it produces the following result:
TempIsZeroException: Zero Temperature found
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the System.Exception class.
You can use a throw statement in the catch block to throw the present object as:

Catch(Exception e)

...

Throw e

Page 195 of 228


13. Integrating Media Design and Interactivity
Introduction
An overarching goal of interaction design is to develop interactive systems that elicit
positive responses from users, such as feeling at ease, being comfortable, and enjoying the
experience of using them. More recently, designers have become interested in how to
design interactive products that elicit specific kinds of emotional responses in users,
motivating them to learn, play, be creative, and be social. There is also a growing concern
with how to design websites that people can trust, that make them feel comfortable about
divulging personal information or making a purchase.

What are affective aspects?


In general, the term "affective" refers to producing an emotional response. For example,
when people are happy they smile. Affective behavior can also cause an emotional response
in others. So, for example, when someone smiles it can cause others to feel good and smile
back. Emotional skills, especially the ability to ex- press and recognize emotions, are central
to human communication. Most of us are highly skilled at detecting when someone is angry,
happy, sad, or bored by recognizing their facial expressions, way of speaking, and other
body signals. We are also very good at knowing what emotions to express in given
situations. For example, when someone has just heard they have failed an exam we know it
is not a good time to smile and be happy. Instead we try to empathize.

Expressive interfaces
A well-known approach to designing affective interfaces is to use expressive icons and other
graphical elements to convey emotional states. These are typically used to indicate the
current state of a computer. For example, a hallmark of the Apple computer is the icon of a
smiling Mac that appears on the screen when the machine is first started The smiling icon
conveys a sense of friendliness, inviting the user to feel at ease and even smile back. The
appearance of the icon on the screen can also be very reassuring to users, indicating that
their computer is working fine.

Other ways of conveying the status of a system are through the use of:

 dynamic icons, e.g., a recycle bin expanding when a file is placed into it
 animations, e.g., a bee flying across the screen indicating that the computer is doing
something, like checking files

Page 196 of 228


 spoken messages, using various kinds of voices, telling the user what needs to be
done
 various sounds indicating actions and events (e.g. window closing, files being
dragged, new email arriving)

The style of an interface, in terms of the shapes, fonts, colors, and graphical elements that
are used and the way they are combined, influences how pleasurable it is to interact with.

Until recently, HCI has focused primarily on getting the usability right, with little attention
being paid to how to design aesthetically pleasing inter- faces. Interestingly, recent research
suggests that the aesthetics of an interface can have a positive effect on people's perception
of the system's usability

Aaron Marcus, a graphic designer, created the two designs in an attempt to provide
appealing interfaces. Dialog box A was designed for white American females while dialog
box B was designed for European adult male intellectuals. The rationale behind Marcus's
ideas was that European adult male intellectuals like "suave prose, a restrained treatment
of information density, and a classical approach to font selection (e.g., the use of serif
type in axial symmetric layouts similar to those found in elegant bronze European building
identification signs)." In contrast, white American females "prefer a more detailed
presentation, curvilinear shapes and the absence of some of the more-brutal terms .. .
favored by male software engineers."

When the different interfaces were empirically tested by Teasley et al. (1994), their re-
sults did not concur with Marcus's assumptions. In particular, they found that the
European dialog box was liked the best by all people and was considered most
appropriate for all users. Moreover, the round dialog box designed for women was
strongly disliked by every- one. The assumption that women like curvilinear features
clearly was not true in this con- text. At the very least, displaying the font labels in a
circular plane makes them more difficult to read than when presented in the
conventionally accepted horizontal plane.

Page 197 of 228


Expressive forms like emoticons, sounds, icons, and interface agents have been primarily
used to (i) convey emotional states andlor (ii) elicit certain kinds of emo- tional responses in
users, such as feeling at ease, comfort, and happiness. However, in many situations
computer interfaces inadvertently elicit negative emotional responses. By far the most
common is user frustration, to which we now turn our attention.

User frustration
Everyone at some time or other gets frustrated when using a computer. The effect ranges
from feeling mildly amused to extremely angry. There are myriads of rea- sons why such
emotional responses occur:

 when an application doesn't work properly or crashes


 when a system doesn't do what the user wants it to do
 when a user's expectations are not met
 when a system does not provide sufficient information to let the user know what to
do
 when error messages pop up that are vague, obtuse, or condemning
 when the appearance of an interface is too noisy, garish, gimmicky, or patronizing
 when a system requires users to carry out many steps to perform a task, only to
discover a mistake was made somewhere along the line and they need to start all
over again

Often user frustration is caused by bad design, no design, inadvertent design, or ill-thought-
out design. It is rarely caused deliberately. However, its impact on users can be quite drastic
and make them abandon the application or tool. Here, we pre- sent some examples of

Page 198 of 228


classic user-frustration provokers that could be avoided or reduced by putting more thought
into the design of the conceptual model.

 Gimmicks
Cause: When a users' expectations are not met and they are instead presented with a
gimmicky display.

Level of frustration: Mild

How to avoid or help reduce the frustration:
By far the best strategy is to avoid using gimmicks to cover up the real crime. In this
example it is much better to put material live on the web only when it is complete
and working properly.

 Error Messages
Cause: When a system or application crashes and provides an "unexpected" error
message.

Level of frustration: High
How to avoid or help reduce the frustration:
Ideally, error messages should be treated as how-to-fix-it messages. Instead of
explicating what has happened, they should state the cause of the problem and what
the user needs to do to fix it. Shneiderman (1998) has developed a detailed set of
guidelines on how to develop helpful messages that are easy to read and under-
stand. Box 5.1 summarizes the main recommendations.

 Overburdening the user
Cause: Upgrading software so that users are required to carry out excessive house-
keeping tasks

Level of frustration: Medium to high

How to avoid or help reduce the frustration:
Users should not have to spend large amounts of time on housekeeping tasks.
Upgrading should be an effortless and largely automatic process. Designers need to
think carefully about the trade-offs incurred when introducing upgrades, especially
the amount of relearning required. Plug-ins that users have to search for, down- load,
and set up themselves should be phased out and replaced with more powerful
browsers that automatically download the right plug-ins and place them in the
appropriate desktop folder reliably, or, better still, interpret the different file types
themselves.

 Appearance
Cause: When the appearance of an interface is unpleasant 

Level of frustration: Medium

How to avoid or help reduce the frustration:
Interfaces should be designed to be simple, perceptually salient, and elegant and to
adhere to usability design principles, well-thought-outgraphic design princi- ples, and
ergonomic guidelines (e.g. Mullet and Sano, 1996).

Dealing with user frustration

Page 199 of 228


In the previous part, we provided some suggestions on how systems could be improved to
help reduce commonly caused frustrations. There will always be situations, however, in
which systems do not function in the way users expect them to, or in which the user
misunderstands something and makes a mistake. In these circumstances, error messages
(phrased as "how-to-fix-it” advice) should be provided that explain what the user needs to
do.

Another way of providing information is through online help, such as tips, handy hints, and
contextualized advice.

What is interaction design about?


In interaction design, we investigate the artifact's use and target domain by taking a user-
centered approach to development. This means that users' concerns direct the
development rather than technical concerns.

So interaction design involves developing a plan which is informed by the product's


intended use, target domain, and relevant practical considerations. Alter- native designs
need to be generated, captured, and evaluated by users. For the evaluation to be successful,
the design must be expressed in a form suitable for users to interact with.

Four basic activities of interaction design


These are: identifying needs and establishing requirements, developing alternative designs
that meet those requirements, building interactive versions so that they can be
communicated and assessed, and evaluating them, i.e., measuring their acceptability.

Identifying needs and establishing requirements


In order to design something to support people, we must know who our target users are
and what kind of support an interactive product could usefully provide. These needs
form the basis of the product's requirements and underpin subsequent design and
development. This activity is fundamental to a user-centered approach, and is very
important in interaction design

Developing alternative designs


This is the core activity of designing: actually suggesting ideas for meeting the re -
quirements. This activity can be broken up into two sub-activities: conceptual design
and physical design. Conceptual design involves producing the conceptual model for the
~roducta,nd a conceptual model describes what the product should do, behave and look
like. Physical design considers the detail of the product including the col- ors, sounds,
and images to use, menu design, and icon design. Alternatives are con- sidered at every
point.

Building interactive versions of the designs


Interaction design involves designing interactive products. The most sensible way for
users to evaluate such designs, then, is to interact with them. This requires an
interactive version of the designs to be built, but that does not mean that a software
version is required. There are different techniques for achieving "interaction," not all of
which require a working piece of software. For example, paper-based proto- types are
very quick and cheap to build and are very effective for identifying prob- lems in the

Page 200 of 228


early stages of design, and through role-playing users can get a real sense of what it will
be like to interact with the product.

Evaluating designs
Evaluation is the process of determining the usability and acceptability of the prod - uct
or design that is measured in terms of a variety of criteria including the number of errors
users make using it, how appealing it is, how well it matches the requirements, and so
on. Interaction design requires a high level of user involvement throughout
development, and this enhances the chances of an acceptable product being delivered.
In most design situations you will find a number of activities concerned with quality
assurance and testing to make sure that the final product is "fit-for-purpose."
Evaluation does not replace these activities, but complements and enhances them.

Three key characteristics of the interaction design process


There are three characteristics that we believe should form a key part of the interaction
design process. These are: a user focus, specific usability criteria, and iteration.

Some practical issues


Before we consider how the activities and key characteristics of interaction design can be
pulled together into a coherent process, we want to consider some questions highlighted by
the discussion so far. These questions must be answered if we are going to be able to "do"
interaction design in practice. These are:

 Who are the users?



 What do we mea; by needs?

 How do you generate alternative designs?
 How do you choose among alternatives?

What is a prototype?

prototype can be anything from a paper-based storyboard through to a complex piece of


software, and from a cardboard mockup to a molded or pressed piece of metal. A prototype
allows stakeholders to interact with an envisioned product, to gain some experience of
using it in a realistic setting, and to explore imagined uses.

Why prototype?

Prototypes are a useful aid when discussing ideas with stakeholders; they are a
communication device among team members, and are an effective way to test out ideas for
yourself.

Page 201 of 228


A paper-based prototype of a handheld device to support an autistic child.

Low-fidelity prototyping
A low-fidelity prototype is one that does not look very much like the final product. For
example, it uses materials that are very different from the intended final version, such as
paper and cardboard rather than electronic screens and metal. Low-fidelity prototypes are
useful because they tend to be simple, cheap, and quick to produce.

 Storyboarding is one example of low-fidelity prototyping that is often used in


conjunction with scenarios.

Page 202 of 228


An example storyboard.

 Sketching Low-fidelity prototyping often relies on sketching, and many people find it
difficult to engage in this activity because they are inhibited about the quality of
their drawing.

Some simple sketches for low-fidelity prototyping

High-fidelity prototyping
High-fidelity prototyping uses materials that you would expect to be in the final product and
produces a prototype that looks much more like the final thing.

Page 203 of 228


Conceptual design: moving from requirements to first design
Conceptual design is concerned with transforming the user requirements and needs into a
conceptual model.

Key guiding principles of conceptual design are:

 Keep an open mind but never forget the users and their context.
 Discuss ideas with other stakeholders as much as possible.
 Use low-fidelity prototyping to get rapid feedback.
 Iterate, iterate, and iterate.

Using scenarios in conceptual design


Scenarios can be used to explicate existing work situations, but they are more commonly
used for expressing proposed or imagined situations to help in conceptual design.

Page 204 of 228


Using prototypes in conceptual design
Prototyping is used to get feedback on emerging designs. This feedback may be from users,
or from colleagues, or it may be feedback telling you that the idea is not technically feasible.
However, low-fidelity prototypes are not very impressive to look at, so if the feedback
you're looking for is approval from people who will be basing their judgment on first
impressions, then a horizontal, high-fidelity prototype might suit the job better than one
based on post-its or cards.

Page 205 of 228


A card-based prototype for booking a meeting in the shared calendar system

Physical design: getting concrete


Physical design involves considering more concrete, detailed issuer; of designing the
interface, such as screen or keypad design, which icons to use, how to structure menus, etc.

Page 206 of 228


A card-based prototype for borrowing a book in the library catalog system

Different kinds of widget


Interfaces are made up of widgets, elements such as dialog boxes, menus, icons, toolbars,
etc. Each element must be designed or chosen from a predesigned set of widgets.

We consider here briefly three main aspects of interface design: menu design, icon design,
and screen layout. These are applicable to a wide range of interactive products, from
standard desktop interfaces for PC software, to mobile communicator functions and
microwave ovens.

 Menu design Menus provide users with a choice that can be a choice of commands
or a choice of options related to a command.
 Icon design Designing a good icon takes more than a few minutes. You may be able
to think up good icons in a matter of seconds, but such examples are unlikely to be
widely acceptable to your user group.

Page 207 of 228


 Screen design. There are two aspects to screen design: how the task is split across a
number of screens, and how the individual screens are designed.
 Information display. Making sure that the relevant information is available for the
task is one aspect of information display, but another concerns the format.

Tool support
The tools available to support the activities described here are wide-ranging and various. Brad
Myers (1995) suggests nine facilities that user interface software tools might provide:

 Help design the interface given a specification of the end users' tasks
 Help implement the interface given a specification of the design
 Create easy-to-use interfaces
 Allow the designer to rapidly investigate different designs
 Allow nonprogrammers to design and implement user interfaces
 Automatically evaluate the interface and propose improvements
 Allow the end user to customize the interface
 Provide portability
 Be easy to use

Page 208 of 228


14. Addressing ICT Security and Risks
Introduction
Software security—the idea of engineering software so that it continues to function correctly under
malicious attack—is not really new, but it has received renewed interest over the last several years as
reactive network-based security approaches such as firewalls have proven to be ineffective.
Unfortunately, today's software is riddled with both design flaws and implementation bugs, resulting
in unacceptable security risk. The notion of software security risk has become common knowledge,
yet developers, architects, and computer scientists have only recently begun to systematically study
how to build secure software.
Software is everywhere. It runs your car. It controls your cell phone. It keeps your dishwasher going.
It is the lifeblood of your bank and the nation's power grid. And sometimes it even runs on your
computer. What's important is realizing just how widespread software is. As businesses and society
come to depend more heavily on software, we have to make it better. Now that software is networked
by default, software security is no longer a luxury—it's a necessity
Software security is about understanding software-induced security risks and how to manage them.
Good software security practice leverages good software engineering practice and involves thinking
about security early in the software lifecycle, knowing and understanding common problems
(including language-based flaws and pitfalls), designing for security, and subjecting all software
artifacts to thorough objective risk analyses and testing. As you can imagine, software security is a
knowledge-intensive field.
Factors affecting security of ICT systems
1. Defect: Both implementation vulnerabilities and design vulnerabilities are defects. A defect is
a problem that may lie dormant in software for years only to surface in a fielded system with
major consequences.

2. Bug: A bug is an implementation-level software problem. Bugs may exist in code but never be
executed. Though the term bug is applied quite generally by many software practitioners, I
reserve use of the term to encompass fairly simple implementation errors. Bugs are
implementation-level problems that can be easily discovered and remedied. An example
would be the ‘Buffer Overflow’ problem in java.

3. Flaw: A flaw is a problem at a deeper level. Flaws are often much more subtle than simply an
off-by-one error in an array reference or use of an incorrect system call. A flaw is certainly
instantiated in software code, but it is also present (or absent!) at the design level. For
example, a number of classic flaws exist in error-handling and recovery systems that fail in an
insecure or inefficient fashion. Another example can be found in the box, Microsoft Bob: A
Design Flaw, that follows. Automated technologies to detect design-level flaws do not yet
exist, though manual risk-analysis processes can identify flaws.

4. Risk: Flaws and bugs lead to risk. Risks are not failures. Risks capture the probability that a
flaw or a bug will impact the purpose of the software (that is, risk = probability x impact). Risk
measures must also take into account the potential damage that can occur. A very high risk is
not only likely to happen but also likely to cause great harm. Risks can be managed by
technical and non-technical means.

The three pillars of ICT security


ICT security of software application security is dependent on the following three pillars

Page 209 of 228


Pillar 1- Risk Management
Successful risk management is nothing more than a business level decision-support tool: a way to
gather the requisite data to make a good judgment call, based on knowledge of vulnerabilities, threats,
impacts, and probabilities.
First, risk concerns future happenings. Today and yesterday are beyond active concern, as we are
already reaping what was previously sowed by our past actions. The question is, can we, therefore, by
changing our actions today, create an opportunity for a different and hopefully better situation for
ourselves tomorrow. This means, second, that risk involves change, such as in changes of mind,
opinion, actions, or places . . . [Third,] risk involves choice, and the uncertainty that choice itself entails.
Thus paradoxically, risk, like death and taxes, is one of the few certainties of life.
When risk is considered in the context of software engineering, the three abovementioned conceptual
underpinnings are always in evidence. The future is our concern—what risks might cause the software
project to go awry? Change is our concern—how will changes in customer requirements, development
technologies, target computers, and all other entities connected to the project affect timeliness and
overall success? Last, we must grapple with choices—what methods and tools should we use, how
many people should be involved, how much
emphasis on quality is "enough"?
Pillar 2- Software Security Touchpoints
On the road to implementing a fundamental change in the way we build software, we must first agree
that software security is not security software. This is a subtle point often lost on development people,
who tend to focus on functionality. Obviously, there are security functions in the world, and most
modern software includes security features; but adding features such as SSL to your program (to
cryptographically protect communications) does not present a complete solution to the security
problem.
Software security is a system-wide issue that takes into account both security mechanisms (such as
access control) and design for security (such as robust design that makes software attacks difficult).
Sometimes these overlap, but often they don't. Put another way, security is an emergent property of
a software system. A security problem is more likely to arise because of a problem in a system's
standard-issue part (say, the interface to the database module) than in some given security feature.
This is an important reason why software security must be part of a full lifecycle approach. Just as you
can't test quality into a piece of software, you can't spray paint security features onto a design and
expect it to become secure. There's no such thing as magic crypto fairy dust—we need to focus on
software security from the ground up. We need to build security in.
Pillar 3- Knowledge
One of the critical challenges facing software security is the dearth of experienced practitioners. Early
approaches that rely solely on apprenticeship as a method of propagation will not scale quickly enough
to address the burgeoning problem. As the field evolves and best practices are established, knowledge
management and training play a central role in encapsulating and spreading the emerging discipline
more efficiently. Pillar III involves gathering, encapsulating, and sharing security knowledge that can
be used to provide a solid foundation for software security practices.
Knowledge is more than simply a list of things we know or a collection of facts. Information and
knowledge aren't the same thing, and it is important to understand the difference. Knowledge is
information in context—information put to work using processes and procedures. A checklist of
potential security bugs in C and C++ is information; the same information built into a static analysis
tool is knowledge.
Software security knowledge can be organized into seven knowledge catalogs (principles, guidelines,
rules, vulnerabilities, exploits, attack patterns, and historical risks) that are in turn grouped into three
knowledge categories (prescriptive knowledge, diagnostic knowledge, and historical knowledge).

Page 210 of 228


Addressing Risk
Risk can be addressed in three ways: accept it, mitigate it, or transfer it. The appropriate method
entirely depends on the financial value of the risk versus the investment required to reduce it to an
acceptable level or transfer it to a third party. In addition to prescriptive controls, regulations such as
HIPAA/HITECH and PCI require that organizations assess risk to protected information and implement
reasonable controls to reduce risk to an acceptable level.

Risk Acceptance
The financial value of a risk is often smaller than the cost of mitigating or transferring it. In this case,
the most reasonable option is to accept the risk. However, if the organization opts to accept a risk, it
should demonstrate that risk was indeed assessed and document the rationale behind the decision.

Risk Mitigation
When a risk has a significant financial value, it is often more appropriate to mitigate the risk rather
than accept it. With few exceptions, the cost of implementing and maintaining a control should be
less than the monetary value of the risk being mitigated. We demonstrate how to assign monetary
value to risk later in this chapter.

Risk Transfer
The insurance industry is based on risk transference. Organizations often buy insurance to cover the
costs of a security breach or catastrophic system outage. It is important to note that insurance
companies offering these types of policies often require that policy holders implement certain
controls. Failure to comply with the control requirements may nullify the policy. When the
management of IT systems is outsourced to a third party, a certain level
of risk may be contractually transferred to the third party as well. In these cases, it is the responsibility
of the organization outsourcing its systems to verify that IT risk is reduced to an acceptable level and
that the company managing its systems has the financial strength to cover a loss should it occur. See
Chapter 14 for information on auditing outsourced operations.
Quantitative vs. Qualitative Risk Analysis
Risk can be analyzed in two ways: quantitatively and qualitatively. Like anything else, each has
advantages and disadvantages. Where the quantitative approach is more objective and expresses risk
in financial terms that decision-makers can more easily justify, it is also more time-consuming. The
qualitative approach is better suited to present a stratified view of risk, but it can be more subjective
and therefore difficult to substantiate. The organizations with more successful risk management
programs tend to rely more heavily on qualitative risk analysis to identify areas of focus and then use
quantitative risk analysis techniques to justify risk mitigation expenditures.
Quantitative Risk Analysis
With few exceptions, whether related to financial, physical, or technological resources, different types
of risk can be calculated using the same universal formula. Risk can be defined by the following
calculation:
Risk = asset value × threat × vulnerability
Elements of Risk
As you can see in the preceding equation, risk comprises three elements: asset value, threat, and
vulnerability. Estimating these elements correctly is critical to assessing risk accurately.

Assets

Normally represented as a monetary value, assets can be defined as anything of worth to an


organization that can be damaged, compromised, or destroyed by an accidental or deliberate action.
In reality, an asset’s worth is rarely the simple cost of replacement; therefore, to get an accurate

Page 211 of 228


measure of risk, an asset should be valued taking into account the bottom-line cost of its compromise.
For example, a breach of personal information may not cause a monetary loss at first glance, but if it
actually were realized, it likely would result in legal action, damage to the company’s reputation, and
regulatory penalties. These consequences potentially would cause a significant financial loss. In this
case, the asset-value portion of the equation would represent the personal information. The
calculated value of the personal information would include an estimate of the cumulative dollar cost
of the legal action, reputation damage, and regulatory penalties.

Threats

A threat can be defined as a potential event that, if realized, would cause an undesirable impact. The
undesirable impact can come in many forms, but it often results in a financial loss. Threats are
generalized as a percentage, but two factors play into the severity of a threat: degree of loss and
likelihood of occurrence. The exposure factor is used to represent the degree of loss. It is simply an
estimate of the percentage of asset loss if a threat is realized. For example, if we estimate that a fire
will cause a 70 percent loss of asset value if it occurs, the exposure factor is 70 percent, or 0.7. The
annual rate of occurrence, on the other hand, represents the likelihood that a given threat would be
realized in a single year in the event of a complete absence of controls. For example, if
we estimate that a fire will occur every 3 years, the annual rate of occurrence would be 33 percent,
or 0.33. A threat, therefore, can be calculated as a percentage by multiplying the exposure factor by
the annual rate of occurrence. Given the preceding example, the threat of fire would result in a value
of 23.1 percent, or 0.231.

Vulnerabilities

Vulnerabilities can be defined as the absence or weakness of cumulative controls protecting a


particular asset. Vulnerabilities are estimated as percentages based on the level of control weakness.
We can calculate control deficiency (CD) by subtracting the effectiveness of the control by 1 or 100
percent. For example, we may determine that our industrial espionage controls are 70 percent
effective, so 100 percent – 70 percent = 30 percent (CD). This vulnerability would be represented as
30 percent, or 0.3.
Qualitative Risk Analysis
Unlike the quantitative approach to risk analysis, qualitative risk analysis techniques can provide a
high-level view into enterprise risk. Where quantitative methods focus on formulas, a qualitative risk
analysis will focus on values such as high, medium, and low or colors such as red, yellow, and green to
evaluate the risk.

As mentioned earlier, qualitative and quantitative approaches complement one another. Most
organizations base their risk management methodologies on the qualitative method, using
quantitative formulas to build business cases for risk mitigation investments. We will spend the rest
of the chapter on qualitative risk analysis.
There are 5 phases associated with qualitative risk management, they are –

• Phase 1: Identify information assets.

 The goal of this phase is to identify all information assets and assign each
information asset a criticality value of high, medium, or low for its
confidentiality, integrity, and availability requirements. For example, we may
identify credit card information as an information asset that is processed by
our retail system. This information asset is governed by the Payment Card
Industry (PCI) data security standard and is valuable to thieves if disclosed in

Page 212 of 228


an unauthorized manner. We also know that if altered, this information is
useless to us, but that in most cases a temporary loss of access to this
information is tolerable. As a result, we would assign credit card information
values of high for both confidentiality and integrity and medium for
availability.

• Phase 2: Quantify and qualify threats.

 The goal here is to quantify and qualify threats. We will be discussing this
phase in detail in the following section.

• Phase 3: Assess vulnerabilities.

 In examining threats, the common denominator is the information asset,


because each threat is tied to an information asset. When assessing
vulnerabilities, on the other hand, the common denominator is the
information process. We will first identify process-component vulnerabilities
and then combine them to determine our process vulnerabilities. Process
vulnerabilities then will be combined to determine business function
vulnerabilities.

• Phase 4: Remediate control gaps.

 This step deals with mitigating risks.

• Phase 5: Manage residual risk.

 Risk is inherently dynamic in nature, especially the threat component of risk.


As a result, we will need to measure risk continually and invest in new controls
to respond to emerging threats.

Due to the limited scope of this course we will only discuss phase 2 in detail in the next section.
Quantifying and Qualifying Threats
This phase of the risk management life cycle requires the following steps:

• Assess business threats.

• Identify technical, physical, and administrative threats.

• Quantify threat impact and probability.

• Evaluate process flows for weaknesses.

• Identify process-component threats.

Assessing Business Threats


Threats can be accounted for in several ways, but at a high level, business threats to information can
be divided into three categories: financial threats, legal threats, and regulatory threats. All business
threats will fall into one of these categories.
Financial Threats

Page 213 of 228


One could argue that all information threats are financial in nature because they all boil down to a
monetary loss, if realized. Although this may be true, we also define regulatory and legal threats
because of their prevalence. For our purposes, a financial threat is defined as a threat that, if realized,
would cause a loss of actual funds, reputation, operational effectiveness, or competitive advantage,
ultimately resulting in a monetary impact. Financial threats may include the following:

• Financial fraud
• Loss of proprietary information
• Loss of productivity

Once the information assets are identified, these types of threats become more evident. For example,
the credit card information asset we identified earlier has exposure to all three of these threats.
Legal Threats
After we’ve identified some of the financial threats, we must consider the potential legal exposure
associated with realization of a threat. Given current
privacy laws, if an individual’s private information such as his or her name and associated address,
Social Security number, health information, or credit information is disclosed in an unauthorized
manner, you can bet that some legal exposure will result. Additionally, if service levels are affected or
another organization’s confidential information is disclosed, a breach of contract could occur.
Needless to say, legal fees can be very expensive, even if a court finds in your organization’s favor. To
get an accurate business threat assessment, we need to identify potential legal exposure in the event
of an information security violation.

Regulatory Threats
Along with financial and legal threats, it is important to consider regulatory threats. A regulatory
infraction resulting from an information security
incident could lead to fines or other penalties (including imprisonment of company
officers), as well as temporary or permanent suspension of company operations. Financial institutions
generally take the laws governing their operation very seriously because of the severe consequences
of noncompliance, but health care entities, merchants, and public companies are also heavily
regulated.
The key to identifying regulatory threats is understanding the laws or mandatory
industry standards governing the information your organization is processing. Given our earlier
example, we know that the PCI data security standard will govern the protection of the credit card
information our organization processes.
Identifying Technical, Physical, and Administrative Threats
Once all the business threats pertaining to our information assets are identified, we can begin
identifying the technical, physical, and administrative threats. These threats, if realized, will give rise
to one of the business threats that we have identified. For example, a system malfunction will give
rise to a loss of organizational productivity.
Technical Threats
Technical threats are generally system related, affecting electronically stored or transmitted
information. Given our previous credit card processing example, one technical threat would be system
intrusion. This threat then could give rise to the theft of proprietary information, regulatory or legal
business threats. Here are some examples of technical threats:

• System intrusion
• Worms, viruses, spyware, and other malware
• System failure
• Logical access control failure

Page 214 of 228


Physical Threats
Physical threats are normally facility related and often can be tied to natural events or mechanical
breakdowns. Here are some examples of physical threats:

• Natural or man-made disasters


• Physical intrusion
• Fire
• Water seepage from burst pipes or weather-related flooding
• Excessive heat or humidity
• Electrical disruptions or black-outs

Although physical in nature, these threats can cause significant information loss. Business
continuity/disaster recovery plans and data center controls aim to address these threats. See Chapter
4 for information on auditing data centers and business continuity plans.
Administrative Threats
It is common knowledge in information security circles that the “human factor” is the cause of most
security violations. Administrative threats are people related. They may include the following:

• Unintentional disclosure of sensitive information


• Social engineering
• Information theft
• Industrial espionage
• Malicious destruction of information
• Accidental deletion or corruption of information
• System configuration errors
• Inappropriate use of computing resources

Evaluating Process Flows


Now that we understand our business and high-level technical threats, we can examine the processes
that we mapped out when we identified our information assets. We will review the process as a whole
for weaknesses. For example, processes that are manual in nature are more susceptible to
vulnerabilities than highly automated processes. In fact, we can look for several things that might
indicate a need for increased controls, such as the following:

• Manual inputs and outputs


• Data transmission over untrusted networks
• Interfaces between applications
• External data inputs and outputs (including cloud providers)
• Nonsegregated data stores

With the increase in utility computing in recent years, information flows have become more
decentralized. This obviously increases risk because of the necessity to trust cloud providers with
sensitive information that would have remained within the boundaries of internal networks just a few
years ago.

Identifying Process Component Threats


Since we have now mapped our process flows and examined them for obvious weaknesses, we can
analyze the threats to different process components such as systems, manual inputs, or outputs.

Page 215 of 228


Our goal is to identify the threats associated with each step in the process. For example, when an
employee swipes a card (step 1), we might identify a threat of employees keeping credit cards or credit
card numbers of store customers. Or we might identify a risk of system failure or system intrusion
when transactions are aggregated to a system within each retail store (step 2). We should be able to
identify several threats for each process component. When combined, they represent all the threats
associated with the processing of an information asset.

Page 216 of 228


15. Testing and Deployment of the Application
Introduction
Software testing is a critical element of software quality assurance and represents the
ultimate review of specification, design, and code generation.
The increasing visibility of software as a system element and the attendant
"costs" associated with a software failure are motivating forces for well-planned,
thorough testing. It is not unusual for a software development organization to
expend between 30 and 40 percent of total project effort on testing. In the
extreme, testing of human-rated software (e.g., flight control, nuclear reactor
monitoring) can cost three to five times as much as all other software engineering steps
combined!

Testing Objectives
In an excellent book on software testing, Glen Myers [MYE79] states a number of
rules that can serve well as testing objectives:

 Testing is a process of executing a program with the intent of finding an


error.
 A good test case is one that has a high probability of finding an as-yet undiscovered
error.
 A successful test is one that uncovers an as-yet-undiscovered error.

These objectives imply a dramatic change in viewpoint. They move counter to the
commonly held view that a successful test is one in which no errors are found. Our objective
is to design tests that systematically uncover different classes of errors and to do so with a
minimum amount of time and effort.

If testing is conducted successfully (according to the objectives stated previously), it will


uncover errors in the software. As a secondary benefit, testing demonstrates that software
functions appear to be working according to specification, that behavioral and performance
requirements appear to have been met. In addition, data collected as testing is conducted
provide a good indication of software reliability and some indication of software quality as a
whole. But testing cannot show the absence of errors and defects, it can show only that
software errors and defects are present. It is important to keep this (rather gloomy)
statement in mind as testing is being conducted.

Testing Principles
In an excellent book on software testing, Glen Myers [MYE79] states a number of
rules that can serve well as testing objectives:

Before applying methods to design effective test cases, a software engineer must
understand the basic principles that guide software testing. Davis [DAV95] suggests a set of
testing principles that have been adapted for use in this book:

 All tests should be traceable to customer requirements. As we have


seen, the objective of software testing is to uncover errors. It follows that the most

Page 217 of 228


severe defects (from the customer’s point of view) are those that cause the program
to fail to meet its requirements.
 Tests should be planned long before testing begins. Test planning can begin as soon
as the requirements model is complete. Detailed definition of test cases can begin as
soon as the design model has been solidified. Therefore, all tests can be planned and
designed before any code has been generated.
 The Pareto principle applies to software testing. Stated simply, the
Pareto principle implies that 80 percent of all errors uncovered during testing will
likely be traceable to 20 percent of all program components. The problem, of course,
is to isolate these suspect components and to thoroughly test them.
 Testing should begin “in the small” and progress toward testing “in
the large.” The first tests planned and executed generally focus on individual
components. As testing progresses, focus shifts in an attempt to find errors in
integrated clusters of components and ultimately in the entire system.
 Exhaustive testing is not possible. The number of path permutations for
even a moderately sized program is exceptionally large (see Section 17.2 for further
discussion). For this reason, it is impossible to execute every combination of paths
during testing. It is possible, however, to adequately cover program logic and to
ensure that all conditions in the component-level design have been exercised.
 To be most effective, testing should be conducted by an independent third party.
By most effective, we mean testing that has the highest probability of finding errors
(the primary objective of testing). The software engineer who created the system is
not the best
person to conduct all tests for the software.
Black Box Testing vs White Box Testing
Criteria Black Box Testing White Box Testing
Definition White Box Testing is a software
Black Box Testing is a software testing method in which the
testing method in which the internal structure/ design/
internal structure/ design/ implementation of the item being
implementation of the item being tested is known to the tester.
tested is NOT known to the tester

Levels Applicable To Mainly applicable to higher levels Mainly applicable to lower levels
of testing: of testing:
Acceptance Testing Unit Testing
System Testing Integration Testing

Responsibility Generally, independent Software Generally, Software Developers


Testers
Programming Knowledge Not Required
Required

Implementation Knowledge Not Required Required


Basis for Test Cases Requirement Specifications Detail Design

Alpha and Beta Testing


It is virtually impossible for a software developer to foresee how the customer will
really use a program. Instructions for use may be misinterpreted; strange combinations of

Page 218 of 228


data may be regularly used; output that seemed clear to the tester may be unintelligible to
a user in the field. When custom software is built for one customer, a series of acceptance
tests are conducted to enable the customer to validate all requirements. Conducted by the
end user rather than software engineers, an acceptance test can range from an informal
"test drive" to a planned and systematically executed series of tests. In fact, acceptance
testing can be conducted over a period of weeks or months, thereby uncovering cumulative
errors that might degrade the system over time. If software is developed as a product to be
used by many customers, it is impractical to perform formal acceptance tests with each one.
Most software product builders use a process called alpha and beta testing to uncover
errors that only the end-user seems able to find.

The alpha test is conducted at the developer's site by a customer. The software is
used in a natural setting with the developer "looking over the shoulder" of the user and
recording errors and usage problems. Alpha tests are conducted in a controlled
environment.

The beta test is conducted at one or more customer sites by the end-user of the
software. Unlike alpha testing, the developer is generally not present. Therefore, the beta
test is a "live" application of the software in an environment that cannot be controlled by
the developer. The customer records all problems (real or imagined) that are encountered
during beta testing and reports these to the developer at regular intervals. As a result of
problems reported during beta tests, software engineers make modifications and then
prepare for release of the software product to the entire customer base.

Manual Testing vs Automation Testing


Automation Testing Manual Testing
Automation testing perform the same operation Manual testing is not reliable. Using this method
each time test execution is not accurate all the time.
Automation testing is very much helpful regressions To execute the test cases first time using manual
in testing where code changes frequently. testing will be very much useful. But it is not sure
that it will catch the regression defects under
frequently changing requirements.
Automation testing will be useful to execute the set Manual testing will be useful when the test case
of test cases frequently. only needs to run once or twice.
After making Automation test suites, fewer testers To execute the test cases every time tester requires
required to execute the test cases. the same amount of time
Automation testing can also be done on different Using manual testing, testing on different machine
machine with different OS platform combination, with different OS platform combination is not
concurrently. possible, concurrently. To execute such task
different testers are required.
Using Automation testing, testers can test It does not involve in programming task to fetch
complicated application too. hidden information.
Automation runs test cases significantly faster than Manual testing is slower than automation. Running
human resources. tests manually can be very time consuming.
Some time it is not helpful in UI testing It is very much helpful in UI testing
Automation testing is very useful for automating the To execute the Build Verification Testing (BVT) is
Build Verification Testing (BVT) & it is not mundane very mundane and tiresome in manual testing.
and tiresome.
Initial cost of automation testing is more than Manual testing requires less cost than automation.
manual testing but useful always.

Page 219 of 228


What are Test Cases?
A test case is a document, which has a set of test data, preconditions, expected results and
postconditions, developed for a particular test scenario in order to verify compliance against
a specific requirement.

Test Case acts as the starting point for the test execution, and after applying a set of input
values, the application has a definitive outcome and leaves the system at some end point or
also known as execution postcondition.

Typical Test Case Parameters:


 Test Case ID
 Test Scenario
 Test Case Description
 Test Steps
 Prerequisite
 Test Data
 Expected Result
 Test Parameters
 Actual Result
 Environment Information
 Comments

Example:
Let us say that we need to check an input field that can accept maximum of 10 characters.

While developing the test cases for the above scenario, the test cases are documented the
following way. In the below example, the first case is a pass scenario while the second case
is a FAIL.

Scenario Test Step Expected Result Actual Outcome

Verify that the input field that Login to application Application should be Application accepts
can accept maximum of 10 and key in 10 able to accept all 10 all 10 characters.
characters characters characters.

Verify that the input field that Login to application Application should NOT Application accepts
can accept maximum of 11 and key in 11 accept all 11 characters. all 10 characters.
characters characters

If the expected result doesn't match with the actual result, then we log a defect. The defect
goes through the defect life cycle and the testers address the same after fix.

Unit Testing
Unit testing focuses verification effort on the smallest unit of software design—the software
component or module. Using the component-level design description as a guide, important
control paths are tested to uncover errors within the boundary of the module. The relative
complexity of tests and uncovered errors is limited by the constrained scope established for

Page 220 of 228


unit testing. The unit test is white-box oriented, and the step can be conducted in parallel
for multiple components.

Page 221 of 228


Unit Test Plan Template

Unit Test Plan

Module ID: _________ Program ID: ___________

1. Module Overview

Briefly define the purpose of this module. This may require only a single phrase: i.e.: calculates
overtime pay amount, calculates equipment depreciation, performs date edit validation, or
determines sick pay eligibility, etc.

1.1 Inputs to Module

[Provide a brief description of the inputs to the module under test.]

1.2 Outputs from Module

[Provide a brief description of the outputs from the module under test.]

1.3 Logic Flow Diagram

[Provide logic flow diagram if additional clarity is required.]

2. Test Data

(Provide a listing of test cases to be exercised to verify processing logic.)

2.1 Positive Test Cases

[Representative data samples should provide a spectrum of valid field and processing values
including "Syntactic" permutations that relate to any data or record format issues. Each test

Page 222 of 228


Unit Test Plan

case should be numbered, indicate the nature of the test to be performed and the expected
proper outcome.]

2.2 Negative Test Cases

[The invalid data selection contains all of the negative test conditions associated with the
module. These include numeric values outside thresholds, invalid Characters, invalid or missing
header/trailer record, and invalid data structures (missing required elements, unknown
elements, etc.)

3. Interface Modules

[Identify the modules that interface with this module indicating the nature of the interface:
outputs data to, receives input data from, internal program interface, external program
interface, etc. Identify sequencing required for subsequent string tests or sub-component
integration tests.]

4. Test Tools

[Identify any tools employed to conduct unit testing. Specify any stubs or utility programs
developed or used to invoke tests. Identify names and locations of these aids for future
regression testing. If data supplied from unit test of coupled module, specify module
relationship.]

Page 223 of 228


Unit Test Result

1. Unit Test Plan Scope (In Scope – Out of Scope)


In Scope Out of Scope
In Scope List features/functions that are tested. Out of Scope List features/functions that are not
tested.

2. Unit Test Cases


ID Test Cases Input Value Expected Output Actual Output
2.1 Test Case Identify the test cases
along with the expected results.
Example:
Test Procedure:
Login with a corporate user
account.
Username: abc
Password: abc
Expected Results:
An error will be displayed for the
wrong credentials.

3. Unit Test Results


ID Test Cases Pass/Fail Tested By Date
Tested
Test Case Name the test case. mm/dd/y
Example: yyy
Test Procedure:
Login with a corporate user account.
Username: abc
Password: abc
Expected Results:
An error will be displayed for the wrong credentials.

Test Case Add more rows if needed.

System Testing
System testing is actually a series of different tests whose primary purpose is to fully
exercise the computer-based system. Although each test has a different purpose, all work to
verify that system elements have been properly integrated and perform allocated functions.

Recovery Testing
Many computer based systems must recover from faults and resume processing within a
prespecified time. In some cases, a system must be fault tolerant; that is, processing faults
must not cause overall system function to cease. In other cases, a system failure must be
corrected within a specified period of time or severe economic damage will occur.

Recovery testing is a system test that forces the software to fail in a variety of ways
and verifies that recovery is properly performed. If recovery is automatic (performed by the
system itself), re-initialization, checkpointing mechanisms, data recovery, and restart are

Page 224 of 228


evaluated for correctness. If recovery requires human intervention, the mean-time-to-repair
(MTTR) is evaluated to determine whether it is within acceptable limits.

Security Testing
Security testing attempts to verify that protection mechanisms built into a system will, in
fact, protect it from improper penetration. "The system's security must, of course, be tested
for invulnerability from frontal attack—but must also be tested for invulnerability from flank
or rear attack."

During security testing, the tester plays the role(s) of the individual who desires to
penetrate the system. Anything goes! The tester may attempt to acquire passwords through
external clerical means; may attack the system with custom software designed to
breakdown any defenses that have been constructed; may overwhelm the system, thereby
denying service to others; may purposely cause system errors, hoping to penetrate during
recovery; may browse through insecure data, hoping to find the key to system entry.

Given enough time and resources, good security testing will ultimately penetrate
a system. The role of the system designer is to make penetration cost more than the value
of the information that will be obtained.

Stress Testing
Stress testing executes a system in a manner that demands resources in abnormal
quantity, frequency, or volume. For example, (1) special tests may be designed that
generate ten interrupts per second, when one or two is the average rate, (2) input data
rates may be increased by an order of magnitude to determine how input functions will
respond, (3) test cases that require maximum memory or other resources are executed, (4)
test cases that may cause thrashing in a virtual operating system are designed, (5) test cases
that may cause excessive hunting for disk-resident data are created. Essentially, the tester
attempts to break the program.
A variation of stress testing is a technique called sensitivity testing. In some situations (the
most common occur in mathematical algorithms), a very small range of data contained
within the bounds of valid data for a program may cause extreme and even erroneous
processing or profound performance degradation. Sensitivity testing attempts to uncover
data combinations within valid input classes that may cause instability or improper
processing.

Performance Testing
Performance testing is designed to test the run-time performance of software within the
context of an integrated system. Performance testing occurs throughout all steps in the
testing process. Even at the unit level, the performance of an individual module may be
assessed as white-box tests are conducted. However, it is not until all system elements are
fully integrated that the true performance of a system can be ascertained.

Software Deployment
Software producers in this context no longer distribute complete systems. They must
therefore find a way to deal with greater uncertainty in the environment within which their
systems will operate. For example, before they can guarantee a successful installation,
producers must be able to determine what components are available at a given site, as well

Page 225 of 228


as the configuration of those
components. Additionally, since the components are produced by multiple organizations,
they must be able to anticipate or react to updates to components that are not under their
control.

These issues are further magnified when the scale of the Internet—in terms of the vast
numbers of producers and consumers, as well as the great distances involved—is taken into
consideration. Clearly, this is a daunting task that creates new challenges in the areas of
release, installation, activation, deactivation, update, and removal of components. These
activities constitute a large and complex process that we refer to as software deployment.

The Software Deployment Process

The following steps constitute the steps in a software deployment.

Release: The release activity is the interface of the deployment process with the
development process. It encompasses all the operations needed to prepare a system for
assembly and transfer to the consumer site. Thus, the release activity must determine the
resources required by a software system to correctly operate at the consumer site. It must
also collect the information that is necessary for carrying out subsequent activities of the
deployment process. This information may be derived from a variety of sources including
the development process itself and human knowledge about the system structure and
operation. The release activity includes packaging the system so that it can be transferred to
the consumer
site. This package must contain the system components, a description of the system,
including its requirements and the dependencies on other external components, the
deployment procedures, and all the information that is relevant for the management of the
system at the consumer site.

Another step in the release activity is advertising, i.e., the set of operations that are needed
to disseminate appropriate information to interested parties about the characteristics of the
system being released.

Install: The installation activity covers the initial insertion of a system into a consumer site.
Usually, it is the most complex of the deployment activities because it deals with the proper
assembly of all the resources needed to use a system. It is also currently the activity best
supported by specialized tools.
Installation involves two distinct sub-activities. The first one is the transfer of the product
from the producer site to the consumer site. The second one consists of all the configuration
operations that are necessary to make the system ready for activation on the consumer site.

Activate: Activation is the activity of starting up the executable components of a system. For
a simple system, activation involves establishing some form of command (or clickable
graphical icon) for executing the binary component. For a complex system, it might be
necessary to start servers or daemons before the software system itself is activated. Note
that any of the activities of the deployment process might require the activation of other
systems in support of that activity, which in turn might require recursive deployment of
those support systems. For example, if a system has been packaged as an archive file, the

Page 226 of 228


installation procedure must be able to activate the archive tool to extract the pieces of the
system to be
installed. If the archive tool is not available, then a recursive deployment of the archive tool
would be required.

Deactivate: Deactivation is the inverse of activation, and refers to the activity of shutting
down any executing components of an installed system. Deactivation is often required
before other deployment activities, such as update, can commence.

Update: The process of updating a version of a system is a special case of installation.


However, it is usually less complex because it can often rely on the fact that many of the
needed resources have already been obtained during the installation process. Typically, the
deployment life cycle includes an iteration where a system is deactivated, a new version is
installed, and then the system
reactivated. For some systems, deactivation may not be necessary and update can be
performed while a previous version is still active. Similar to installation, update also includes
the transfer and configuration of the components needed to complete the operation.

Adapt: The adaptation activity, like the update activity, involves modifying a software
system that has been previously installed. Adaptation differs from update in that the update
activity is initiated by remote events, such as a software producer releasing an update,
whereas adaptations are initiated by local events, such as a change in the environment of
the consumer site. An adaptation
activity may be initiated to take corrective action to maintain the operational correctness of
the deployed software system.

Deinstall: At some point a system as a whole is no longer required at a given consumer site
and can be removed. Of course, deinstallation presumes the system is also deactivated. The
deinstallation activity possibly involves some reconfiguration of other systems in addition to
the removal of the deinstalled system’s files.There is a critical issue of properly deinstalling
systems that were installed as a result of deploying the system. In particular, subsequent
dependencies may arise that must be taken into account
by the deinstallation activity.

Derelease (Retire): Ultimately, a system is marked as obsolete and support by the producer
is withdrawn. As with deinstallation, care must be taken to ensure that the withdrawal will
not cause difficulties. This requires that the withdrawal be advertised to all known
consumers of the system.

Page 227 of 228


References
1. Quentin Docter, Emmett Dulaney, Toby Skandier (2016) CompTIA A+ Complete Study
Guide: Exams 220-901 and 220-902 3rd Edition USA: Sybex.
2. Wendell Odom (2012) CCENT/CCNA ICND1 640-822 Official Cert Guide, Third edition
USA: Cisco Press
3. IEEE Standard for Information technology—Telecommunications and information
exchange between systems—Local and metropolitan area networks—Specific
requirements. Part 2: Logical Link Control. New York: The Institute of Electrical and
Electronics Engineers. May 7, 2008.
4. Wikipedia. Org, IEEE 802.3. Retrieved from https://en.wikipedia.org/wiki/IEEE_802.3
5. Wikipedia. Org, Token Ring. Retrieved from
https://en.wikipedia.org/wiki/Token_ring
6. Wikipedia. Org, IEEE 802.6. Retrieved from https://en.wikipedia.org/wiki/IEEE_802.6
7. Home network help, What are Straight and Crossover cable. Retrieved from
http://www.home-network-help.com/straight.html
8. Multicom, Single Mode vs. Multi-Mode Fibre Optic Cable. Retrieved from
http://www.multicominc.com/training/technical-resources/single-mode-vs-multi-
mode-fibre-optic-cable/
9. FIS, Fibre Optic Connector Guide. Retrieved from
http://www.fibreinstrumentsales.com/fibre-optic-product-directory/fibre-optic-
connectors
10. Wikipedia. Org, Apple filling protocol. Retrieved from
https://en.wikipedia.org/wiki/Apple_Filing_Protocol
11. RFC2616, Hypertext Transfer Protocol. Retrieved from
https://tools.ietf.org/html/rfc2616
12. EFF, HTTPS everywhere. Retrieved from
13. https://www.eff.org/https-everywhere/faq
14. RFC4252, SHH. Retrieved from
15. https://tools.ietf.org/html/rfc4252
16. WiseGeek, What is a Logical Network Diagram? Retrieved from
17. http://www.wisegeek.org/what-is-a-logical-network-diagram.htm

Page 228 of 228

Potrebbero piacerti anche