Documente Academic
Documente Profesional
Documente Cultură
SOF535
Application Design and Development
20 Credits
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.
Level 5
Number of credits 20
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.
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:
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.
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.
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:
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
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.
Development can be divided into smaller parts and the risky parts can be developed earlier
which helps in better risk management.
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 −
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 −
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.
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.
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.
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 Engineering
The process to gather the software requirements from client, analyze and document them is
known as requirement engineering.
Feasibility Study
Requirement Gathering
Software Requirement Specification
Software Requirement Validation
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.
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.
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.
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.
Interviews
Interviews are strong medium to collect requirements. Organization may conduct
several types of interviews such as:
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.
Clear
Correct
Consistent
Coherent
Comprehensible
Modifiable
Verifiable
Prioritized
Unambiguous
Traceable
Credible source
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 -
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.
Security
Logging
Storage
Configuration
Performance
Cost
Interoperability
Flexibility
Disaster recovery
Accessibility
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.
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 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.
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.
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.
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.
delayFlight N/A
Name Type
numberOfMinutes Minutes
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
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.
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.
Indicator Meaning
1 One only
* Zero or more
3 Three only
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.
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.
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.
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.
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.
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.
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
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?
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:
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
Computer Science
Cognitive Psychology
Social Psychology
Ergonomics/Human Factors
Linguistics
Artificial Intelligence
Philosophy, Sociology & Anthropology
Engineering & Design
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:
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.
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.
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.
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.
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.
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
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)
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.
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.
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.
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.
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 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:
User Focus
As we’ve already said, the start of any interaction design exercise must be the
Page 61 of 228
“Know your users”
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.
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.
Page 62 of 228
Aesthetics and utility
Making a mess of it: color and 3D
Localization / internationalization
Role of prototyping
From this we can see that there are two things you need in order for prototyping methods
to work:
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.
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
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
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.
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
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
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.
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 .
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 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.
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.
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#.
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#.
*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
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 –
following steps:
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.
Depending on whether the year is a leap year, divide the total by 366 or 365,
respectively can be converted to the following pseudocode –
else
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.
* 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:
}
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.
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.
Polymorphism
Polymorphism means one name, many forms.
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 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.
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
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/
*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.
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.
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.
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.
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:
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
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
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.
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.
Basic Syntax
Identifiers and Keywords
Identifiers are names that programmers (yes that’s you!!) choose for their classes, methods,
variables, and so on.
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
volatile while
Contextual Keywords
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);
}
}
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
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):
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.
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.
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;
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-
Numeric suffixes
Numeric suffixes explicitly define the type of a literal. Suffixes can be either lower- or
uppercase, and are as follows:
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
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.
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.
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++.
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:
using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
double d = 5673.74;
int i;
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;
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.
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.
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.
Type Example
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:
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.
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:
/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b,
c);
Console.ReadLine();
}
}
}
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";
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:
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;
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:
== 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.
<= 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.
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");
}
}
}
&& 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.
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");
}
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 = 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:
& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) = 12,
which is
0000 1100
^ 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
<< 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
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; /* 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);
= 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
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#.
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;
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.
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
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.
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
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
Selection Statements
C# has the following mechanisms to conditionally control the flow of program execution:
Iteration Statements
C# enables a sequence of statements to execute repeatedly with the while, do-while, for,
and foreach statements
Jump Statements
The C# jump statements are break, continue, goto, return, and throw.
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.
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();
}
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 {}
}
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!
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.
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.
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.
1. On the menu bar, choose File, New, Project. The dialog box should look like this –
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.
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.
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.
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.
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.
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.
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
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
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.)
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.
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
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
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
1. Choose the Windows Forms Designer (Form1.cs [Design] or Form1.vb [Design]) and
then open the Dialogs group in the Toolbox.
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):
f. The Filter property settings specify the kinds of file types that will display in
the Select a picture file dialog box.
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.
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.
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
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.)
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
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.
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.
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.
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.
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:
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:
or simply:
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.
Had Point been a class, creating the array would have merely allocated 1,000 null
references:
To avoid this error, we must explicitly instantiate 1,000 Points after instantiating the array:
An array itself is always a reference type object, regardless of the element type. For instance, the
following is legal:
int[] a = null;
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,
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;
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.
}
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:
The GetLength method of an array returns the length for a given dimension (starting at 0):
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:
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:
A jagged array can be initialized as follows (to create an array identical to the previous example with
an additional element at the end):
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.
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.
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
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
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.
IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.
The following table lists some of the commonly used methods of the ArrayList class:
Sr.No. Methods
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;
};
/* 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;
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
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.
C# provides following types of decision making statements. Click the following links to check their
detail.
<Table no.>
Statement Description
nested if statements You can use one if or else if statement inside another if or else
if statement(s).
nested switch statements You can use one switch statement inside
another switch statement(s).
The if statement
if (5 < 2 * 3)
Console.WriteLine ("true"); // true
if (5 < 2 * 3)
{
Console.WriteLine ("true");
Console.WriteLine ("Let's move on!");
}
The else clause
if (2 + 2 == 5)
if (2 + 2 == 5)
Console.WriteLine ("Does not compute");
else
if (2 + 2 == 4)
Console.WriteLine ("Computes"); // Computes
if (true)
if (false)
Console.WriteLine();
else
Console.WriteLine ("executes");
if (true)
{
if (false)
Console.WriteLine();
else
Console.WriteLine ("executes");
}
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)
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.
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:
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:
switch (cardNumber)
{
case 13:
case 12:
case 11:
Console.WriteLine ("Face card");
break;
default:
Console.WriteLine ("Plain card");
break;
}
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
for loop It executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
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.
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:
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:
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:
The following prints the first 10 Fibonacci numbers (where each number is the sum of the previous
two):
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");
OUTPUT:
c
o
o
l
• 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 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 forgoes the remaining statements in a loop and makes an
early start on the next iteration. The following loop skips even numbers:
OUTPUT: 1 3 5 7 9
The goto statement transfers execution to another label within a statement block.
The form is as follows:
goto statement-label;
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 return statement exits the method and must return an expression of the method’s return type if
the method is nonvoid:
if (w == null)
throw new ArgumentNullException (...);
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
ClassB exposes field x to other types in the same assembly; ClassA does not:
class BaseClass
{
void Foo() {} // Foo is private (default)
protected void Bar() {}
}
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:
Method Body
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.
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
int result;
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
int result;
result = num1;
else
result = num2;
return result;
int a = 100;
int b = 200;
int ret;
Console.ReadLine();
When the above code is compiled and executed, it produces the following result:
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
int result;
result = num1;
else
result = num2;
return result;
class Test
int a = 100;
int b = 200;
int ret;
Console.ReadLine();
When the above code is compiled and executed, it produces the following result:
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
int result;
if (num == 1)
return 1;
else
return result;
Console.ReadLine();
When the above code is compiled and executed, it produces the following result:
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.
Output parameters This method helps in returning more than one 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;
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;
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;
}
}
}
}
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();
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:
// member variables
...
// member methods
// method body
// method body
...
// method body
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.
using System;
namespace BoxApplication
class Box
class Boxtester
// box 1 specification
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 of box 2
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;
class Box
length = len;
breadth = bre;
height = hei;
class Boxtester
double volume;
// 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();
// volume of box 2
volume = Box2.getVolume();
Console.ReadKey();
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
public Line()
length = len;
return length;
line.setLength(6.0);
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
length = len;
length = len;
return length;
line.setLength(6.0);
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
using System;
namespace LineApplication
class Line
~Line() //destructor
length = len;
return length;
line.setLength(6.0);
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
using System;
namespace StaticVarApplication
class StaticVar
num++;
return num;
class StaticTester
s1.count();
s1.count();
s1.count();
s2.count();
s2.count();
s2.count();
Console.ReadKey();
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
num++;
return num;
class StaticTester
s.count();
s.count();
Console.ReadKey();
When the above code is compiled and executed, it produces the following result:
Variable num: 3
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.
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)
void print(double f)
void print(string s)
p.print(5);
p.print(500.263);
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:
namespace PolymorphismApplication
length = a;
width = b;
class RectangleTester
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
width = a;
height = b;
return 0;
class Caller
int a;
a = sh.area();
class Tester
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
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
{
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
try: A try block identifies a block of code for which particular exceptions is activated. It is
followed by one or more catch blocks.
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
catch( ExceptionName e1 )
catch( ExceptionName e2 )
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
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;
try
catch (DivideByZeroException e)
finally
d.division(25, 0);
Console.ReadKey();
When the above code is compiled and executed, it produces the following result:
at ...
Result: 0
using System;
namespace UserDefinedException
class TestTemperature
try
temp.showTemp();
catch(TempIsZeroException e)
Console.ReadKey();
int temperature = 0;
if(temperature == 0)
else
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
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
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.
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:
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
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).
Another way of providing information is through online help, such as tips, handy hints, and
contextualized advice.
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.
What is a prototype?
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.
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.
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.
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.
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.
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.
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
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.
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
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
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 –
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
The goal here is to quantify and qualify threats. We will be discussing this
phase in detail in the following section.
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:
• 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
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:
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.
Testing Objectives
In an excellent book on software testing, Glen Myers [MYE79] states a number of
rules that can serve well as testing objectives:
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.
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:
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
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.
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.
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.
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
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.
[Provide a brief description of the outputs from the module under test.]
2. Test Data
[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
case should be numbered, indicate the nature of the test to be performed and the expected
proper outcome.]
[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.]
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
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
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.
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
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.
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.