Anda di halaman 1dari 206

Chapter 1

Introduction to the Object-Oriented Approach


Object-Oriented Programming (OOP) is one of the most popular methodologies in software
development. It offers a powerful model for creating computer programs. It speeds the program
development process, improves maintenance, and enhances reusability of programs.
his chapter introduces object-oriented methodology and discusses the concepts of objects,
classes, messages, and methods. It provides an overview of the phases involved in object-
oriented analysis and design. his chapter also e!plains how to define classes in "#.
Objectives
In this chapter, you will learn to$
%!plain features of the object-oriented methodology
&escribe the phases of the object-oriented methodology
&efine classes in "#
Object-Oriented Methodology
Object-orientation is a software development methodology that is based on modeling a real-world
system. 'n object is the core concept involved in object orientation. 'n object is the
representation of a real-world entity or concept. (or e!ample, an employee, a window, a car, or a
bird can be modeled as objects. )ou can thin* of an object-oriented model as a collection of
objects and their inter-relationships.
The Foundation of Object-Orientation
Object-orientation is a type of methodology used for building software applications. 'n object-
oriented program consists of classes, object, and methods.
If you were as*ed to create a classroom, you will start by creating a room and defining its
boundaries and features. +e!t, you will put together all the components, such as chairs, tables,
and boo*s. ,imilarly, if you want to create an aircraft or a high-rise building, you can do so by
putting together several components or parts. hese components or parts are analogous to
objects in the objected-oriented methodology.
he object-oriented methodology in software development revolves around a single concept
called the object. ,oftware is developed by brea*ing the application into component objects.
hese objects interact with each other when the whole application is put together.
'n object is a combination of messages and data. Objects can receive and send messages and
use messages to interact with each other. he messages can contain information that is to be
passed to the recipient object.
Object
'n object literally means a -material thing. that is capable of being presented to the senses. (or
our purpose, an object is a tangible entity that may e!hibit some well-defined behavior. (or
e!ample, let us consider a tennis ball$
' tennis ball is a tangible entity, with a visible boundary
' tennis ball has a specific defined purpose (such as bouncing)
)ou can direct a specific action towards a tennis ball by hitting it with a rac/uet or by
tossing it
0ut the definition of an object is not limited to merely something that can be seen, held and
touched, such as a tennis ball or a car. (or the purpose of software development, the definition of
an object needs refinement for e!ample, consider the 'cme +ut and 0olt "ompany1 'n
organi2ation does not have a visible boundary, unli*e a tennis ball. 3hile it does not possess a
physical boundary, it does have a conceptual boundary. 4i*e all organi2ations, it has a specific
defined purpose, and one can direct a specific action towards it. hus, the 'cme +ut and 0olt
"ompany is an object.
,tate, 0ehavior, and Identity of an object
'ccording to 5rady 0ooch, a renowned software architect, an object has the following
characteristics$
It has a state
It may display behavior
It has a uni/ue identity
he state of an object is indicated by a set of attributes and their values. (or e!ample, a chemical
can characteri2ed by it temperature, color and density. he behavior of a chemical refers to the
change of it attributes over a period of time. ' chemical also has state, such as solid, li/uid or
gas.
he preceding paragraph e!plains the first two points of the definition of an object by 5rady
0ooch 6'n object has state, e!hibits some well-defined behavior78. +ow, you will e!amine the
ne!t part of the definition 9 67and has a uni/ue identity.8
%ach object has a uni/ue identity and the identity of an object distinguishes the object from all
other objects.
(or e!ample, you can ta*e a car as an object. It can have states such as moving and stationary. It
can accelerate, decelerate, turn right, or turn left, which is it behavior. he car also has an identity,
such as a uni/ue registration number.
wo objects may have the same behavior and state, but they will never have the same identity.
he identity of an object does not change in its lifetime. (or e!ample, two tennis balls may have
the same color, be made of the same material, have the same weight and the same
circumference, and display the same behavior. :owever, they will have distinct identities (for
e!ample, one ball will have the factory seal number -';<=>?@A. and the other -,@A=@A@..
Just a minute
Identify the possible states of the following objects:
1. a cell phone
2. a stereo
Answer:
1. States of a cell phone: Off, Ring, Vibrate and Call
2. States of a stereo: lay, a!se, Rewind and "orward
Classes
4oo* at the world around you. It is full of objects of various shapes, si2es, colors and behavior.
(or e!ample, the earth is inhabited by millions of animals. ' 2oologist cannot do any meaningful
study of these objects without organi2ing this vast variety of animals found in the world in a logical
manner. hus, the 2oologists have classified animals into *ingdoms, genus, families and species.
'll animals and birds, which are essentially objects, can be classified on the basis of their
common attributes. (or e!ample, the peacoc*, the sparrow, and the *ingfisher are all birds. 'll of
them share characteristics that are common to the family of birds. 'll of them lay eggs, are
covered with feathers, have hollow bone structures and have the ability to fly. herefore, they
share structural and behavioral similarities and belong to the class of 0irds.
his is shown in the following figure$
(rom the preceding e!ample, you may define a class as a declaration, a template, or a blueprint
that can be used to classify objects. ,imilarly, 0oo* is a class and -5one with the wind. and
-(arewell to 'rms. are the objects of this class.
"onsider a video game that involves two players, om and Bar*, who fight with each other. om
chooses a shotgun and Bar* chooses a pistol as their weapons in the game. If you need to
create an object model for this game, you can identify a total of four objects. hey are om, Bar*,
the shot gun and the pistol.
he object ,hotgun belongs to the class (irearms. It has certain attributes that are common with
the pistol. :owever, a shotgun is a uni/ue object. 0oth the shotgun and the pistol are e!amples
or instances of firearms. herefore, the shotgun and pistol are objects of the same class, as
shown in the following figure.
Birds
Peacock Kingfisher Sparrow
The class - Birds
Messages and Methods
Objects do not e!ist is isolation. hey interact with other objects. hese interactions ta*e place
through messages. 5rady 0ooch has defined behavior as follows$
#$eha%ior is how an object acts and reacts, in ter&s of its state changes and &essage passing.'
In the e!ample of a video game, every time om attac*s, Bar* either attac*s or defends himself.
3hen om attac*s Bar*, Bar* receives a message and reacts to that message. he reaction can
be e!hibiting a particular behavior such as running, hiding, dodging, or fighting bac*. (or
e!ample, when om attac*s, Bar* receives a message 60eing 'ttac*ed8. Bar* responds to this
message by hiding. In this situation, hiding is a behavior e!hibited by Bar*. herefore, behavior
(also called method in object-oriented methodology) is simply a set of actions ta*en by the
receiving object in response to a message.
Just a minute
(r )a&es and *r. +yde went to the railway station to boo, tic,ets for -
rd
(ece&ber. .t the
railway station, they re/!ested the cler, at the tic,et co!nter to boo, 2 tic,ets for the "lying
01press in the first class. Identify the following:
1. 2he possible recei%er of the &essage in this sit!ation
2. 2he possible &ethod that the recei%er can !se
Answer
1. 2he recei%er of the &essage in this case will be the cler, at the tic,et co!nter.
2. 2he cler, will chec, if 2 tic,ets are a%ailable on the re/!ested train in the desired class
and for the desired date. If the tic,ets are a%ailable, the cler, will enter the details 3na&e,
age, depart!re date and seat4, confir& the reser%ation and collect the re/!ired fare.
Characteristics of the Object-Oriented Approach
's discussed earlier, an object has state, behavior and identity. 'n object is reusable. herefore,
an object e!ists as a stand-alone entity that can be used in any relevant conte!t. (or e!ample, if
you have a chair, you can use the same chair in an office, in a classroom, or in a garden.
Class: Firearms
Object: Pistol Object: Shotgun
Classes and Objects
'n e!isting object can be used to create a similar object. (or e!ample, you have a simple wooden
chair and you need to add a headrest to it. )ou do not need to create a new chair because you
can easily add a headrest to the e!isting chair. his is *nown as resilience to change.
Realistic Modeling
0ecause you live in a world of objects, it logically follows that the object-oriented approach
models the real world more accurately. he object-oriented approach allows you to identify
entities as objects having attributes and behavior. 'ttributes and behavior typically depict how the
objects acts and reacts. (or e!ample, the car is an object belonging to the class Cehicle. he car
has attributes such as speed, color, and power. It displays behavior such as being stationary,
moving slowly, or accelerating.
Reusability
In the software industry, using e!isting classes or objects from other applications saves resources
spent in recreating the classes from scratch. "onsider the following analogy$
"arcare is a leading car manufacturing company. "arcare manufactures D seater cars that are
very popular among the consumers aged between DE and D@. he company has decided to enter
the mar*et of family segment mar*et and has decided to manufacture a @ seater model.
"arcare can either design a new car for the family segment or convert the D seater model to @
seater model. he cost involved in designing a new model is very high as compared to the cost
involved in converting D seater model to @ seater model.
herefore, the management and the design team may decide to convert the D seater model into a
family segment model as shown in the following figure$
he preceding scenario depicts the concept of reusability that is supported by the object-oriented
approach. he process of creating a new class by adding some features to the e!isting class is
Two-seater Car
Attributes
Behaior
Four-Seater Car
Two-seater Car - Attributes
Two-seater Car - Behaior
!ew Attributes
!ew Behaior
Example of reusability
*nown as inheritance. he benefit of reusability translates to savings in time and effort, which in
turn results in cost benefits.
Just a minute
State whether the following sit!ations de&onstrate re!sability.
1. Recycling paper
2. !&p Re!sability 3sa&e p!&p is !sed in a well and in a f!el station4
Answer
1. It does not represent re!sability beca!se the !n!sable paper s destroyed before paper is
recycling for !se. 2he !sable paper loses its identity and cannot be considered the sa&e
as recycling paper.
2. It represents re!sability beca!se a p!&p can be !sed for s!ction of water as well as
petrol. It is not necessary to !se to the sa&e p!&p in both the cases. 2wo separate
&achines can be !sed beca!se both belong to the 5!&p6 class.
Resilience to change
he object-oriented approach allows system to evolve. 3hen a change is suggested, the old
system need not be completely abandoned. "onsider the e!ample of Foyoys, Inc, is a company
that manufactures toys for children in the age group of ; to ;D. Its car toys are popular with
children because of their attractive colors, shape and sound.
(or a couple of years, the company had no cause for complain about the design of the toy car.
:owever, due to the advancement in technology and increase in competition, the designers now
want to stop manufacturing the old car because the mar*et re/uirements have changed. hey
want the company to manufacture a car that has flashing lights and remotely controlled.
In the object-oriented system, this re/uirement does not mean that the new car needs to be build
from scratch. he new features can be easily incorporated in the old toy car without modifying the
color, shape and sound of the old toy car, as shown in the following figure$
Gesilience to change also results in easier maintenance. his feature of object-oriented
methodology is now *nown as e!tensibility. he ability of the class to inherit features from another
class also ma*es object-oriented programs more e!tensible. (or the same reason, even during
construction, parts of system under development can be refined without any major changes to
other parts.
Existence as ifferent for!s
Hsing the object-oriented approach, objects can be made to respond differently to the same
message. he response is decided upon based on the information or parameters provided with
the message.
+ote$ Information is passed as parameters in a function. (or a detailed functions and parameters,
refer the subse/uent chapters.
If a car collides against an object, the behavior of the car after the collision will depend on the
speed of the car, and the nature of the object that hit the car. (or e!ample, if the car collides with
another car at high speed, both the cars will be smashed and the drivers might get injured. On the
other hand, if a car collides with a street light at a low speed, the impact would be less. his
ability to react differently based on the information associated with the message is *nown as
polymorphism.
"hases of object-oriented !ethodology
0efore the actual development of any product, important steps such as analysis and design need
to be performed. he following phases are involved in the object-oriented methodology$
'nalysis Phase
&esign Phase
Implementation Phase
"onsider an aircraft manufacturing factory where a new jet liner is being assembled and several
competent engineers and wor* men are wor*ing with speciali2ed tools. "an you visuali2e them
wor*ing on pure intuition, grabbing the tools, and sitting down to wor* immediately1 Or, do you
see them wor*ing according to a detailed design, on which they have spent hundreds of hours,
and finally constructing the aircraft based on specific design.
(or the safety of millions of people who fly everyday, it is recommended to use a detailed design.
'fter all, it is comforting to *now that a lot of thought has gone into first ma*ing a model on a
paper and then translating the design into the physical jet liner. he same thing holds true for
almost any item that is constructed. ,imilarly, designers put pen to paper before attac*ing the
fabric with scissors. 'rchitects spend hours drawing layouts of buildings on blueprints before the
bric*s are laid.
herefore, the construction of software follows the same approach. he software industries still
rely mainly on the paper-and-pencil approach in the upstream development phases.
It is this paper-and-pencil approach that is termed analysis and design. o analy2e and design a
system, you need to build a model of the system. he model is simpler than the system that is
finally constructed. 'll the practical aspects of building a system for the real world can not be
reflected in the design. :owever, this does not undermine the importance of design.
Analysis "hase
#2he p!rpose of analysis is to pro%ide a description of a proble&. 2he description &!st be
co&plete, consistent, readable, and re%iewable by di%erse interested parties, and testable
against reality' 7 *ellor
he analysis or the object-oriented analysis (OO') phase considers the system as a solution to a
problem in its environment or domain. 0roadly, analysis is a phase where users and developers
of the system get together and arrive at a common understanding of the system. One of the end
products of the analysis phase is the specification on how a system functions.
In the analysis phase, the developer concentrates on obtaining as much information as a possible
about the problem. he developer has to identify the critical re/uirements. 'nalysis therefore
involves meeting and interviewing the concerned persons to understand systems that are
currently in operation, and identifying all the causes of problems (if any) in the current system.
The esign "hase
In the design phase, the developers of the system document their understanding of the system.
&esign generates the blue print of the system that is to be implemented.
he first step in creating an Object -Oriented &esign (OO&) is the identification of classes and
their inter-relationships.
3or* in the design phase of software development is comparable to the wor* of an architect. he
architect will need to create a blue print or a model of the building before the construction of the
building starts.
The #!ple!entation "hase
he design phase is followed by OOP, which is implementation phase. OOP provides
specifications for writing programs in a programming language. One on the most popular
languages used to write object-oriented programs "#.
&uring the implementation phase, programming is done as per the re/uirements gathered during
the analysis and the design phases.
Bany of the modern applications are built by using OOP. &eveloping comple!, large-scale
business systems can be simplified by using OOP techni/ues. ,ome of the applications that can
be built by using OOP techni/ues are "omputer 'ided &esign ("'&), "omputer 'ided
Banufacturing ("'B), and Object-Oriented &atabases.
Just a minute
.s a &e&ber of a tea& that is de%eloping software for (ialCo& 2eleco&&!nications, Inc., yo!
ha%e been assigned the tas, of creating a software &od!le that accepts and displays c!sto&er
details s!ch as na&e, age, and phone n!&ber. Identify the class that yo! will create and the
&ethods of the class.
Answer:
.s per the proble& state&ent, the class re/!ired is:
C!sto&er
2he class sho!ld ha%e the &ethods to:
.ccept c!sto&er details
(isplay c!sto&er details
#ntroducing C$
"omputer languages have come a long way since ;=@Es. 0ac* then, scientists punched
instructions into the mammoth, room-si2ed computer systems. hese instructions were long
series of 2eros and ones. hese machine language instructions are called the first generation of
computer languages.
he ;=AEs saw the emergence of second generation of computer languages 9 assembly
language 9 easy to write than the machine language but still e!tremely complicated for a common
man. :owever, the computer could still understand only machine language. herefore, the
assembler software was developed to translate the code written in assembly language to
machine language.
In ;=I>, Bartin Gichard developed a language called 0P"4, for writing operating systems. 'n
Operating system is a set of programs that manages the resources of a computer and its
interactions with users. he era of the third generation computer languages had arrived. In ;=>E,
Jen hompson modified 0P"4 to create a new language called 0. 3hile wor*ing for 0ell
laboratories, hompson teamed up with &ennis Gitchie and wrote an early version of H+IK
operating system for a &%"-P&P-> computer.
&ennis Gitchie was wor*ing on a project to further develop the H+IK operating system. :e
wanted a low level language li*e assembly language that could control hardware efficiently. 't the
same time, he wanted the language to provide the features of a high level language, that is, it
should be able to run on different types of hardware. 0 had performance draw bac*s, so in ;=>D
he rewrote 0 and called it ". herefore, " is categori2ed as both a second and third generation
language. hompson and Gitchie rewrote the H+IK operating system in ". In the years that
followed " was widely accepted and used over different hardware platforms. his led to many
variations of ". In ;=<=, the .&erican 8ational Standard Instit!te 3.8SI4, along with international
standards organi2ation (I,O), approved a machine-independent and standard version of ".
In the early ;=<Es, 0ijarne ,troustrup of 0ell 4aboratories developed the "LL language. In his
own words, 6"LL was designed primarily so that m friends and I would not have to program in
assembly, ", or various modern high-level languages. Its main purpose was to ma*e writing good
programs easier and more pleasant for the individual programmer.8
"LL was originally *nown as -" with classes., because D languages contributed to its design 9 ",
which provided low level features and ,imula I>, which provided the class concept. "LL is an
object-oriented language. Other object-oriented languages are Fava, ,malltal*, and "#.
"#, also *nown as "-,harp, is a programming language introduced by Bicrosoft. "# contains
features similar to Fava and "LL. It is specially designed to wor* with Bicrosoft.s .+% platform.
+ote$ 2he .802 platfor& is ai&ed at pro%iding internet !sers with web9enabled interface for
applications and co&p!ting de%ices, s!ch as &obile phones. It also pro%ides de%elopers, the
ability to create re!sable &od!les, thereby increasing prod!cti%ity.
Co!pilers
'll languages have a vocabulary, which is a list of words that have a specific meaning in that
language. 4anguages also have their own grammar rules, which state the rules for combing
words to form sentences. hat is what ensures that whatever is spo*en in particular language is
interpreted by all people to understand the language. ,imilarly, programming languages also
have vocabulary, which is referred to as a set of *eywords of that language, and a grammar,
which is referred to as synta!.
&oes this mean that computers can directly interpret the instructions written in any programming
languages1 +o, they cannot. hen, how do you ensure that a computer e!ecutes the instructions
from a program as intended1 3hat would you do if you got hold of a receipe for a delicious dish
written in foreign language that you do not understand1 )ou would get it translated to %nglish or
any other language you understand to be able to prepare the dish. ,imilarly, you need a
translator to convert the instructions written in a programming language to machine language.
' compiler is a special program that processes the statements written in particular programming
languages and converts them into machine language. 4i*e everything else in the computer, the
compiler also follows the input-process-output (IMPMO) cycle. It ta*es programming language
instructions as input. hese instructions can be e!ecuted by the computer. his process of
conversion is called compilation. (or each programming language, there is different compiler
available. (or e!ample, for compiling a program written in the " language, you re/uire a "
compiler. (or a Fava program, you re/uire a Fava compiler. (or "# programs, you will use the
"," compiler.
)ou will now learn to create classes in the "# language.
Classes in C$
"onsider the following code e!ample which defines a class$
Public class :ello
N
public static void Bain(stringOP args)
N
,ystem."onsole.3rite4ine(6:elloQn8)R
S
S
he preceding class declaration provides a method Bain() that will display the message 6:ello8
on your screen. he parts of the preceding code need to be e!amined.
The Main%& function
he first line of the code that a "# compiler loo*s for in the source file compiled is the Bain
function. his function is the entry point of the application.
he main function is ideally used to create objects and invo*e member function.
The Class 'ey(ord
he class *eyword is used to declare a class. Jeywords are reserved words that have a special
meaning. :ere, the class *eyword defines the class :ello. he braces, *nows as delimiters, are
used to indicate the start and end of the class body.
%!ample$
"lass :ello
N
777.
7.
7..
S
The class na!e
he class *eyword is followed by the name of the class. In the preceding e!ample, :ello is the
name of the class defined by using the class *eyword. 3hen you create classes, you must
consider the following naming conventions and rules.
"lass +aming "onventions in "#
"lass name should follow certain naming conventions are guidelines. ' class name$
,hould be meaningful (strongly recommended)
,hould ideally be a noun.
"an use either the Pascal case or the "amel case. In Pascal case, the first letter is
capitali2ed and the rest of the letters are in lower case, such as Byclass. In camel case,
the first letter is in the lower case and the first letter of each subse/uent word is
capitali2ed, such as my"lass.
Gules for naming classes in "#
+ame of classes$
Bust begin with a letter. his letter may be followed by a se/uence of letters, digits (E-=),
or 6M8. he first character in a class name cannot be a digit.
Bust not contain any embedded space and any symbol li*e 1 - L T U # V W U X ( ) N S
O P $ . R 6 - Y Q. :owever, an underscore 6M8 can be used wherever a space is re/uired.
Bust not use a *eyword for a class name. (or e!ample, you cannot declare a class.
)yste!*Console*+rite,ine%&
"onsole is a class that belongs to the system namespace. ' namespace is a collection of
classes. he system namespace contains the method 3rite4ine(), which displays the enclosed
te!t on the screen. he console class has other methods, which are used for various inputYoutput
operations. he character(.) is used to access the function, 3rite4ine(), which is coded in the
console class of the system namespace.
he preceding line can also be written as "onsole.3rite4ine() is the statement using system is
included as the first line of code.
he following code is an e!ample "onsole.3rite4ine ( ) $
"onsole.write4ine(6:ello world Qn8)R
he preceding code will display on the screen.
:ello 3orld
The Escape Characters
o display special characters such as the new line character or the bac*space character, you
need to use escape characters.
he following table lists the escape characters used in "#.
Escape
Sequence
Character Name
:6 Single /!otation &ar,
:' (o!ble /!otation
&ar,
:: $ac, slash
:; 8!ll
:a .lert
:b $ac, Space
:f "or& "eed
:n 8ew line
:r Carriage ret!rn
:t +ori<ontal tab
:% Vertical tab
2he 0scape Characters
%!ample of +ew line escape se/uence
"onsole.3rite4ine(6 :ello Qn world8)R
he preceding code will display the following message on the screen$
:ello
3orld
Activity- creating Classes
"roble! state!ent
's a member of a team that is developing for Foyoys, inc., you have been assigned the tas* of
creating a bi*e module that accepts and displays bi*e details. &eclare the 0i*e class and its
member functions. he member function that accepts bi*e details should display the message 6
'ccepting 0i*e &etails8. ,imilarly, the member function to display bi*e details on the screen
should display the message 6 &isplaying 0i*e &etails8.
)olution
he following code will create the 0i*e class with the re/uired functions$
class 0i*e
N
void 'ccept0i*e&etails()
N
"onsole.3rite4ine(Z'ccepting 0i*e &etailsQnZ)R
S
void &isplay0i*e&etails()
N
"onsole.3rite4ine(Z&isplaying 0i*e &etailsQnZ)R
S
S
"ractice .uestions
;. 3hich of the following is not a class1
a. ' (ord I*on car with the registration number KKKK
b. (ruit
c. Bammal
d. (ish
D. 3hich method displays the message 6:ello People8 on the screen1
a. "onsole.3rite4ine(Z:ello PeopleZ)R
b. ,ystem.3rite4ine(Z:ello PeopleZ)R
c. "onsole(Z:ello PeopleZ)R
d. "onsole.writeline(Z:ello PeopleZ)R
?. "onsole is a MMMMMMMMMMMMMM.
a. +amespace
b. "lass
c. (unction
d. %scape ,e/uence character
@. In a "# program, which is the first function to be e!ecuted1
a. Bain()
b. Bain()
c. "onsole.3rite4ine()
d. void 'ccept0i*e&etails()

A. 3hich of the following is used to denote a newline character1
a. Qb
b. Qn
c. Qv
d. Yn
)u!!ary
In this chapter, you learned that
'ccording to the object-oriented approach, systems consist of component objects that
interact with each other.
'n object is an entity that may have a physical boundary. :owever, it should have the
following characteristics$
o ,tate
o 0ehavior
o Identity
' class consists of a set of objects that share a common structure and behavior
If an object desires an action from another object, it sends a message to that object.
he object that receives the message is called the receiver, and the set of actions ta*en
by the receiver constitutes the method.
he features of the object-oriented approach are$
o Gealistic modeling
o 0inding attributes and behavior together
o Geusabilty
o Gesilience to change
o %!istence as different forms
' model of a system is built in the stages of analysis and design.
he purpose of the model is to help developers understand the reality that they are trying
to imitate
In "#, a class is created by using the *eyword class. It is identified by a name called the
class name.
he console.3rite4ine( ) method is used to display te!t on the screen
Bain( ) is first function which is e!ecuted in a "# program
%scape characters are used to display special characters such as the newline character.
Exercises
Exercise /
'naly2e the process of ma*ing a call by using a pay phone. Identify the objects involved and
the behavior of these objects. 'lso, identify the messages passed between the objects for
interacting with each other.
Exercise 0
's a member of a team that is developing an automated ran*ing system of players in video
game parlors, you have been assigned the tan* of creating a module that accepts the details
of the player after a game is over &eclare a class player, which consists of three member
functions$ 'cceptPlayer&etail ( ) , "omparePlayer&etail ( ), and PrintPlayerGan* ( ).%ach of
these functions should print the appropriate message on the screen.
Chapter 0
Creating Objects
'n object is an instance of a class. )ou create objects to access member variables and member
functions of a class.
he chapter discusses how to declare variables. It also discusses how to write and e!ecute and
e!ecute "# program
.
Objectives
In this chapter, you will learn to$
&eclare variables
3rite and e!ecute "# programs
eclaring 1ariables
' %ariable is a location in the memory that has a name and contains a value. he value could be
an integer, such as D>, a decimal, such as =.<A, or a character, such as -4.. ' variable is
associated with the data type that defines the type of data, which can be stored in a variable. (or
e!ample, a variable called ennisPlayer+ame will ideally store characters, whereas a variable
called :ighM,core will store numbers. ' program refers to a variable by its name.
2a!ing 1ariables in C$
he following rules are used for naming variables in "#$
Bust begin with a letter or an underscore(-M.), which ay be followed by a se/uence of
letters, digits(E-=), or underscores. he first character in a variable name cannot be a
digit.
,hould not contain any embedded spaces or symbols such as 1 T [ # L - V W U X ( ) O P N S
. , R $ 6 - Y and Q. :owever, an underscore can be used wherever a space is re/uired, li*e
highMscore.
Bust be uni/ue. (or e!ample, to store four different numbers, four uni/ue variable names
need to be used. Hppercase letters are considered distinct from lowercase letters.
"an have any number of characters.
Jeywords cannot be used as variables names. (or e!amples, you cannot declare a
variable named class because it is a *eyword in "#.
he following are e!amples of valid variables names$
5ameMlevel
:ighMscore
hisMvariableMnameMisMveryMlong
he following are e!amples of invalid names$
# score
Dstran*
+ote$
C= is a case9sensiti%e lang!ages. 2his &eans that the %ariable 2ennislayer8a&e is not the
sa&e as the %ariable tennisplayerna&e.
&eclaring and Initiali2ing Cariables
)ou can declare and initiali2e variables by using the following synta!$
\dataMtype] \variableMname] ^ \value]
In the preceding synta!, the \dataMtype] represents the *ind of data type that will be stored in a
variable and \value] specifies the value that needs to be stored in a variable.
"onsider the following statement of variable declarations$
int ageRR
he preceding statement declares the variable age of the int data type and initiali2ing the variable
with the value E. he int data type is used to store numeric data.
"onsider the following statement$
char choice ^ _y_R
he preceding statement declares the variable choice of the char data type and initiali2ing the
variable with the value y.
he data type represents the *ind of data that will be stored in a variable.
&ata ypes in "#
"# provides various built-in data types. 0uilt-in data types are the predefined data types.
he following table lists some of the built-in data types.
Predefined Type # Bytes Range f !a"ues
char 2 ; and >??-?
int @ 92, 1@A, @B-, >@B and 2, 1@A, @B-, >@A
float @ 9-.@;2B2-0C-B and 91.@;12DB09@? 3"or negati%e
%al!es4
1.@;12DB09@? and -.@;2B2-0 C -B 3"or positi%e
%al!es4
do!ble B 91.ADA>D-1-@B>2-20-;B to 7 @.D@;>?>@?B@12@A09
-2@ 3for negati%e %al!es4 and @.D@;>?>@?B@12@A09-2@
to 1.ADA>D-1-@B>2-20-;B 3for positi%e %al!es4
bool 1 2r!e or "alse
string Variable length ;92 billion Enicode characters
$!ilt9In (ata 2ypes
0uilt-in data types are represented at the machine level. he storage re/uirement, therefore,
depends on the hardware. he #0ytes column in the preceding table depicts the bytes re/uired to
store the value in the memory.
2ote
C= also pro%ides !ser9defined data types. Fo! will learn abo!t !ser9defined data types in
s!bse/!ent chapters.
Types of ata Types
"# supports D types of data types. he types of data types supported by "# are$
Calue ypes$ hey directly contain data. ,ome e!amples of the value types are char, int and float,
which can be used for storing alphabets, integers, and floating point numbers, respectively. 3hen
you declare an variable int, the system allocated memory ti store the value. he following figure
shows the memory allocation of an int variable.
Geference types$ he types do not maintain data but theycontain reference to the variables,
which are stored in memory. Hsing more than one variable, you can use reference types to refer
to a memory allocation of a string value 6 :ello8 in a variable named str.
Table 0*3 creating objects
In the preceding figure, the value of the variable ,tr is stored in memory and the address of this
memory is stored at another location.
Accepting and storing 1alues in Me!ber 1ariables
o understand how to store value in variable, consider the following code snippet.
Int +umberR
+umber ^ "onvert.oInt?D("onsole.Gead4ine ( ) )R
In the preceding code snippet, the "onsole.read4ine ( ) is used to accept input from the user and
store it in the number variable. "onsole.Gead4ine( ) is a function of the console class, which is a
part of the system namespace.
he "onvet.oInt?D( ) converts the data entered by the user to the int data type.)ou need to
perform conversion because "onsole.Gead4ine( ) accepts the data in string format. he "onvert
( ) method e!plicitly tells the compiler to convert one data tpe to other data type. his is called
e!plicit conversion. he complier performs an implicit conversion automatically. (or e!ample,
implicit conversion converts the int data type to float or float data type to int, automatically,
3riting and e!ecuting a "# program
In this section you will learn to write, compile and e!ecute a "# program.
"reating a sample "# program
' "# program can be written by using +otepad. "onsider the following code, which declares a
car class and created the object By"ar of the same class$
using ,ystemR
class "ar
N
int !um"
!um # $"
$
!um
%emor& allocated
Memory Allocation in Value Type
YYBember Cariables
string %ngineR
int +oOf3heelsR
YYBember (unctions
public void 'ccept&etails()
N
"onsole.3rite4ine(Z%nter the %ngine Bodel$Z)R
%ngine ^ "onsole.Gead4ine()R
"onsole.3rite4ine(ZQn%nter the number of 3heels$Z)R
+oOf3heels ^ "onvert.oInt?D("onsole.Gead4ine())R
S
public void &isplay&etails()
N
"onsole.3rite4ine(Z%nter the %ngine Bodel$NESZ, %ngine)R
"onsole.3rite4ine(ZQn%nter the number of 3heels$NESZ, +oOf3heels )R
S
S
YY"lass used to instantiate the "ar class
class %!ecute"lass
N
public static void Bain()
N
"ar c ^ new "ar()R
c.'ccept&etails()R
c.&isplay&etails()R
S
S
he output of the preceding code is as follows$
he using *eyword
(irst statement in a typical "# program is$
using ,ystemR
he using *eyword is used to include the namespaces in the program. Jeywords are reserved
words that have a special meaning. he statement, using ,ystem, declares that you can refer to
the classes defined in the namespace without using the fully /ualified name. ' program can
include using statements.
he class Jeyword
he class *eyword is used to declare a class. In the preceding code, the class *eyword defines
the class car. he braces, *nown as delimeters, are used to indicate start and end of the class
body.
he comment %ntry
"omments are a part of the program and are used to e!plain code. "ompilers ignore comment
entries. he following symbols are use to give a comment entry in "#$
YY "omment e!t
Or
YX his is the sample program to display addition of two numbers
"omment te!t XY
If a comment entry spans more than one line, it has to be enclose within -YX. and -XY.. he symbol
-YY. treats the rest of code within the same line as a comment.
Bember Caraibles
Cariables are used to store data. Cariables are also called the data members of a class. In the
preceding code, class car has two member variables called engine and +oOf3heels. hese
member variables can be used to store data for a car.
Bember (unctions
' f!nctions is a set of statements that performs a specific tas* in response to a message. he
functions of a class are called member functions in "#. member functions are declared inside the
class. he function declaration introduces the function in the class and the function defenition
contains the function code.
he preceding code contains two member functions named 'ccept&etails and &isplay&etails.
hese are declared and defined inside the class. +otice, the function definition contains code,
which enclosed in a bloc*. he bloc* is enclosed withon braces -( )..
Instantiating "lass
In the preceding code, the %!ecutive"lass class is declared with the Bain ( ) method. he
%!ecutive"lass is used as a class from where the "ar class can be instantiated. he first line of
code that a "# compiler loo*s for in the source file compiled is the Bain( ) function.
o use a class the members of a class, you need to create an object the class. Objects interact
with each other by passing messages and by responding to the recived messages. Objects use
methods to pass messages. In "#, the tas* of passing messages can be accomplished by using
member functions.
'll the objects of a class share the same copy of the member functions but they maintain a
separate copy of the member variables in memory. he sharing of member functions and non
sharing of member variables of classes and objects is shown in the following figure.
Table -A class and its objects 0*/4 creating Objects*
In the preceding code, you have declared a class named "ar. o create an object named By"ar
of the type car, the following code is given in the main( ) method.
"ar By"ar ^ new "ar()R
he member functions of the class are accessed through an object of the class by using the 6.8
Opertor, as shown in the following e!ample$
By"ar.'ccept&etails ()R
By"ar.&isplay&etails ()R
In the preceeding e!ample, the object named and the 6.8 Operator are used to access the
member function 'ccept&etails( ) and
&isplay&etails( ). his means the object By"ar of the class car has invo*ed the function
'ccpet&etails( ) and &isplay&etails( ). his function accepts the values of engine type and the
number of wheels from the user and displays the same.
+ote$
2he preceding code in%o,es the &e&ber f!nction which is written within the *ain3 4 f!nction.
Es!ally, &e&ber f!nctions are declared and defined !nder the p!blic access specifier. .ccess
specifiers are !sed to deter&ine if any other class can access the %ariables or f!nction of a class.
"ompiling and %!ecuting "# Program
Bember (unction ;
Bember (unction D
Bember Cariable;
Bember Cariable D
Bember Cariable ;
Bember Cariable D
Bember Cariable ;
Bember Cariable D
Object Object
'fter writing a "# program in notepad, you need to compile and e!ecute it to get the desired
output. he complier converts the source code that you write in the machine code, which the
computer can understand.
)ou need to perform the following steps to compile and e!ecute a "# program$
;. ,ave the code written in +otepad with an e!tension .cs.
D. o compile the code, you need to go to the Cisual ,tudio DEEA command prompt. ,elect
)tart all progra!s1isual studio 04451isual studio Tools 1isual studio 0445
co!!and pro!pt to compile this program.
?. In the 1isual studio 0445 Co!!and "ro!pt window, move to the location where the
program file is saved
@. "ompile the program file by using the following command
csc %!ecutive"lass.cs
A. o e!ecute the code, type the following on the command prompt$
%!ecute"lass.e!e
Activity- Creating a C$ "rogra!
Problem ,tatement
&avid is the member of a team that is developing the 'utomatic Gan*ing ,oftware for a tennis
tournament. )ou have been assigned the tas* of creating a program. he program should accept
the following details of a tennis player and display it$
+ame, containing a ma!imum of DA characters
Gan* as an integer
3inning average as a decimal value
:elp &avid to create the program
,olution
o develop the re/uired program, &avid needs to perform the following steps$
/* ,elect )tart All "rogra!s Accessories 2otepad
0* 3rite the following program code in +otepad
using ,ystemR
class ennisPlayer
N
string ennisPlayer+ameR
int Gan*R
decimal 3inning'verageR
public void 'ccept&etails()
N
"onsole.3rite4ine(ZQn %nter the name of the ennis Player$Z)R
ennisPlayer+ame ^ "onsole.Gead4ine()R
"onsole.3rite4ine(ZQn %nter the Gan* of the Player$Z)R
Gan* ^ "onvert.oInt?D("onsole.Gead4ine())R
"onsole.3rite4ine(ZQn %nter the 3inning 'verage$Z)R
3inning'verage ^ "onvert.o&ecimal("onsole.Gead4ine())R
S
public void &isplay&etails()
N
"onsole.3rite4ine(ZQn +ame of the ennis Player$NESZ, ennisPlayer+ame)R
"onsole.3rite4ine(ZQn Gan* of the Player$NESZ, Gan*)R
"onsole.3rite4ine(ZQn 3inning 'verage$NESZ, 3inning'verage)R
S
public static void Bain()
N
ennisPlayer t ^ new ennisPlayer()R
t.'ccept&etails()R
t.&isplay&etails()R
S
S
6* ,elect File )ave to save the program file. he )ave As dialog bo! opens
7* %nter Tennisplayer*cs in the File na!e te!t bo!. he filename is saved with the .cs
e!tension, signifying that it is a "# program.
5* ,elect )tart all progra!s1isual studio 04451isual studio Tools 1isual
studio 0445 co!!and pro!pt to compile this program
3* In the 1isual studio 0445 Co!!and "ro!pt window, move to the location where the
program file is saved
8* "ompile the program file by using the following command
csc ennisplayer.cs
I. o e!ecute the code, type the following on the command prompt$
ennisplayer.e!e
9* Cerify the output of the e!ecuted program
Practice `uestions
;. In the statement, using ,ystem, ,ystem is a MMMMMMMMMMMMMMMMMMMMMMMM
a. +amespace
b. "lass
c. Object
d. Jeyword
D. 3hich is the following is not an e!ample of value type1
a. "har
b. Int
c. (loat
d. ,tring
?. he MMMMMMMMM compiler is used for "#.
a. "c
b. "sc
c. "LL
d. "s
@. he statement YY:ello 3orld in a "# program
a. &isplays the te!t :ello 3orld on the screen
b. Is not e!ecuted by the compiler and will be treated as a comment
c. &eclares a variable :ello 3orld
d. "auses all code lines following it to be treated as comments
A. In which of the following datatype does the "onsole.Gead4ine() function accept a value1
a. int
b. float
c. bool
d. string
,ummary
In this chapter, you learned that$
' variable is a named location in the memory that contains a specific value
' data type defines the type of the data that can be stored in a variable
he two types of data type are Calue ype an Geference type
he Gead4ine() function is used to accept inputs from the user
he using *eyword is used to include namespaces in a program
' namespace contains a set of related classes
Bember variables are declared inside the class body
"omment entries are notes written by a programmer in code so that others reading that
code can understand it better
'n object is an instance of a class
he compiler software translates a program written in a language, such as "#, into the
machine language.
%!ercises
%!ercise ;
&ia2 %ntertainment, Inc is developing a software application for toddlers that would enable them
to identify and distinguish shapes and colors. )ou have defined the 5eometricalM,hapes class as
a part of developing the software. he following is the class definition$
using ,ystemR
class 5eometricalM,hapes
N
double +oMofMcoordinatesR
double 'reaR
string "olorR
public void "reate()
N
YYcode to accept the user inputs and store the values in
YY the corresponding variables
S
public void &isplay()
N
YY "ode to display the details of hte shape such as
YYnoMofMcoordinates, area and color
S
S
he 5eometricalM,hapes class definition contains errors and is incomplete. )ou need to fi! the
errors and complete the code in the 5eometricalM,hapes class definition. )ou also need to write
the Bain() function, compile and e!ecute the code
%!ercise D
Fim is developing software for automating the slot boo*ing process for a video game parlor. s
"ustomers fill the 0oo*ing Ge/uest (orm with the details of the game, such as the name, number
of players and comple!ity level. hey hand over the form to the boo*ing officer at the parlor.
depending on the availability, the boo*ing officer reserves the time slots and the play station for
customers.
Identify the involved classes and objects, and their attributes. 3rite methods in the class to
accept the game details and store the values in a variable.
%!ercise ?
Provide the output of the following code$
using ,ystemR
class Byclass
N
static void Bain(stringOP args)
N
string 'nswer ^ Z)ZR
string GesponseMcode ^ ZIIZR
int counter ^ IER
"onsole.3rite4ine('nswer)R
"onsole.3rite4ine(GesponseMcode)R
"onsole.3rite4ine(counter)R
S
S
%!ercise @
'n automobile company has developed an application for maintaining the number of wheels in a
vehicle. Predict the output of the following partial code of the application$
using ,ystemR
class Cehicle
N
public int +umberMofMtyresR
S
class ByCehicle
N
static void Bain(stringOP args)
N
Cehicle Botorcycle ^ new Cehicle()R
Cehicle "ar ^ new Cehicle()R
"onsole.3rite4ine(Z%nter the number of vehicles in a car$Z)R
"a.+umberMofMtyres ^ "onvert.oInt;I("onsole.Gead4ine())R
"onsole.3rite4ine(Z%nter the number of vehicles in a Botorcycle$Z)R
Botorcycle.+umberMofMtyres ^ "onvert.oInt;I("onsole.Gead4ine())R
"onsole.3rite4ine(ZQnZ)R
"onsole.3rite4ine("ar.+umberMofMtyres)R
"onsole.3rite4ine(Z$ is the number of vehicles in a carZ)R
"onsole.3rite4ine(Botorcycle.+umberMofMtyres)R
"onsole.3rite4ine(Z$ is the number of vehicles in a BotorcycleZ)R
S
S
%!ercise A
echnosoft, a leading software company, has developed application for maintaining the scores of
the games in a video parlor. If the new score is greater than the scored top score, the following
program should interchange the values of the variables. opMscore and newMscore. :owever, the
program does not generate the desired output. Identify the error in the following program and
write the correct code.
using ,ystemR
class Interchange
N
int opMscoreR
int +ewMscoreR
int empR
void ,wap()
N
opMscore ^ AR
+ewMscore ^ ;ER
emp ^ topMscoreR
+ewMscore ^ opMscoreR
opMscore ^ +ewMscoreR
S
void &isplay()
N
"onsole.3rite4ine(Zhe new value of the top score is$Z)R
"onsole.3rite4ine(opMscore)R
"onsole.3rite4ine(Zhe old value of the top score was$Z)R
"onsole.3rite4ine(+ewMscore)R
S

static void Bain(stringOP args)
N
Interchange I;R
I;.,wap()R
I;.&isplay()R
S
S
%!ercise I
's a part of the team that is developing software for library, you have been assigned the tas* of
writing a program. he program should accept the following boo* details
I,0+ number
0oo* category ((iction of non-fiction
'uthor
+umber of copies available
3rite a "# program to accept and display the preceding boo* details.
Chapter 6
Operators and "rogra!!ing Constructs
Operators are used to compute results and compare the data values of a program. ' program
often involves decision ma*ing and iterative tas*s. o accomplish this tas*, programmers use
various operators in the conditional and looping constructs.
his chapter discusses the types of operators used in "# language. In addition, the conditional
constructs and the looping constructs are also discussed.
Objectives
In this chapter we will learn to
Hse various operators
o 'rithmetic
o 'rithmetic assignment
o Hnary
o "omparison
o 4ogical
Hse conditional constructs
Hse looping constructs
Hsing Operators
'pplications use operators to process the data entered by a user. Operators li*e L and 9 are
used to process variables and return a value. 'n operator is a set of one or more characters
that is used for computations or comparisons. Operators can transform one or more data
values, called operands, into a new data value.
"onsider the following e!pression
K L )
he preceding e!pression use two operands and an operator to add the values stored in the
variables.
Operators in "# can be classified as follows$
o 'rithmetic operators
o 'rithmetic assignment operators
o Hnary operators
o "omparison operators
o 4ogical operators
'rithmetic Operators
hese operators are the symbols that are used to perform arithmetic operations on variables.
he following table describes the commonly used arithmetic operators.
Operator escription Exa!ple
L Hsed to add D numbers K ^ ) L a. If ) ^ DE and a^ D,
K will have the value DD.
- Hsed to substract D numbers K ^ ) - a. If ) ^ DE and a^ D, K
will have the value ;<.
X Hsed to multiply D numbers K ^ ) X a. If ) ^ DE and a^ D,
K will have the value @E.
Y Hsed to divide one number by another K ^ ) Y a. If ) ^ D; and a^ D, K
will have the value ;E. 0ut if )
^ D;.E and a ^ D, K will have
the value ;E.A
V Hsed to divide D numbers and return the remainder K ^ ) V a. If ) ^ D; and a^ D,
K will have the value ;.
.rith&etic Operators
'rithmetic 'ssignment Operators
hese operators are used to perform arithmetic operations to assign a value to an operand. he
simplest of these is 6^8. Its general form is C'G ^ %!pression. he following table lists the usage
and describes the commonly used arithmetic assignment operators$
Operator :sage escription
^ K ^ AR ,tores the value A in the variable K
L^ KL^)R ,ame as $ K ^ K L )
-^ K-^)R ,ame as $ K ^ K - )
X^ KX^)R ,ame as $ K ^ K X )
Y^ KY^)R ,ame as $ K ^ K Y )
V^ KV^)R ,ame as $ K ^ K V )
.rith&etic .ssign&ent Operators
Hnary Operators
hese operators are used to increment or decrement the value of an operand by ;. he following
table e!plains the usage of the increment and decrement operators.
Operator :sage escription Exa!ple
LL LL operand R (pre-increment
operator) or
Operand LLR (post increment
operator)
Hsed to increment the
value of an operand
by ;
) ^ LLKR If the initial
value of K is A, after
the e!ecution of the
preceding statement
values of both K and )
will be I.
) ^ KLLR If the initial
value of K is A, after
the e!ecution of the
preceding statement
values of K will be I
and value of ) will be
A
-- -- operand R (pre-decrement
operator) or
Operand --R (post decrement
operator
Hsed to decrement
the value of an
operand by ;
) ^ --KR If the initial
value of K is A, after
the e!ecution of the
preceding statement
values of both K and )
will be @.
) ^ K--R If the initial
value of K is A, after
the e!ecution of the
preceding statement
values of K will be @
and value of ) will be
A
Enary Operators
"omparison Operators
hese operators are used to compare two values and perform an action on the basis of the result
of that comparison. 3henever you see comparison operator, the e!pression results of 0oolean
value -true. or -false.. he following table e!plains the usage of commonly used comparison
operators.
Operator :sage escription Exa!ple
%#n the follo(ing
exa!ples; the value
of < is assu!ed to
be 04 and value of =
is assu!ed to be 05&
\ %!pression; \ e!pression D Hsed to chec* whether
e!pression ; is less than
e!pression D
bool GesultR
Gesult ^ K \ )R
Gesult will have the
value true
] %!pression; ] e!pression D Hsed to chec* whether
e!pression ; is greater than
e!pression D
bool GesultR
Gesult ^ K ] )R
Gesult will have the
value false
\^ %!pression; \^ e!pression D Hsed to chec* whether
e!pression ; is less than or
e/ual to e!pression D
bool GesultR
Gesult ^ K \^ )R
Gesult will have the
value true
]^ %!pression; ^] e!pression D Hsed to chec* whether
e!pression ; is greater than
or e/ual to e!pression D
bool GesultR
Gesult ^ K ]^ )R
Gesult will have the
value false
^^ %!pression; ^^ e!pression D Hsed to chec* whether
e!pression ; is e/ual to
e!pression D
bool GesultR
Gesult ^ K ^^ )R
Gesult will have the
value false
T^ %!pression; T^ e!pression D Hsed to chec* whether
e!pression ; is not e/ual to
e!pression D
bool GesultR
Gesult ^ K T^ )R
Gesult will have the
value true
Co&parison Operators
4ogical Operators
4ogical operators are used to evaluate e!pressions and return a 0oolean value. he following
table e!plains the usage of logical operators.
Operator :sage escription Exa!ple
UU %!pression; UU
e!pression D
Geturns true if both
e!pression ; and
e!pression D are true
bool GesultR
string str;, strDR
str; ^ ZJoreaZR
strD ^ Z(ranceZR
Gesult ^ (str; ^^ ZJoreaZ) UU (strD
^^ Z(ranceZ)R

"onsole.3rite4ine(Gesult.o,tring())R
he message displays true because
str; has the value 6Jorea8 and strD
has the value 6(rance8.
T T e!pression Geturns true if the
e!pression is false
bool GesultR
int !R
! ^ DER
Gesult ^ (T(! ^^;E))R
"onsole.3rite4ine(Z! is not e/ual to
;EZ)R
he message ! is not e/ual to ;E is
displayed because the e!pression
used in the if statement is true
bb %!pression; bb
e!pression D
Geturns true if either
e!pression ; or
e!pression D or both
of them are true
bool GesultR
string str;, strDR
str; ^ ZJoreaZR
strD ^ Z(ranceZR
Gesult ^ (str; ^^ ZJoreaZ) bb (strD ^^
Z(ranceZ)R

"onsole.3rite4ine(Gesult.o,tring())R
he message displays true if either
str; has the value 6Jorea8 or strD has
the value 6(rance8.
W %!pression; W
e!pression D
Geturns true if either
e!pression ; or
e!pression D is true.
Geturns false if both
e!pression ; and
e!pression D are true
or if both e!pression
; and e!pression D
are false
bool GesultR
string str;, strDR
str; ^ ZJoreaZR
strD ^ Z(ranceZR
Gesult ^ (str; ^^ ZJoreaZ) W (strD ^^
Z(ranceZ)R

"onsole.3rite4ine(Gesult.o,tring())R
he message displays false because
both the e!pressions are true
:sing Conditional Construct
he ability to ta*e decisions is fundamental to human beings. &ecision-ma*ing can be
incorporated into programs as well. his will result in determining the se/uence in which a
program will e!ecute instructions. )ou can control the flow of a program by using conditional
constructs. "onditional constructs allow the selective e!ecution of statements, depending on the
value of the e!pressions associated with them. he comparison operators are re/uired for
evaluating the conditions. he various conditional constructs are$
he if7else construct
he switch..case construct
he If7else construct$
he if7else conditional construct is followed by a logical e!pression, where data is compared
and a decision is made on the basis of result of the comparison. he following is the synta! of the
if..else construct.
if (e!pression)
N
statementsR
S
else
N
statementsR
S
he follwing code is an e!ample of if 7 else construct
using ,ystemR
class 4eapyear
N
public static void Bain()
N
int yearR
"onsole.3rite4ine(Z%nter the year$Z)R
year ^ "onvert.oInt?D("onsole.Gead4ine())R
if ((year V @ ^^ E) UU (year V ;EE T^ E bb year V @EE ^^ E))
"onsole.3rite4ine(ZQn you have entered a 4eap )earZ)R
else
"onsole.3rite4ine(ZQn he year you have entered is not a 4eap )earZ)R
S
S
he preceding code chec*s whether the year entered by a user is a leap year. If the condition
specifed in the if statement is true, the statements in the if bloc* are e!ecuted. 'nd if the condition
specifed in the if statement is false, the statements in the else bloc* are e!ecuted.
he else part in the if.. else construct is optional and can be omitted as shown in the following
code$
int var ^ AR
if (var]E)
"onsole.3rite4ine(ZCar is a positive numberZ)R
he if.. else constructs can be nested inside each other. 3hen nested together, the construct is
*nown as cascading if..else constructs. he following code is an e!ample of cascading if..else
constructs$
int !, y, 2R
! ^ ;ER
y ^ DER
2 ^ ?ER
if ((! ] y)
if (! ] 2))
"onsole.3rite4ine(ZK is greater than ) and aZ)R
else
"onsole.3rite4ine(ZQn a is greater than K and )Z)R
else
if (y]2))
"onsole.3rite4ine(ZQn ) is greater than K and aZ)R
else
"onsole.3rite4ine(ZQn a is greater than K and )Z)R
he preceding code displays the greatest of ? numbers.
he cascading if..else construct can also be used with logical operators. he following code is an
e!ample of converting the cascading if..else construct to an if..else construct by using logical
operators$
int !, y, 2R
! ^ ;ER
y ^ DER
2 ^ ?ER
if ((! ] y) UU (! ] 2))
"onsole.3rite4ine(ZK is greater than ) and aZ)R
if ((y]!) UU (y]2))
"onsole.3rite4ine(ZQn ) is greater than K and aZ)R
if ((2 ] !) UU (2 ] y))
"onsole.3rite4ine(ZQn a is greater than K and )Z)R
In the preceding code, the UU is used to find the logical and '+& of D conditions.
he statement "onsole.3rite4ine(ZK is greater than ) and aZ)is e!ecuted only if both the
conditions evaluate to true.
+ote$
In case of logical OG operator (bb), if the first condition evaluates to true, the second condition is
not evaluated.
he ,witch.."ase construct
'nother conditional available in "# is the switch7 case construct. It is used when there are
multiple values for a variable. he following code is the synta! of the switch case construct$
switch (Cariable+ame)
N
case "onstM%!p;$
statementsR
brea*R
case "onstM%!pD$
statementsR
brea*R
...
.. .
case "onstM%!pn$
statementsR
brea*R
default$
statementsR
brea*R
S
3hen the switch case statement is e!ecuted, the variable given in the switch statement is
evaluated and compared with each case constant. If one of the case constants is e/ual to the
value of the variable given in the switch statement, control is passed to the statement following
the matched case label. ' brea* statement is used to e!it the switch statement. his prevents the
e!ecution of the remaining case structures by ending the e!ecution of the switch case construct.
%ach brea* statement terminates the enclosing switch statement and the flow of control. If none
of the case match, the default case is invo*ed.
he *eyword switch is followed by the variable in parentheses$
switch (var)
%ach case *eyword is followed by a case constant$
case ;$
he data type of the case constant should match the data type of the switch variable. 0efore
entering the switch construct, a value should be assigned to the switch variable.
)ou can substitute a comple! if..else construct with the switch 7case construct. he following
code is an e!ample of the comple! if..else construct$
int varR
var ^ AEER
if (var ^^ ;EE)
"onsole.3rite4ine(Z"enturyZ)R
else if (var ^ DEE)
"onsole.3rite4ine(Z&ouble "enturyZ)R
else if (var ^ ?EE)
"onsole.3rite4ine(Zriple "enturyZ)R
else
"onsole.3rite4ine(ZInvalid CalueZ)R
he preceding code of the if..else construct can be replaced by a switch..case construct as
shown in the following e!ample$

int varR
var ^ AEER
switch (var)
N
case ;EE$
"onsole.3rite4ine(Z"enturyZ)R
brea*R
case DEE$
"onsole.3rite4ine(Z&ouble "enturyZ)R
brea*R
case ?EE$
"onsole.3rite4ine(Zriple "enturyZ)R
brea*R
default$
"onsole.3rite4ine(ZInvalid CalueZ)R
brea*R
S
he switch ..case construct evaluates an e!pression only once at the top of the structure where
as the if..else construct evaluates the e!pression for each if statement.
+ote$
2he ifGelse str!ct!re can be s!bstit!ted with a switchG.case str!ct!re only if each else..if
state&ent in the ifGelse constr!ct e%al!ates the sa&e e1pression.
'ctivity$ "alculator using "onditional constructs
Problem statement
3rite a program that emulates a calculator. he calculator should be able to perform the following
mathematical operations$
'ddition
,ubstraction
Bultiplication
&ivision
,olution
o develop the re/uired program perform the following steps$
/* ,elect )tart All "rogra!s Accessories 2otepad
0* 3rite the following program code in +otepad
using ,ystemR
class "alculator
N
public static int i ^ ER
public static int j ^ ER
public void 'ccept+umbers()
N
"onsole.3rite4ine(ZQn %nter the value of iZ)R
i ^ "onvert.oInt?D("onsole.Gead4ine())R
"onsole.3rite4ine(ZQn %nter the value of jZ)R
j ^ "onvert.oInt?D("onsole.Gead4ine())R
S
public int 'dd"alc("alculator c;)
N
c;.'ccept+umbers()R
int a; ^ iR
int aD ^ jR
int sum ^ a; L aDR
return (sum)R
S
public int ,ub"alc("alculator c;)
N
c;.'ccept+umbers()R
int a; ^ iR
int aD ^ jR
int difference ^ a; - aDR
return (difference)R
S
public int Bul"alc("alculator c;)
N
c;.'ccept+umbers()R
int a; ^ iR
int aD ^ jR
int multi ^ a; X aDR
return (multi)R
S
public float &iv"alc("alculator c;)
N
c;.'ccept+umbers()R
int a; ^ iR
int aD ^ jR
float div ^ a;YaDR
return (div)R
S
public static void Bain()
N
"alculator c ^ new "alculator()R
"alculator g ^ new "alculator()R
"onsole.3rite4ine(ZQnQbQbPlease enter the re/uired option Qn ;. 'ddition Qn D.
,ubstraction Qn?.Bultiplication Qn@.&ivisionZ)R
int h^ER
h^"onvert.oInt?D("onsole.Gead4ine())R
switch (h)
N
case ;$
int s; ^ c.'dd"alc(g)R
"onsole.3rite4ine(ZQn he value of the addition is NESZ, s;)R
brea*R
case D$
int sD ^ c.,ub"alc(g)R
"onsole.3rite4ine(ZQn he value of the substraction is NESZ, sD)R
brea*R
case ?$
int s? ^ c.Bul"alc(g)R
"onsole.3rite4ine(ZQn he value of the multiplication is NESZ, s?)R
brea*R
case @$
float s@ ^ c.&iv"alc(g)R
"onsole.3rite4ine(ZQn he value of the &ivision is NESZ, s@)R
brea*R


S
S
S
6* ,elect File )ave to save the program file. he )ave As dialog bo! opens
7* %nter Calculator*cs in the File na!e te!t bo!. he filename is saved with the .cs
e!tension, signifying that it is a "# program.
5* clic* the )ave button in the )ave As dialog bo!
3* ,elect )tart all progra!s1isual studio 04451isual studio Tools 1isual
studio 0445 co!!and pro!pt to compile this program
8* In the 1isual studio 0445 Co!!and "ro!pt window, move to the location where the
program file is saved
9* "ompile the program file by using the following command
csc "alculator.cs
>* o e!ecute the code, type the following on the command prompt$
"alculator.e!e
/4* Cerify the output of the e!ecuted program
:sing ,oop Constructs
4oop constructs are used to e!ecute one or more lines of code repetitively. he following loop
construts re supported by "#$
he while loop
he do..while loop
he for loop
The (hile loop
he while loop construct is used to e!ecute a bloc* of statements for a definite number of times,
depending on a condition. he while statement always chec*s the condition before e!ecuting the
statements within the loop. 3hen the e!ecution reaches the last statement in the while loop, the
control is passed bac* to the begening of the loop. If the condition still holds true, the statements
within the loop are e!ecuted again. he e!ecution of the statements within the loop continues
until the condition evaluates to false.
he following code is the synta! of the while loop construct$
3hile (e!pression)
N
,tatementsR
S
he following code is an e!ample of the while loop construct$
using ,ystemR
class Cariable
N


static void Bain(stringOP args)
N

int varR
var ^ ;EER
while (var \ DEE)
N
"onsole.3rite4ine(ZCalue of Cariable is NESZ, var)R
var ^ var L ;ER
"onsole.Gead4ine()R
S
S
S
he preceding code creates an integer vriable var and assigns the value ;EE to it. he while
statement chec*s whether the value of var is lower than DEE. If the condition evaluates the true,
the statements within the while loop are e!ecuted. his process continues until the value of var
becomes greater than or e/ual to DEE.
)ou can use the brea* statement to to e!it the while loop structure. he following code is an
e!ample of the brea* statement
int varR
var ^ ;EER
while (true)
N
"onsole.3rite4ine(ZCalue of Car$ Z,L var)R
var ^ var L ;ER
if (var ]^ DEE)
brea*R
S
In the preceeding code, the while statement while(true) will always evaluate to true and the while
bloc* will run an indefinite number of times. In such a case, the brea* statement is used to e!it
the while loop bloc* on the basis of the condition given within the while bloc*. In the preceeding
e!ample, the control moves out of the while loop when the value of var becomes greater than or
e/ual to DEE.
The do?(hile loop
he do..while loop construct is similar to the while loop construct. 0oth iterate until the specified
loop condition becomes false. :owever, in the do..while loop, the body of the loop is e!ecuted
atleast once and the condition is evluated for subse/uent interactions.
he following code is the synta! of the do..while loop construct$
&o
N
,tatementsR
Swhile(e!pression)R
"onsider the following e!ample of the do.while loop construct$
int varR
Car ^ ;EER
do
N
"onsole.write4ine(6Calue of var$ 6 L var)R
Car ^ var L ;ER
S
3hile (var \ DEE)R
In the preceding code, the condition is chec*ed after the statements in the do..while loop sructure
is e!ecuted. herefore, the statements within the do7while loop are e!ecuted at least once,
regardless of whether the condition evaluates to true or false.
he difference between the do..while and while loop constructs is shown in the following figure.
(ifference in 01ec!tion of the do..while and whileloop
The for loop
he for loop structure is used to e!ecute a bloc* of statements for a specific number of times. he
following code is the synta! of the for loop construct$
(or (initiali2ationR termination R incrementYdecrement)
N
,tatements
S
he initiali2ation e!pression initiali2es the for loop construct. It is e!ecuted once at the begenning
of the loop. he termination e!pression determines when to terminate the loop. 't the begening of
the loop, this e!pression is evaluated for each interation. 3hen the e!pression evaluates to false,
the loop terminates. hen, through the loop, the increment or decrement e!pression gets invo*ed
after each iteration. 'll these components are optional.
)ou can create an infinite loop by omitting all the three e!pressions, as shown in the following
code$
(or ( R R )
N
. . .
S
Execute Body
of the Loop
Evaluat
e
Conditio
n
Execute Body
of the Loop
Evaluat
e
Conditio
n
True
False
Do while
True
False
while
he se/uence of the e!ecution of a complete for loop construct is shown in the following figure
Se/!ence of e1ec!tion for the loop*
he following is an e!ample of the for loop strcture that displays integers between ;E and DE$
using System;
class Variable
{
static void Main(string[] args)
{
int var;
for (var = 10; var = !0; var"")
{
#onsole$%rite&ine('Value of t(e variable is){0*'+ var);
#onsole$,ead&ine();
*
*
*
Activity- Fibonacci )eries :sing ,oop Constructs
Problem statement
3rite a program that generates the (ibonacci series up to DEE.
,olution
o create the re/uired program, perform the following steps$
;. ,elect )tart All "rogra!s Accessories 2otepad
Initialization
Evaluate
Condition
Body of the Loop
Increment/Decrement
Exit the For Loop
True
False
D. 3rite the following program code in +otepad
using System;
class -ibnossi
{
.ublic static void Main()
{
int n1 = 1;
int n! = 1;
#onsole$%rite&ine(n1);
/(ile (n!!00)
{
#onsole$%rite&ine(n!);
n! = n!" n1;
n1 = n! 0 n1;
*
*
*
?. ,elect File )ave to save the program file. he )ave As dialog bo! opens
@. %nter Fibonacci*cs in the File na!e te!t bo!. he filename is saved with the .cs
e!tension, signifying that it is a "# program.
A. "lic* the )ave button in the )ave As dialog bo!
I. ,elect )tart all progra!s1isual studio 04451isual studio Tools 1isual
studio 0445 co!!and pro!pt to open the visual studio DEEA command prompt window
>. In the 1isual studio 0445 Co!!and "ro!pt window, move to the location where the
program file is saved
<. "ompile the program file by using the following command
csc (ibonacci.cs
=. %!ecute the compiled program as $
(ibonacci.e!e
;E. Cerify the output of the e!ecuted program
The brea@ and continue )tate!ents
't times, there is a need to e!it a loop before the loop condition is re-evaluated after iteration.
's with a while loop, you can use the brea* statement to e!it for loop. he continue statement
is used to s*ip all the subse/uent instructions and ta*e the control bac* to the loop.
he following code accpets five numbers and prints the sum of all the positive numbers$
using System;
class 1rea2#ontinue
{
static void Main(string[] args)
{
int incr+ Sum3um+ number;
for (Sum3um = number = incr = 0; incr 4; incr "= 1)
{
#onsole$%rite&ine('5nter a 6ositive 3umber');
number = #onvert$7o8nt9!(#onsole$,ead&ine());
if (number = 0) ::3on0.ositive numbers
continue; ::#ontinue to incr"=1 in t(e for loo.
Sum3um = Sum3um " number;
*
#onsole$%rite&ine('7(e sum of t(e .ositive numbers entered
is {0*'+ Sum3um);
#onsole$,ead&ine();
*
*
"ractice .uestions
;. "onsider the following code$

static void Main(string[] args)
{
c(ar c(aracter;
#onsole$%rite&ine('5nter a #(aracter)');
c(aracter = #onvert$7o#(ar(#onsole$,ead&ine());
if (c(aracter == ;<;)
#onsole$%rite&ine('7(e #(aracter is <');
else
#onsole$%rite&ine('7(e c(aracter is not <);
#onsole$,ead&ine();
*
Nte
2he con%ert.2oChar3 4 con%erts a %al!e to the char datatype
3hat will be the output if the input of the preceding code is !1
a. he character is !
b. he character is not !
c. %rror message
d. !
D. o which category of operators do the LL belong1
a. 'rithmetic operators
b. 'rithmetic assignment operators
c. Hnary operators
d. "omparision operators
?. 3hich of the following operators can be used to evaluate an e!pression to ture only if
both the conditions are true1
a. UU
b. b b
c. ]^
d. T ^
@. ,tate whether the following statement is rue or (alse$
he continue statement if used in the while and do7while loop caues the program
control pass to the top of the loop avoiding the other statements in the loop.
A. ,tate whether the following statement is true or (alse$
' termination e!pression is evaluated at each iteration of the for loop.
)u!!ary
In this chapter, you learned that$
Operators are used to compute and compare values and test multiple conditions.
)ou use arithmetic operators to perform arithmetic operations on variables li*e addition,
substraction, multiplication, and division
)ou can use arithmetic assignment operators to perform arithmeic operations and assign
the result to a variable.
he unary operators, such as the increment and decrement operators, operate on one
operand
"omparision operators are used to compare two values and perform an action on the
basis of the result of the comparison
4ogical operators are used to compare two valuse and return a 0oolean value.
"onditional constructs are used to allow the selective e!ecution of statements. he
conditional constructs in " # are$
o If ..else
o ,witch..case
4ooping constructs are used when you want a section of a program to be repeated a
certain number of times. "# offers the following looping constructs
o 3hile
o &o 7while
o (or
he brea* and continue statements are used to control the program flow within a loop.
Exercises
%!ercise ;
3rite a program to identify whether a character entered by user is a vowel or a consonant
%!ercise D
3rite a program to identify whether the number entered by a user is even or odd.
%!ercise ?
3rite a program to accept a number from the user and display all the prime numbers from
2ero up to the number entered by user.
E2CA"):,AT#O2 A2 AA)TRACT#O2
Chapter-7
Objects contain data and methods to end and receive messages.&ata memebers of objects can
have a different scope or visibility. )ou use access specifier to define the scope of data member
and method.
his chapter introduces the concept of abstraction and encapsulation. It discusses the
implementation and encapsulation by using access specifiers. It also e!plains the concept of
using methods. In addition, the chapter also discusses the static variables and static function.
Objectives
In this chapter, you will learn to$
&efine abstrction and encapsulation
Implement encapsulation by using access specifiers
Hse methods
Hse static variables and static functions
#ntroducing Abstraction and Encapsulation
'bstraction and encapsulation are importnt features of any OOP language. 'bstraction involves
only the relavant information. %ncapsulation involves in pac*aging one or more components
together.
efining Abstraction
"onsider the following e!ample$
'n automobile salesperon is aware that different people have different performances. ,ome
people are interested in the spedd of the car, some in its price,some in the engine and some in
the style. 'lthough all of them want to buy a car,each of them is interested in a specific attribute or
feature. he sales man *nows all the details of a car, but he presents only the relevant
information to a potential customer. 's a result, the salesman practices abstraction and presents
only relavent details to customer.
In other words, abstraction means -loo*ing for what you want. in an object or a class.
"onsider the abstraction from the perspective of a programmer who wants a user to be able to
add items to a list. :owevr, the details of how a particular tas* in a program is accomplished is
hidden. 'nstraction does not mean that information is unavailable. It means that all the
information e!ists, but only the relevant information is provided to the user.
efining Encapsulation
%ncapsulation literally means -to enclose in or as if in a capsule.. %ncapsulation is defined as the
process of enclosing one or more items within a physical or logical pac*age. It involves
preventing access to nonessential details.
(or e!ample, when you plug in the cord of the vaccum cleaner and turn on the switch, the
vaccum cleaner starts. )ou do not see the comple! processes needed actually to convert
electricity into suction power. In the otherwords, the e!act wor*ing of the cleaner has been
encapsulated. herefore, encapsulation is also e!plained as information hiding or data hiding
because it involves hiding many of the important details of an object from the user.
'bstraction ad encapsulation are different but related features. 'bstraction enables yo to *ae the
relavent information visible. %ncapsulation enables you to pac*age information to implement the
desired level of abstraction. herefore, encapsulation assists abstraction by providing a means of
suppressing the nonessential details. %ncpsulation allows som information to be hidden but it also
allows some information to be hidden but it also allows some information to be visible.
#!ple!entation Encapsulation by :sing Access )pecifiers
'n access specifier defines the scope of a class member. ' class member refers to the variables
and functions in a class. ' program can have one or more classes. )ou may want some members
of a class to be accessible to the other classes. 0ut, you may not want some other members of
the class to be accessible outside the class.
It is the privilage of the programmer to decide the use of access specifiers to iplement
encapsulation and abstraction in "#.
"onsider the world of modern advertising. Ciewers are bombarded with hundreds of advertising
messages everyday. If they were to listen to, understand and respond to all of them, they would
probably not have much time and energy left for anythin else. Instead, they concentrate only on
messages that are of specific intrest to them. hus, for e!ample if they want to buy a rerigerator,
they will pay attention to the advertisements that feature refrigerators.
,imilarly, a housewife would typically pay attention to the si2e, ese of handling, and durability of a
vaccum cleaner. ,he would not be interested in the gadgetry inside it, which is in the purview of
the maintenance man. ,ales personnel may concentrate on entirely different factors. here is a
term given to the preceeding process$ 'bstraction
)ou use various types of access specifiers to specify the e!tent of the visibility of the class
member.
Types of Access )pecifers
"# supports the following access specifiers$
6ublic
6rivate
6rotected
8nternal
.rotected internal
The public Access )pecifier
he public access specifier allows a class to e!pose its member variables and member functions
to other functions and objects. 'ny member that is declared public can be accessed from outside
the class.
he following is an e!ample of the use of the public access specifier$
using System;
class car
{
.rivate string #ar#olor; ::since t(e variable is .rivate
:: it cannot be accessed outside t(e class definition
*
class 1i2e
{
.ublic string 1i2e#olor; ::Since t(e variable is .ublic
:: it can be accesses outside t(e class definition$
*
class ,esult
{
static void Main(string[] args)
{
car -ord = ne/ car();
1i2e =onda = ne/ 1i2e();
:> 7(e $ o.erator is used to access t(e member data and
functions >:
-ord$#ar#olor = 'red'; :> 5rror? #annot access t(e .rivate
members >:
=onda$1i2e#olor = 'blue';
#onsole$,ead&ine();
*
*
In the preceeding e!ample, the #ar#olor variable cannot be accessed from any function outside
the car class. On the other hand, the 0i*e"olor variable is a public member. herefore, it can be
accessed from outside the class.
he following is another e!aple of the use of the public specifier$
using System;
class car
{
.rivate string #olor;
.ublic void =on2()
{
#onsole$%rite&ine('1556 1556?');
*
*
class ,esult
{
static void Main(string[] args)
{
car -ord = ne/ car();
-ord$=on2() :: @is.lays 1556 1556?
#onsole$,ead&ine();
*
*
In the preceeding e!ample, the =on2()function will be accessible from anywhere in the program
and can be accessed by using the objects of the car class.
The "rivate Access )pecifier
he private access specifier allows a class to hide its member variables and member functions
from other class objects and functions. herefore, the private member of a class is not visible
outside a class. If a member is declared private, only the unctions of that clas can access the
member. %ven the instance of the class cannot access its private members. herefore, the data is
hidden and cannot be altered by any function other than the member functions of the class.
he following is an e!ample of the use of private access specifier$
using System;
class car
{
.rivate string Model;
void =on2()
{
#onsole$%rite&ine('6A,,6 6A,,6?');
*
.ublic void SetModel()
{
#onsole$%rite&ine('5nter t(e Model 3ame)');
Model = #onsole$,ead&ine();
*
.ublic void @is.layModel()
{
#onsole$%rite&ine('7(e model is){0)'+ Model);
*
*
class @is.lay
{
static void Main(string[] args)
{
car -ord = ne/ car();
-ord$SetModel(); ::Acce.ts t(e Model 3ame
-ord$@is.layModel(); ::@is.lays t(e Model 3ame
-ord$=on2(); :: 5rror? 6rivate members cannot be accessed
outside t(e class definition
return 0;
*
*
In the preceeding e!ample, the SetModel()and @is.layModel()functions cn be called from
the (ord object, created in the Bain( ) function because these are public member functions.
,imilarly, the :on*( ) function cannot be accessed through the (ord object because it is a private
member function.
3hen you do not specify any data member as public, protected, or private, then the default
access specifier for a data member is private. In the following e!ample, the data member Model
is private, even though it has not been specified e!plicitly$
class car
{
c(ar Model;
$ $ $ $
*
The protected Access )pecifier
his specifier allows a class to hide its member variabls and member functions from other class
objects and functions, e!cept the child class. he protected access specifier becomes important
while implementing inheritence.
he follwong e!ample shows the protected member of the class will have the same visibility asa
private member of the class
using System;
class car
{
.rotected string Model;
void =on2()
{
#onsole$%rite&ine('6A,,6 6A,,6?');
*
.ublic void SetModel()
{
#onsole$%rite&ine('5nter t(e Model 3ame)');
Model = #onsole$,ead&ine();
*
.ublic void @is.layModel()
{
#onsole$%rite&ine('7(e model is){0)'+ Model);
*
*
class @is.lay
{
static void Main(string[] args)
{
car -ord = ne/ car();
-ord$SetModel(); ::Acce.ts t(e Model 3ame
-ord$@is.layModel(); ::@is.lays t(e Model 3ame
-ord$=on2(); :: 5rror? 6rivate members cannot be accessed
outside t(e class definition
#onsole$%rite&ine(-ord$Model); ::5rror? .rotected members
cannot be accessed
return 0;
*
*
In the preceding e!ample, the ,etBodel( ) and &isplayBodel( ) functions can be called from the
(ord object defined in the Bian( ) function. :owever, the Bodel variable cannot be accessed
through the (ord object because it is a protected member variable. ,imilarly, he :on*( ) function
cannot be accessed through the (ord object because it is also a private member function.
The #nternal Access specifier
he internal access specifier allows a class to e!pose its member variables and member
functions to the other functions and objects. 'ny member that is declared internal can
beaccessed from any class or method defined within the application in which the member is
defined. 3hn you do not specify any data member as public, protected, or private the default
access specifier for a class is internal.
he following is an e!ample of the use of the internal access specifier$
using System;
class car
{
.rivate string #ar#olor; ::Since t(e variable is .rivate
:: it cannot be accesses outside t(e class definition$
internal void =on2()
{
#onsole$%rite&ine('1556 1556?');
*
*
class 1i2e
{
internal string 1i2e#olor; ::Since t(e variable is internal
:: it can be accesses outside t(e class definition$
*
class ,esult
{
static void Main(string[] args)
{
car -ord = ne/ car();
1i2e =onda = ne/ 1i2e();
-ord$#ar#olor = 'red'; :> 5rror? #annot access t(e .rivate
members >:
=onda$1i2e#olor = 'blue';
-ord$=on2() :: @is.lays 1556 1556?
#onsole$,ead&ine();
*
*
In the preceding e!ample, the car"olor variable cannot be accessed from any function outside
the "ar class. On the other hand, the 0i*e"olor variable is an internal member. :ence, it can be
accessed from outside the class. 'lso, the :on*( ) function will be accessible from anywhere in
the program and can be accessed by using the objects of the "ar class.
The "rotected #nternal Access )pecifier
his specifier allows a class to hide its member variables and member functions to be accessed
from other class objects and functions, e!cept the child class, within the application. he
protected internal access specifier becomes important while implementation inheritance.
he following e!ample shows that the protected internal memberof the class will have the same
visibility as a private member of the class$
using System;
class car
{
.rotected internal string Model;
void =on2()
{
#onsole$%rite&ine('6A,,6 6A,,6?');
*
.ublic void SetModel()
{
#onsole$%rite&ine('5nter t(e Model 3ame)');
Model = #onsole$,ead&ine();
*
.ublic void @is.layModel()
{
#onsole$%rite&ine('7(e model is){0)'+ Model);
*
*
class @is.lay
{
static void Main(string[] args)
{
car -ord = ne/ car();
-ord$SetModel(); ::Acce.ts t(e Model 3ame
-ord$@is.layModel(); ::@is.lays t(e Model 3ame
-ord$=on2(); :: 5rror? 6rivate members cannot be accessed
outside t(e class definition
#onsole$%rite&ine(-ord$Model); ::5rror? .rotected internal
members cannot be accessed outside t(e class definition
return 0;
*
*
In the preceding e!ample, the ,etBode ( ) and d&isplayBode ( ) functions can be called from the
(ord object defined in the Bain ( ) function. :owever, the model variable cannot be accessed
through the (ord objects because it is a protected internal member variable. ,imilarly, the :on* ()
function cannot be accessed through the (ord object because it is also a private member
function.
he following table shows the visisbility of the class members for the access specifiers
Access
Specifier
s
!isi#"e t wn
c"ass
mem#ers
!isi#"e t
#$ects f
ther
c"ass
!isi#"e t #$ects f
ther c"ass utside
the namespace
c""ectin
!isi#"e t #$ects f
chi"d c"asses utside
the namespace
c""ectin
Public )es )es )es )es
Private )es +o +o +o
Protected )es +o +o )es
Internal )es )es +o +o
Protected
internal
)es +o +o +o
Visibility of class &e&bers
Activity- Calculating Area and 1olu!e by :sing Access specifiers
"roble! )tate!ent
3rite a program to calculate the area of a rectangle and a s/uare.
)olution
o develop the re/uired program perform the following steps$
;. ,elect )tart All "rogra!s Accessories 2otepad
D. 3rite the following program code in +otepad
using System;
class Area
{
static int result;
.ublic void ,ecArea()
{
int l;
int /;
#onsole$%rite&ine('Bn 5nter t(e lengt( of t(e rectangle)');
l = #onvert$7o8nt9!(#onsole$,ead&ine());
#onsole$%rite&ine('Bn 5nter t(e /idt( of t(e rectangle)');
/ = #onvert$7o8nt9!(#onsole$,ead&ine());
result = l > /;
#onsole$%rite&ine('Bn 7(e area of t(e rectangle is ){0*'+
result);
*
.ublic void SCArea()
{
int s;
#onsole$%rite&ine('Bn 5nter t(e side of t(e SCuare)');
s = #onvert$7o8nt9!(#onsole$,ead&ine());
result = s>s;
#onsole$%rite&ine('Bn 7(e area of t(e SCuare is ){0*'+
result);
*
static void Main()
{
Area a = ne/ Area();
int c;
#onsole$%rite&ine('Bn Main Menu');
#onsole$%rite&ine('Bn 1$ Area of ,ectangle');
#onsole$%rite&ine('Bn !$ Area of SCuare');
#onsole$%rite&ine('Bn #(oose 1 or !');
c = #onvert$7o8nt9!(#onsole$,ead&ine());
s/itc( (c)
{
case 1)
a$,ecArea();
brea2;
case !)
a$SCArea();
brea2;
default)
brea2;
*
*
*
?. ,elect File )ave to save the program file. he )ave As dialog bo! opens
@. %nter Area*cs in the File na!e te!t bo!. he filename is saved with the .cs e!tension,
signifying that it is a "# program.
A. "lic* the )ave button in the )ave As dialog bo!
>. ,elect )tart all progra!s1isual studio 04451isual studio Tools 1isual
studio 0445 co!!and pro!pt to open the visual studio DEEA command prompt window
>. In the 1isual studio 0445 Co!!and "ro!pt window, move to the location where the
program file is saved
<. "ompile the program file by using the following command
"sc 'rea.cs
=. %!ecute the compiled program as $
area.e!e
;E. Cerify the output of the e!ecuted program
:sing !ethods
' method is a set of one or more program statements, which can be e!ecuted by refering to the
method name.
Bethod play a *ey role in modular programming. 3hen a comple! application is divided into
methods, code is more fle!ible and easy to maintain and to debug. Bethods are useful for
performing repetitive tas*s, such a fetching specific records and te!t. hey allow you to brea* an
application into discrete logical units, whuch ma*es the application more readable. )ou can reuse
code written in a method because it can be e!ecuted any number of times by calling the method
with little or no modification.
o use methods, you need to$
&efine methods
"all methods
efining !ethods
&efining a method means declaring the elements of its structure. "onsider the synta! of defing a
method$
\ 'ccess specifier ] \Geturn ype] \Bethod +ame](Parameter list)
N
Behod body
S
he elements of the method declaration include the method name, the parameters list, the return
type, and the method body. he following are the elements of a method$
Access specifier- his determines the e!tent to which a variable or method can be
accessed from another class
Return type- ' method can return a value of any type. If the method is not returning any
value, use void as the return type.
Method na!e- his is uni/ue identifier and is case-sensitive. he method name cannot
be the same as the variable name or any other non-method item declared in the class.
"ara!eter list- his is used to pass and receive the data from a method. It is enclosed
between parentheses. he parameters are included even if there are no parameters.
Method Aody- his contains the set of instructions needed to complete the re/uired
activity.
"onsider the following code snippet of method definiton$
class #alculator
{
.ublic int Add3umber(int num1+ int num!)
{
int result;
result = num1 " num!;
return result;
*
*
In the preceding code snippet, the public access specifier states that the method can be
accessed from outside the class. he method is returning the integer value as specified in the
method declaration. 'dd+umber is the name of the method. It is good practice to specify the
method name in Pascal "ase. he method is ta*ing two integers as the parameters and
retuning the value stored I result variable.
Calling !ethods
'fter defining the method, you can tell it by using the name of the method. he method name
is followed by parentheses even if the method call has no parameters, as shown in the
following e!ample$
Bethod+ame ( )R
he following is an e!ample of calling methods$
using System;
class #alculator
{
.ublic int Add3umber(int num1+ int num!)
{
int result;
result = num1 " num!;
return result;
*

static void Main(string[] args)
{
#alculator cal = ne/ #alculator();
:: 7(e follo/ing statement is calling t(e Add3umber met(od
and
:: .assing 10 and !0 as t(e .arameter list
int value = cal$Add3umber(10+ !0);
#onsole$%rite&ine('7(e result is {0*'+ value);
#onsole$,ead&ine();
*
*
he preceding e!ample begins at the start of the Bain() method of the "alculator class. 'n object
named cal is created to access the method of the class. 3hen you call the method 'dd+umber
(int num;, int numD), pass two integer values 'dd+umber(;E, DE) to the method. his method
returns an integer value, which is stored in the variable, value.
,ince the return type of Bain( ) is void, the return statement is not returning any value. he return
statement is used to ma*e a method return immediately to the caller. 3ithout a return statement,
the e!ecution returns to the caller by default when the last statementin the method is reached.
his type of return is called an immediate return.
)ou can also call public methods from other classes by using the object of the class. he
following e!ample shows how to call the method of "alculator class from est class$
using System;
class #alculator
{
.ublic int Add3umber(int num1+ int num!)
{
int result;
result = num1 " num!;
return result;
*
*
class 7est
{

static void Main(string[] args)
{
:: #reating an obDect of a class #alculator
#alculator cal = ne/ #alculator();
:: #alling t(e met(od Add3umber(10+!0)of t(e class
#alculator
int value = cal$Add3umber(10+ !0);
#onsole$%rite&ine('7(e result is {0*'+ value);
#onsole$,ead&ine();
*
*
' method can call itself. his is *nown as recursion.
he following is an e!ample of the recursive method$
using System;
class 3umber
{
.ublic int -actorial(int n)
{
int result;
if (n == 1)
return 1;
else{
{
result = -actorial(n01) >n;
return result;
*
*
static void Main(string[] args)
{
3umber obD = ne/ 3umber();
#onsole$%rite&ine('-actorial of 9 is)');
obD$-actorial(9);
#onsole$%rite&ine('-actorial of E is)');
obD$-actorial(E);
#onsole$%rite&ine('-actorial of 4 is)');
obD$-actorial(4);
#onsole$,ead&ine();
*
*
In the preceding code, the factorial ( ) method is recursive method. If the value entered by the
user is not ;, this method will call itself.
:sing !ethods (ith para!eters
's discussed earlier, parameters allow information to be passed in and out of method. 3hen you
define a method, you can include a list of parameters in parentheses.
eclaring !ethods (ith "ara!eters
%ach parameter has a type and name. )ou can declare parameters by placing parameter
declarations inside parentheses. ' synta! that is used to declare parameters is similar to the
synta! that is used to declare local variables. :owever, you can separate each parameter
declaration with a comma.
he following e!ample shows how to declare a methos with parameters$
Coid Bethod3ithParameters(int n, string y)
N
YY 7..
S
he preceding code declares the method Bethod3ithParameters with two parameters n and y.
the first parameter is of type int, and the second parameter is of type string.
Calling !ethods (ith para!eters
3hen a method with parameters is called, you must pass the parameters to the method.
Parameters can be passed by using any one of the following mechanism$
Calue$ 'resometimes called in parameters, therefore, the data can be transferred into the
method but cannot be transferred out.
Geference$ 're sometimes called inYout parameters, therefore, the data can be
transferred into the method and out again.
Output$ 're sometimes called out parameters, therfore, data can be transferred out of the
method.
Pass parameter by value$
Pass by value is defalut mechanism for passing parameters to a method. he simplest
defenition of a value parameter is a data type name followed by a variable name. when a method
is called, a new storage location is created for each value parameter. he values of the
corresponding e!pressions are copied into them. he e!pression supplied for each value
parameter must be similar to the declaration of the value parameter. Or it must be a type that can
be implicity converted to the value type.

he synta! of declaring value parameter is as follows$
\return type] Bethod+ame(\data type] variable+ame)
N
QQQ 7.
S
3ithin the method, you can write code that changes the value of the parameter. ' parameter will
have no effect any variables outside the method call.
In the following e!ample, the variable var inside 'ddOne() method separate from the variable
number in the Bain() method and it can be changed in 'ddOne(), wihtout effecting var$
using System;
class #alculator
{
void AddFne(int var)
{
var"";
*

static void Main(string[] args)
{
#alculator obD = ne/ #alculator();
int number = G;
obD$AddFne(number);
#onsole$%rite&ine(number); ::@is.lay t(e value of G not H
*
*
he graphical representation of the memory allocated to the variables is shown in the following
figure$
Pass Parameter by Geference
*e&ory allocated to %al!e type para&eters
Pass Parameter by Geference
' reference parameter is a reference to a memory location of a data member. Hnli*e a value
parameter, a reference parameter does not create a new storage location. Instead, a reference
parameter represents the same location in memory as the variable that is supplied in the method
call.
)ou can declare a reference parameter by using the ref *eyword before the data types, as shown
in the following e!ample$
void S(o/,eference(ref n8d+ ref long n#ount)
{
:: $$$$
*
he ref *eyword only applies to the parameter following it and not to the whole parameter list.
"onsider the following method, in which nId is passed by reference but longCar is passed by
value$
void Fne,efFneVal(ref n8d+ long longVar)
{
:: $$$$
*
3hen calling the method, you supply reference parameters by using the ref *eyword, which is
followed by a variable name. he value supplied in the call to the method must e!actly match the
type in the method definition. 'nd, it must be a variable, not a constant or a calculated
e!pression.
he following is an e!ample of calling a method with reference type parameters$

num!er
var

var
"
#ain$%
&dd'ne$%
&dd'ne$%
Before #ethod Call &fter #ethod Call
class #alculator
{
void AddFne(ref int var)
{
var"";
*
static void Main(string[] args)
{
#alculator obD = ne/ #alculator();
int number = G;
obD$AddFne(ref number);
#onsole$%rite&ine(number); ::@is.lay t(e value H
*
*
he graphical representation of the memory allocated to the variables of the preceding code is
shown in the following figure$
If you omit the ref *eyword or if you supply a constant or a calculated e!pression, the compiler will
reject the call. )ou will receive an error message that is similar to the message$ 6"annot convert
from -int. to -ref int.8.
Pass parameter by Output
's discussed earlier, to return a value from a method you can use the return statement. ' return
statement can be used to return only a single value. his limitation is overcame by the output
parameter.
num!er num!er
var var
"
((( (((
#ain$% #ain$%
&dd'ne$% &dd'ne$%
&t the method call &fter execution of
var)) statement
Output parameters are li*e reference parameters, e!cept that they transfer data out of the
method rather than into it. 'n output parameter is a reference to a storage location supplied by
the caller. :owever, the variable that is supplied for the output parameter does not need to be
assigned a value before the call is made, and the method will assume that the parameter has not
been initiali2ed on entry.
Output parameters are useful when you want to return values from a method by means of a
parameter without assigning an initial value to the parameter. o declare an output parameter,
use the *eyword out before the data type and the variable name.
he following is an e!ample of output parameters$
static void Fut@emo(out int variable)
{
:: $$$
*
he out *eyword only affects one parameter, and each output parameter must be mar*ed
separately. 3hen calling a method with an output parameter, place the out *eyword before the
variable to be passed, as shown in the following e!ample$
int var;
Fut@emo(out var);
In the body of the method being called, no initial assumptions about the contents of the output
parameter are made. It is treated li*e an unassigned local variable. he output parameter must
be assigned a value inside the method.
Activity- )(apping T(o 2u!bers by :sing Methods (ith "ara!eters
"roble! )tate!ent
3rite a program to swap two numbers by using reference type parameters in the method.
,olution
o write the re/uired program, perform the following steps$
;. ,elect )tart All "rogra!s Accessories 2otepad
D. 3rite the following program code in +otepad
using System;
using System$#ollections$Ieneric;
using System$7eJt;
.ublic class S/a.3umber
{
void S/a.3um(ref int a+ ref int b)
{
int tem.;
tem. = a;
a = b;
b = tem.;
*
static void Main(string[] args)
{
S/a.3umber classobD = ne/ S/a.3umber();
int number1+ number!;
#onsole$%rite&ine('5nter t(e first number)');
number1 = #onvert$7o8nt9!(#onsole$,ead&ine());
#onsole$%rite&ine('5nter t(e second number)');
number! = #onvert$7o8nt9!(#onsole$,ead&ine());
#onsole$%rite&ine('7(e value of t(e first number is {0*'+
number1);
#onsole$%rite&ine('7(e value of t(e second number is {0*'+
number!);
classobD$S/a.3um(ref number1+ ref number!);
#onsole$%rite&ine('3o/ t(e value of t(e first number after
s/a..ing is {0*'+ number1);
#onsole$%rite&ine('3o/ t(e value of t(e second number after
s/a..ing is {0* '+ number!);
#onsole$,ead&ine();
*
*
?. ,elect File )ave to save the program file. he )ave As dialog bo! opens
@. %nter )(ap2u!ber*cs in the File na!e te!t bo!. he filename is saved with the .cs
e!tension, signifying that it is a "# program.
A. "lic* the )ave button in the )ave As dialog bo!
<. ,elect )tart all progra!s1isual studio 04451isual studio Tools 1isual
studio 0445 co!!and pro!pt to open the visual studio DEEA command prompt window
>. In the 1isual studio 0445 Co!!and "ro!pt window, move to the location where the
program file is saved
<. "ompile the program file by using the following command
"sc ,wap+umber.cs
=. %!ecute the compiled program as $
,wap+umber.e!e
;E. Cerify the output of the e!ecuted program
:sing )tatic 1ariables and )tatic Functions
%ach object has its own set of member variables. 'll the member variables have a scope. (or
e!ample, if you create the temp integer variable inside a function, the variable will be destroyed
when the function e!ecution completes. In other words, every time the function is called, temp will
be created, initiali2ed, and then destroyed when the function e!ists. If you want a variable to
retain its value throughout the program, you can declare it as a static variable in the program. o
manipulate and use the values of static variables, you can also define a function as static.
)tatic 1ariables
he *eyword -static. means that only one instance of a given variable e!ists for a class. ,tatic
variables are used to define constants because their values can be retrieved by invo*ing the
class without creating an instance of it.
,tatic variables can be initiali2ed outside the member function or class definition. he following
code is an e!ample of static variables, which shows the declaration and initiali2ation of a static
variable. "onsider the following e!ample of static variables$
using System;
class 6rogram
{
static void Main(string[] args)
{
Static5Jam.le$ivar = 1; ::static variable initialiKed
#onsole$%rite&ine(Static5Jam.le$ivar$7oString());
#onsole$,ead&ine();
*
*
.ublic class Static5Jam.le
{
.ublic static int ivar; ::static variable declared
Static5Jam.le()
{
#onsole$%rite&ine('FbDect #reated');
*
*
In the preceding code, a static variable is initiali2ed outside the class definition. "reating more
than one object will not reinitiali2e the static variable. Hnli*e other member variables, only one
copy of the static variable e!ists in the memory for all the objects of that class. herefore, all
objects share one copy of the static variable in the memory.
"onsider a situation where you are re/uired to trac* the number of objects created for a class. If
you declare a non-static member variable called counter, every instance of the class will create a
separate variable. 'nd there will be no variable with a count of the total number of created
objects. o avoid such a situation you can use static member variables because the single static
variable gets incremented by all objects.
)ou can also initiali2e the static variable inside the class definition, as shown in the following
e!ample of static variables$
using System;
class Static
{
static void Main(string[] args)
{
Static5Jam.le s1 = ne/ Static5Jam.le();
Static5Jam.le s! = ne/ Static5Jam.le();
s1$count();
s1$count();
s1$count();
#onsole$%rite&ine('7(e value of variable is {0*'+
s!$dis.lay());

#onsole$,ead&ine();
return 0;
*
*
.ublic class Static5Jam.le
{
.ublic static int s;
.ublic void count()
{
s"";
*
.ublic int dis.lay()
{
return s;
*
*
'vani.s +ote $ Geturn E in the main function throws an error. If that statement is commented then
the rest of the program returns the desired output.
)tatic Functions
)ou can declare a static function. ,uch functions can access only static variables. In a situation
where you want to chec* whether an object of a class has been created, you ma*e use of static
functions because they e!ist even before the object is created.
he following is the e!ample of static functions$

'ctivity$ "ounting the +umber of imes (unction is "alled by Hsing ,tatic (unctions$
Problem ,tatement
,olution
o write the re/uired program, perform the following steps$
;. ,elect )tart All "rogra!s Accessories 2otepad
using System;
class Static
{
static void Main(string[] args)
{
Static5Jam.le s = ne/ Static5Jam.le();
s$count();
s$count();
s$count();
#onsole$%rite&ine('7(e value of variable is {0*'+
Static5Jam.le$dis.lay());

#onsole$,ead&ine();
::return 0;
*
*
.ublic class Static5Jam.le
{
.ublic static int s;
.ublic void count()
{
s"";
*
.ublic static int dis.lay()
{
return s;
*
*
D. 3rite the following program code in +otepad
?. ,elect File )ave to save the program file. he )ave As dialog bo! opens
@. %nter FunctionCount*cs in the File na!e te!t bo!. he filename is saved with the .cs
e!tension, signifying that it is a "# program.
A. "lic* the )ave button in the )ave As dialog bo!
=. ,elect )tart all progra!s1isual studio 04451isual studio Tools 1isual
studio 0445 co!!and pro!pt to open the visual studio DEEA command prompt window
>. In the 1isual studio 0445 Co!!and "ro!pt window, move to the location where the
program file is saved
<. "ompile the program file by using the following command
"sc FunctionCount.cs
=. %!ecute the compiled program as $
FunctionCount.e!e
;E. Cerify the output of the e!ecuted program
"ractice .uestions
;. ,tate whether the given statement is true or false
%ncapsulation means preventing access to nonessential data
D. "onsider the following statements
,tatement '$ ,tatic variables retain their values even after the function to which they
belong have been e!ecuted
,tatement 0$ ,tatic functions can access static as well as non-static variables
3hich of the given statements are true
a) ' and 0 both are true
b) ' is true and 0 is false
c) ' is false and 0 is true
d) ' and 0 both are false
?. 3hich of the following statement about access specifiers is true1
using System;
.ublic class -unction#ount
{
.ublic static int count = 0;
.ublic static void #ount-unction()
{
count"";
System$#onsole$%rite&ine('#ount function is called by
Main {0* times'+ count);
*
static void Main(string[] args)
{
for (int var = 0; var 10; var"")
{
-unction#ount$#ount-unction();
*
#onsole$,ead&ine();
*
*
a. 'n access specifier determines which feature of a class can be used by other classes
b. Protected variables are not accessible to the subclasses of the class in which they are
declared
c. ' method declared as public in a superclass cannot be accessed by the subclasses of that
superclass
d. ' variable declared inside a method can have access specifiers
@. ,tate whether the following statement is true or false
In a public access specifier, all the public members of the base class become protected
A. ,tate whether the given statement is rue of (alse$
'bstraction represents the essential characteristics of an object or classes that
differentiate it from other objects or classes
)u!!ary
In this chapter, you learned that$
'bstraction is the process of reducing information content in order to retain only the
relevant information for a particular purpose
%ncapsulation is the process of hiding all the details of an object that do not contribute to
it essential characteristics
'n access specifier is used to determine whether any other class or function can access
the member variables and functions of a particular class
he public access specifier allows a class to e!pose its member variables and member
functions to other functions and objects
he private access specifier allows a class to hide its member variables and member
functions from other class functions and objects
he protected access specifier allows a class to hide its member variables and member
functions from other class functions and objects, just li*e the private access specifier
while implementing inheritance
' method is a set of one or more program statements that can be e!ecuted by referring
to the method name
&efining a method means declaring the elements of its structure
he access modifiers that can used with methods are public, protected, internal,
protected internal and private
Parameters allow information to be passed into and out of a method. 3hen you define a
method, you can include a list of parameters in parenthesis
Parameters can be passed by using any one of the following parameter types$
o Calue
o Geference
o Output
Pass by value is the default mechanism for passing parameters in "#.
' reference parameter is a reference to a memory location of a data member
Output parameters are li*e reference parameters, e!cept that they transfer data out of
the method rather than into it
he return statement is used to ma*e a method return immediately to the caller
he static variable retains its value even after the function to which it belongs has been
e!ecuted
he static functions can access only static variables. +on-static variables cannot be
accessed by using static functions
Exercises
Exercise /
3rite a program that emulates a calculator. he calculator should consist of the following
methods$
'ddition
,ubtraction
Bultiplication
&ivision
%ach method should have a minimum of two parameters
Exercise 0
3rite a program to identify the greatest of three numbers entered by a user. "reate this program
by using methods
Exercise 6
3rite a program to calculate the factorial of the number entered by a user. "reate this program
by using static functions and static variables.
:int$ he limit of users input should be ;-DE.
Exercise 7
Information echnologies is a software development organi2ation. 'nnie a software developer of
the organi2ation is currently under a project of cineple!es. ,he has to develop a program that a
program that counts the number of tic*ets sold. If a tic*et is not sold, the program should give the
following message 6)ou should sell the tic*ets8.
Chapter %
Creating 1alue Types and Reference Types
he variables in a program are allocated memory at run time in the system. In "#, variables are
referred in two ways, value type and reference type. Calue type variables contain data, whereas
reference type variables hold the reference to the memory location where data is stored.
his chapter e!plains how "# manages memory for its data type variables. It also e!plains the
implementation of value types such as structure and enumeration. his chapter describes how to
implement reference types such as arrays and collections in "#.
Objectives
In this chapter, you will learn to
&escribe memory allocation
Hse structures
Hse enumerations
Implement arrays
Hse collections
&escribing Bemory 'llocation
he memory allocated to variables is referred to in two ways, value types and reference types. 'll
the built-in data types such as int, char, and float are value types. 3hen you declare an int
variable, the compiler generates code that allocates a bloc* of memory to hold an integer.
int 3um1 = 40;
he preceding statement assigns a value to the int type variable +um; and the value is copied to
the memory.
Geference types, such as classes are handled differently by the compiler. 3hen you declare a
class variable the compiler does not generate code that allocates a bloc* of memory to hold a
class. Instead it allocates a piece of memory that can potentially hold the reference to another
bloc* of memory containing the class. he memory for the class object is allocated when the new
*eyword is used to create an object.
Calue type contains data. Geference types contain address referring to a bloc* of memory. Calue
types are also called direct types because they contain data. Geference types are also called
indirect types because they hold the reference to the location where the data is stored.
o understand value type referencing, consider a scenario, where you declare a variable named
+um; as an int and assign the value AE to it. If you declare another variable +umD as an int, and
assign +um; to +umD, +umD will contain the same value as +um;. :owever, both the variables
contain different copies of the value AE. If you modify the value in +um;, the vlaue in +umD does
not change. he following code is an e!ample of value type variables$
int 3um1 = 40; ::declare and initialiKe 3um1
int 3um! = 3um1; ::3um! contains t(e co.y of t(e data in 3um1
3um1""; ::incrementing 3um1 /ill (ave no effect on t(e value of 3um!
he following figure is a diagrammatic representation of the memory allocated to the value type
variable.
+ote$
'll value types are created on the stac*. ,tac* memory is organi2ed li*e a stac* of boo*ed piled
on a rac*.
o understand reference types, consider a class named "ar. he object Bercedes of the class
"ar is initiali2ed with (ord, which is also an object of the same class. In this case both (ord and
Bercedes will refer to the same object.
he following code is an e!ample of reference type variables
he following figure is the diagrammatic representation of the memory allocated to the reference
type variable.
Memory allocated for value type variable
int 3um1;
3um1 = 40;
int 3um!;
3um! = 3um1;
$'
$'
+um;
+umD
using System;
names.ace ,efL7y.e
{
class #ar
{
.ublic int Model;
.ublic void @is.layLModel()
{
#onsole$%rite&ine(Model);
*
*

class class1
{
static void Main(string[] args)
{
#ar -ord = ne/ #ar();
-ord$Model = 10;
#ar Mercedes = -ord;
Mercedes$@is.layLModel();
-ord$@is.layLModel();
*
*
*
+ote$
'll reference types are created on the heap. :eap memory is li*e boo*s arranged ne!t to each
other in rows.
3e have discussed int as a value type in the preceding e!amples, which is a built-in data type.
here are more value types li*e, structures and enumerations, which are user-defined data types.
3e also discussed class as reference type. here are more e!amples are reference types li*e
arrays and collections.
Hsing ,tructures
' structure is a value type data type. 3hen you want a single variable to hold related data of
various data types, you can create a structure. o create a structure you use the struct *eyword.
(or e!ample, if you want to maintain bill details, such as invM+o, ordM,t, cust+ame, product, cost
and dueM'mt, in a single variable, you can declare a structure. he following code shows the
synta! of a structure data type$
struct 1illL@etails
{
.ublic string invL3o; ::invoice 3umber
.ublic string ordL@t; ::Frder @ate
.ublic string cust3ame; :: #ustomer 3ame
.ublic string .roduct; ::6roduct 3ame
.ublic double cost; ::#ost of t(e .roduct
.ublic double dueLAmt; ::7otal Amount @ue
*
4i*e classes, structures contain data members which are defined within the declaration of the
structure. :owever, structures differ from classes and the differences are$
,tructures are value types and they get stored in a stac*
,tructures do not support inheritance
,tructures cannot have default constructor
he following program uses the 0illM&etails structure$
#ar -ord = ne/ #ar();
-ord$Model = 10;
#ar Mercedes;
Mercedes = -ord;
(((
(((
(ord
Bercedes *+
using System;
names.ace 1ills
{
.ublic struct 1illL@etails
{
.ublic string invL3o;
.ublic string ordL@t;
.ublic string cust3ame;
.ublic string .roduct;
.ublic double cost;
.ublic double advanceLAmt;
.ublic double dueLAmt;
*
class 7estStructure
{
.ublic static void Main(string[] args)
{
1illL@etails billFbD = ne/ 1illL@etails();
billFbD$invL3o = 'A101';
billFbD$ordL@t = '10:10:0';
billFbD$cust3ame = 'Moe';
billFbD$.roduct = '6etrol';
billFbD$cost = 100;
billFbD$advanceLAmt = 40;
billFbD$dueLAmt = 40;
#onsole$#lear();
#onsole$%rite&ine('8nvoice number is {0*'+ billFbD$invL3o);
#onsole$%rite&ine('Frder @ate is {0*'+ billFbD$ordL@t);
#onsole$%rite&ine('#ustomer 3ame is {0*'+ billFbD$cust3ame);
#onsole$%rite&ine('6roduct 3ame is {0*'+ billFbD$.roduct);
#onsole$%rite&ine('#ost is {0*'+ billFbD$cost);
#onsole$%rite&ine('Advance Amount is {0*'+
billFbD$advanceLAmt);
#onsole$%rite&ine('@ue Amount is {0*'+ billFbD$dueLAmt);
*
*
*
:sing Enu!erations
%numerations is a value type data type, which means that enumeration contains its own values
and cannot inherit or cannot pass inheritance. %numerator allows you to assign symbolic names
to integral constants. (or e!ample, you may want to write a program to represent the wee*days in
a program. )ou could use the integers E, ;, D and ? to represent ,aturday, ,unday, Bonday and
uesday respectively. his representation would wor*, but it has a problem. It is not convinient. If
the integer value E is used in code, it would not be obvious that E represents ,aturday or ,unday.
o overcome such a problem, you can use enumeration. o enumerate, you can use the enum
*eyword.
eclaring an Enu!eration
o declare an enumeration type called &ays, where the values are restricted to the symbolic
names of the wee*days, use the following code$
enum @ays {Sat+ Sun+ Mon+ 7ue+ %ed+ 7(u+ -ri *;
he names of days must appear within the braces and must be separated by commas. he
enumeration type associates a numeric value with every element. 0y default, the se/uence of
values starts from E for the first element and goes forward by incrementing ; each time.
#!ple!enting Enu!erations
'fter declaring the enumeration type, you can use the enumeration type in the same manner as
any other data type, as shown in the following code$
using System;
names.ace 5num@ays
{
class 5num7est
{
enum @ays { Sat+ Sun+ Mon+ 7ue+ %ed+ 7(u+ -ri *;
static void Main(string[] args)
{
int -irstL@ay = (int)@ays$Sat;
int &astL@ay = (int)@ays$-ri;
#onsole$%rite&ine('Sat = {0*'+ -irstL@ay);
#onsole$%rite&ine('-ri = {0*'+ &astL@ay);
#onsole$,ead&ine();
*
*
*
In the preceding code, the enum has been declared as &ays. hi enum has symbolic names,
which appear wihtin braces. In the class %numest, Bain() function displays the values of enum
&ays. he local variable (irstM&ay and 4astM&ay holds the value of enum and displays the value
,at and ,un as an output.
#!ple!enting Arrays
'n array is a collection of values of the same data type. (or e!ample, you can create an array
that stores ;E integer type values. he variables in an array are called the array elements. 'rray
elements are accessed using a single name and an inde! number representing the position of the
element within the array. 'rray is a reference type data type. he following figure shows the array
structure in the system.s memory.
&rray ,ame Index
Index
-alue + -alue
&eclaring an 'rray
'n array needs to be declared before it can be used in a program. )ou can declare an array by
using the following statement$
&atatypeOP 'rray+ameR
he e!planation of the elements of the preceding statement is as follows$
&atatype$ Is used to specify the data type for the elements, which will be stored in the
array.
O P$ Is used to specify the ran* of the array. Gan* is used to specify the si2e of the array.
'rrayname$ Is used to specify the name of the array using which the elements of the
array will be initiali2ed and manipulated.
he following is an e!ample of the array declaration$
int[] Score;
#nitialiBing and Assigning 1alues to Array
&eclaring an array variable does not initiali2e the array in the memory. 3hen the array variable is
initiali2ed, you can assign values to the array elements.
#nitialiBing Array
'rray is a reference type, therefore you need to use the new *eyword to create an instance of the
array. )ou must have noticed that while declaring the array, the si2e of the array, the si2e of the
array was not mentioned. he si2e of the array is specified while it is initiali2ed. he following
statement is an e!ample of array initiali2ation$
int[] Score; ::Array declaration
Score = ne/ int[10]; ::Array 8nstance
he preceding two statements can be combined into a single statement, and written as follows$
int[] Score = ne/ int[10];
In "#, the array subscript always starts with 2ero. herefore, the preceding statement creates as
array of integers containing ;E elements, from E and =.
Assigning 1alues to the Array
)ou can assign values to each element of the array by using the inde! number, which is also
called the array subscript of the element. (or e!ample, to assign the value A to the first element of
the array, you can use the following code$
int[] Score = ne/ int[N];
Score[0] = 4;
)ou can also assign values to the array at the time of declaraiton. :owever, in case of such
e!plicit initiali2ation, you cannot specify the si2e of the array, as shown in the following e!ample$
int[] Score = { 4+ 10+ 14 *;
he "# compiler implicitly initiali2es each array element to a default value depending on the array
type. (or e!ample, integer array would be initiali2ed by E implicitly by the compiler.
)ou can also create and initiali2e can integer array containing ;E elements, as shown in the
following code snippet$
int[] Score = ne/ int[10] { 0+ 1+ !+ 9+ E+ 4+ G+ H+ O+ N *;
In the preceding statement, the only curly braces ( NS ) are used to initiali2e the array elements.
int[] Source = ne/ int[10] { 0+ 1+ !+ 9+ E *;
int[] 7arget = Source;
In the preceding statement, if you declare the array, you can omit the si2e of the array. his is
shown in the following statement$
Copying an Array
3hen an array is initiali2ed, you can access the element values and manipulate them. he
following code is an e!ample of array manipulation$
::code to c(ec2 a .alindrome c(aracter array
using System;
names.ace Multi.leArray
{
class 6alindrome
{
static void Main(string[] args)
{
c(ar[] Str = ne/ c(ar[10];
::5nter t(e .alindrome string
#onsole$%rite&ine('5nter t(e 6alindrome String (MaJ 10
c(ar))');
::Acce.ting a string and converting into c(ar array
Str = #onsole$,ead&ine()$7o#(arArray();
::#alling t(e c(ec26alindrome met(od
#onsole$%rite&ine(c(ec26alindrome(Str));
#onsole$,ead&ine();

*
.rivate static bool c(ec26alindrome(c(ar[] myString)
{
int start#(ar;
int last#(ar;
start#(ar = 0;
::using &engt( met(od to calculate t(e total c(aracters in
t(e array
last#(ar = myString$&engt( 0 1;
::5Jecuting t(e loo. till t(e last c(aracter in t(e array
/(ile (start#(ar last#(ar)
{
::c(ec2ing if t(e arrays from bot( t(e ends are eCual
if (myString[start#(ar] == myString[last#(ar])
{
start#(ar"";
last#(ar00;
*
else
{
return false;
*
*
return true;
*
*
*
In the preceding e!ample, a character array is declared and initiali2ed. he value in the array is
entered by the user, which is e!pected to be a palindrome. 4ength() method is used to calculate
the length of the array my,tring and stored in a variable named last"har. 3hile storing the length,
the value is decreased by ; because the subscript inde! number of the array starts with E. he
while loop is used to repeat the statements for comparing the characters in the array. ^^ operator
is used to chec* the e/uality of characters in the array.
Bany other loops are used to manipulating arrays. he foreach loop is however specifically used
for manipulating arrays.
Foreach usage
' statement that iterates through an array and e!ecuted the same set of instructions on each
element is very common. )ou can use any looping construct to iterate through an array, but the
foreach statement interprets the common looping process by removing the need for you to chec*
the array si2e.
he following is the synta! of the foreach statement$
foreac((ty.e identifier in eJ.ression)
statement0bloc2
he following code has a set of instructions to declare an array called +umbers, process an array
with the foreach statement, and write the values to the console, one line at a time$
using System;
names.ace -or5ac(
{
class -or5ac(5Jam.le
{
static void Main(string[] args)
{
int[] 3umbers = {E+9+!+1+0+01+0!+N+4*;
#onsole$%rite&ine('7(e contents of an array is)');
foreac( (int P in 3umbers)
{
#onsole$%rite('{0* Bt'+ P);
*
#onsole$,ead&ine();
*

*
*
,imilar to other data types, you can also pass arrays as parameter to a method.
"ara! Arrays
3hile declaring a method if you are not sure about the number of arguments passed as a
parameter, you can use the param array.
he following code is an e!ample of using the param array in the methods parameter list$
using System;
names.ace 6aramArrays
{
.ublic class 6aram5Jam.le
{
.ublic int AddingLArray5lement(.arams int[] &ist)
{
int 7otal = 0;
foreac( (int 8 in &ist)
{
7otal "= 8;
*
return 7otal;
*
*
class 7ester
{
static void Main(string[] args)
{
6aram5Jam.le 6aramL5Jam = ne/ 6aram5Jam.le();
int 7otal = 6aramL5Jam$AddingLArray5lement(1+!+9+E+4+G+H);
#onsole$%rite&ine('7(e result is {0*'+ 7otal);
#onsole$,ead&ine();
*

*
*
+ote$
In the parameter list of a method, param array should be the last parameter.
Activity- Matrix )ubtraction :sing Arrays
d.
"roble! )tate!ent
&avid, a student of "alifornia Hniversity, is currently pursuing 0.,c(I). :e is wor*ing on a project
named Batri! ,ubtraction. :e needs to perform the following tas*s for his project$
'ccept data in two arrays
Perform the subtraction operation
Cerify the value of subtraction
:elp &avid to create the "# program using Cisual ,tudio I&%.
)olution
o solve the preceding problem, &avid needs to perform the following tas*s$
;. "reate a "onsole-based application for Batri! subtraction.
D. 0uild and e!ecute an application
as* ;$ "reating a "onsole-0ased 'pplication for Batri! ,ubtraction
o create a console-based application for Batri! subtraction, &avid needs to perform the following
steps$
/* ,elect )tart All "rogra!s Microsoft 1isual )tudio 0445 Microsoft 1isual
)tudio 0445* he )tart "age C Microsoft 1isual )tudio window will be displayed
0* ,elect File 2e( "roject* he 2e( "roject dialog bo! will be displayed
6* ,elect the project type as 1isual C$ from the "roject types pane and Console
Application from the Te!plates pane.
7* ype the name of the new project as Matrix)ubtractionApp in the 2a!e te!t bo!.
5* ,pecify the location where the new project is to be created as c-Dchapter5DActivity in the
,ocation combo bo!.
3* "lic* the O' button.
8* Open the )olution Explorer window and right-clic* the "rogra!*cs file.
9* ,elect the Rena!e option and type the new name as Matrix)ubtraction*cs
2ote-
Hhile rena&ing the rogra&.cs file, the *icrosoft Vis!al St!dio &essage bo1 #Fo! are
rena&ing a file. Ho!ld yo! also li,e to perfor& a rena&e in this project of all references
to the code ele&ent 5rogra&6I' &ight appear. Clic, the Fes b!tton to proceed.
>* &ouble-clic* the Matrix)ubtraction*cs file in the solution explorer window. he code
view of the Matrix)ubtraction*cs file is displayed
/4* Geplace the e!isting code with the following code$
using System;
names.ace MatriJSubtractionA..
{

class MatriJSubtraction
{
.ublic void subtract()
{
int[] Array1;
int[] Array!;
int[] Array9;
Array1 = ne/ int[9] { !+ 9+ E *;
Array! = ne/ int[9] { 1+ !+ 9 *;
Array9 = ne/ int[9];
#onsole$%rite&ine('7(e #ontents of t(e Array 1 is)');
for (int i = 0; i 9; i"")
{
#onsole$%rite&ine('{0* Bt'+ Array1[i]);
*
#onsole$%rite&ine('7(e #ontents of t(e Array 1 is)');
for (int i = 0; i 9; i"")
{
#onsole$%rite&ine('{0* Bt'+ Array![i]);
*
::Subtraction of Array
for (int i = 0; i 9; i"")
{
Array9[i] = Array1[i] 0 Array![i];
*
::@is.lay t(e #ontents of -inal Array
#onsole$%rite&ine('Bn 7(e ,esult of Array Subtraction is)');
for (int i = 0; i 9; i"")
{
#onsole$%rite&ine('{0* Bt'+ Array9[i]);
*
*

static void Main(string[] args)
{
MatriJSubtraction obD = ne/ MatriJSubtraction();
obD$subtract();
#onsole$,ead&ine();
*

*
*
as* D$ 0uilding and %!ecuting an 'pplication
o build and e!ecute the application, &avid needs to perform the following steps$
;. ,elect Auild Auild )olution or press F3 to build the solution
D. ,elect ebug )tart ebugging or press F5 to e!ecute the application
?. Cerify the output of the application
Multidi!ensional Arrays
he ran* value of the array is also *nown as the dimension of the array. he arrays declared and
used in the preceding e!amples are the single dimensional arrays. In single dimensional array,
values are stored in a row. )ou can also declare a multidimensional array, which stores data
using a different dimension. he following figure is a graphical representation of a single
dimensional array and a multidimensional array.
he following code is an e!ample of a multidimensional array$
int[] 3um;
int[] 3um; int[+] 3um;
0 1 ! 9 E
0
1
0 1 ! 9 E
Single and *!lti(i&ensional .rray
using System;
using System$#ollections$Ieneric;
using System$7eJt;
names.ace Multi@imArray
{

class MultiArray5Jam.le
{
static void Main(string[] args)
{
int sum = 0;
int ro/Sum;
int[+] mArray = ne/ int[!+ E] {
{ !+ ! *+ { 9+ 9+ 9+ 9 * *;
for (int ro/ = 0; ro/ ! ; ro/ "")
{
ro/Sum = 0;
for (int col =0; col E; col"")
{
#onsole$%rite('{0* Bt)'+ mArray[ro/+col]);
ro/Sum = ro/Sum " mArray[ro/+ col];
*
sum = sum " ro/Sum;
#onsole$%rite('= {0*'+ ro/Sum);
#onsole$%rite&ine();
*
#onsole$%rite&ine('7(e sum of t(e array is ){0*'+ ro/Sum);
#onsole$,ead&ine();
*

*
*
AvaniQs 3ote ) 5rror at t(e initialiKation$
The Array Class
he 'rray class is the base class for all the arrays in "#. he 'rray class is defined in the ,ystem
namespace. he 'rray class provides properties and methods to wor* with arrays.
Properties
he following table e!plains some of the most commonly used properties of the 'rray class
"roperties Explanation
Jength Ret!rns the total n!&ber of ite&s in all the di&ensions of an array
Ran, Ret!rns the total n!&ber of ite&s in all the di&ensions of an array
Is"i1edSi<e Ret!rns a %al!e indicating if an array has a fi1ed si<e or not
IsReadOnly Ret!rns a %al!e indicating if an array is read9only or not
Co&&only Esed .rray Class roperties
Bethods
he following table e!plains some of the most commonly used methods of the 'rray class.
Prperties E&p"anatin
Sort erfor&s sort operation on an array passed to it as a para&eter
Clear Re&o%es all ite&s of an array and sets a range of ite&s in the array to ;
KetJength Ret!rns the n!&ber of ite&s in an .rray
KetVal!e Ret!rns the %al!e of the specified ite& in an .rray
Inde1Of Ret!rns the inde1 of the first occ!rrence of a %al!e in a one9di&ensional .rray
or in a portion of the .rray
Co&&only Esed .rray class *ethods
:sing Collections
'rrays are useful, but they have their own limitations. 'rrays are used to collect the elements of
same data type. he .+% (ramewor* provides several classes that also collect elements in
speciali2ed ways. hese classes are the "ollection classes, and are declared in the
,ystem."ollections namespace and sub-namespaces.
he collection classes accept, hold, and return their elements as items. he element type of a
collection class is an object. o understand this, contrast an array of int variables (int as a value
type) with an array of objects (object is a reference type). int is a valu type, and an array of int
variables holds its int values directly, as shown in the following figure
In the preceding figure, consider the effect when the array is an array of objects. )ou can still add
integer values to this array. he int data type which is value type is automatically econverted to
reference type. his action is called bo!ing, as shown in the following figure
Val!e Stored in an int .rray
Arra&
) * + , -
int[] array = { N+H+9+!*;
,'"J :%'P
he element type of a collection class is an object. his means when you insert a value in to a
collection, it is always bo!ed. 3hen you remove the value from the collection, you must unbo! it
by using a cast. Enbo1ing means converting from reference type to value type.
he following are the various classes of the ,ystem."ollection namespace.
Class escription :se Exa!ple
.rrayJist Represents the ordered
collection of an object that
can be indi%id!ally inde1ed
Is !sed when yo! want to
access ele&ents by !sing
an inde1. In al&ost e%ery
sit!ation, an .rrayJist is a
good alternati%e to an array
Ite&s can be inserted
or re&o%ed at any
position in a &ailbo1
L!e!e Represents a firstMin,
firstMo!t collection of object
Ese /!e!e when yo! need
firstMin, firstMo!t access.
. /!e!e is often !sed to
hold ele&ents that are
discarded i&&ediately
thereafter, s!ch as
infor&ation in a b!ffer
Haiting in a /!e!e for
boo,ing a tic,et. Fo!
join the end of the
/!e!e and lea%e the
beginning of the
/!e!e.
Re/!ests co&ing
o%er a networ, are
/!e!ed and then
discarded after they
are processed
Stac, Represents a si&ple
lastMin, firstMo!t collection
of objects
Ese a stac, when yo! need
lastMin, firstMo!t access. .
stac, is often !sed to hold
ite&s d!ring calc!lations
. pile of plates, in a
c!pboard, where yo!
place the plates on
top, and also re&o%e
the& fro& the top.
+ash
2able
Eses a ,ey to access the
ele&ents in the collection
Ese a hash table when yo!
&!st access ele&ents by
!sing an inde1 and yo! can
identify a !sef!l inde1 %al!e
Fo! can access boo,
titles by their IS$8
n!&bers
Vario!s Collection Classes
$o1ing
Arra&
) ) ) ) )
int[] array = { N+H+9+!*;
> D
= >
,'"J :%'P
he 'rray4ist "lass
3hen you want to access the elements of an array through its inde! value location in an array,
use an 'rray4ist. he use of the 'rray4ist is an alternative to the use of the array, which has
limitations.
he limitations are$
o resi2e an array, you have to create a new array, copy the elements into the new array,
and then rearrange the array references.
o remove an element from an array, you need to create a copy of the element and then
shift all the remaining elements up.
o add an element in between an array, you have to shift an element down by one place
to empty a slot. :owever, you can lose the last element of the array.
he following table describes the use of various methods of an 'rray4ist class.
'ethd (se
.dd .dds an object to the end of the .rrayJist
Re&o%e Re&o%es the ele&ent at the first occ!rance of a specific object fro& the
.rrayJist
Clear Re&o%es all the ele&ents fro& the .rrayJist
Insert Inserts an ele&ent into the .rrayJist at the specified Inde1
2ri&2oSi<e Sets the capacity to the act!al n!&ber of ele&ents in the .rrayJist
Sort Sorts the ele&ents in the .rrayJist
Re%erse Re%erses the ele&ent in the .rrayJist
*ethods Esed in the .rrayJist Class
2ote
Fo! cannot !se the Re&o%e &ethod in a foreach loop that iterates thro!gh an .rrayJist.
"ractice .uestions
;. If an array is declared as, intOP arr ^ new int OAP, the total number of elements in the array
is MMMMM
a. A
b. D
c. ;
d. E
D. "onsider the following code
int 3umber1 = 0;
int 3umber! = 0;
int[] Array1 = ne/ int[] { !+9+E+4+G+H+O+N+10+11*;
foreac( (int #tr in Array1)
{
if (#tr R ! == 1)

3umber1"";
else
3umber!"";
#onsole$%rite&ine(#tr);

*
3hat is the output of the code$
a) ?,A,>,=,;;
b) D,@,I,<,;E
c) "tr
d) D,?,@,A,I,>,<,=,;E,;;
?. If an array is declared as string OP arr ^ new string OAP, the base type of the array is MMMMMM
a. string
b. int
c. long
d. byte
@. "onsider the following code
using System;
class Array#lass
{
static void Main(string[] args)
{
string[] StringLArray = ne/ string[E];
StringLArray[0] = 'str1';
StringLArray[1] = 'str!';
for (int i = 0; i !; i"")
{
#onsole$%rite&ine('arr[{0*] = {1*'+ i+ StringLArray[i]);
*
*
*
Ciew the problem statement and answer the following /uestion. what is the output of the
program1
a) str;
b) strD
c) %rror Bessage is displayed
d) arrOEP ^ str;
arrO;P ^ strD
A. he subscript number of an array starts from
a. E
b. -;
c. ;
d. D
)u!!ary
In this chapter, you learned that$
Bemory allocated to variables of two types, value type and reference type
Calue types are the simplest types in "#. Cariables of value types directly contain their
data in the variable
Geference type variables contain only a reference to data. he data is stored in a
separate memory area
' value type variable in the stac*
' reference type variable holds a reference to an object in the heap.
o hold related data of various data type in single variable, structures are used
"# provides the features of enum to create user defined data types with numbers as an
inde! value to access them
'n array is a collection of values of the same data type
he foreach statement interprets the common loop process and removes the need for
you to chec* the array si2e.
Param arrays are used in the methods with parameter list when the total number of
parameters is not *nown
he .+% (ramewor* provides several classes that also collect elements together in
other speciali2ed ways. hese are the collection classes, and they live in the ,ystem
namespace
'rray4ist is useful when you want to manipulate the values in an array easily
Exercises
Exercise /
&avid is wor*ing on a project where he needs to accept the total number of array elements and
values from the user. he also needs to arrange the array elements in ascending order, and
display the result
:int$ he array should be an integer array
Exercise 0
&avid is wor*ing on an application where he needs to accept the si2e of an array and its values.
:e needs to identify the largest and smallest number in the array and based on that he needs to
display the result.
Chapter 3
Constructors and estructors
"onstructors and destructors perform special functions as members of classes. "onstructors are
used to initiali2e objects. "onversely, you can use destructors to delete an object when it is not
re/uired.
his chapter introduces the concept of constructors and destructors. In addition, the chapter
e!plains how to implement constructors and destructors. he chapter also e!plains how
constructors and destructors help in identifying the life cycle of the object.
Objectives
In this chapter, you will learn to$
Implement constructors
Implement destructors
Identify the life cycle of an object
#!ple!enting Constructors
' constructor is a special type of method that is invo*ed when you create a new instance of a
class. ' constructor is used to initiali2e the members of a class. he name of a constructor is the
same as the name of the class that contains it.
' constructor is complementary to a destructor. It is good programming practice to use both
constructors and destructors.
The 2eed of Constructors
o initiali2e member variables, a function can be invo*ed as soon as the object is created. he
following program is an e!ample of writing an initiali2ation function$
using System;
names.ace #alc
{
class #alculator
{
static int number1+ number!+ total;
.ublic void 8nitialiKe()
{
number1 = 10;
number! = !0;
*
.ublic void Add3umber()
{
total = number1 " number!;
*
.ublic void @is.lay3umber()
{
#onsole$%rite&ine('7(e 7otal is ) {0*'+ total);
*
.ublic static void Main(string[] args)
{
#alculator c1 = ne/ #alculator();
c1$8nitialiKe();
c1$Add3umber();
c1$@is.lay3umber();
*
*
*
In the preceding e!ample, the c; object of the "alculator class has to call the Initiali2e() member
function to initiali2e the data members number; and numberD. however, you need to ensure that
the initiali2ation function is invo*ed.
OOP offers you a solution to overcome the preceding problem related to ensuring for invo*ing he
initiali2e function. 3hile designing a class, you can include a special member function within the
class. his member function is e!ecuted whenever an object of the class is created. ,uch
functions are called constructors.
Types of Constructors
here are D types of constructors, instance constr!ctors and static constr!ctors.
Instance "onstructors
'n Instance constructor is called whenever an instance of a class is created. hese constructors
are used to initiali2e data members of the class. (or automatic initiali2ation the "alculator class
can be rewritten by using a constructor. (or e!ample, consider the following code$
using System;
names.ace #alc
{
class #alculator
{
static int number1+ number!+ total;
::#onstructors (ave t(e same name as t(e class
#alculator()
{
number1 = 10;
number! = !0;
*
.ublic void Add3umber()
{
total = number1 " number!;
*
.ublic void @is.lay3umber()
{
#onsole$%rite&ine('7(e 7otal is ) {0*'+ total);
*
.ublic static void Main(string[] args)
{
#alculator c1 = ne/ #alculator();
c1$Add3umber();
c1$@is.lay3umber();
*
*
*
In the preceding code notice that there is no return type specified to the "alculator() constructor.
his is because constructors do not return values. he variable number; is assigned with value
;E and numberD is assigned with value DE when the constructor is invo*ed by the "ommon
4anguage Guntime ("4G).
If there are no constructors defined for a class, the compiler creates a default constructor. In such
a case, the instantiation of an object of this class invo*es the default constructor.
,tatic "onstructors
,tatic constructors are used to initiali2e the static variables of a class. hese variables are
created using the static *eyword and they store values that can be shared by all the instances of
a class. hese constructors have an implicit private access. he constructors will be invo*ed only
once during the e!ecution of a program.
he following e!ample illustrates the implementation of a static constructor$
.ublic class class1
{
static int number1;
int number!;
static class1()
{
number1 = 10; ::FP$ Since number1 is a static variable in
class1
number! = 9; ::5rror$ number! is a non0static variable in
class1
*
*
+ote$
In act!al practice, constr!ctors are !sed to initiali<e data &e&bers and not for any inp!t or o!tp!t
operations.
+ote$
He can ha%e &ore than one constr!ctor in a class. Chapter A disc!sses this topic in detail.
Constructors (ith "ara!eters
Objects can be initiali2ed using the default constructor with values hard-coded in the program.
0ut there might be a re/uirement where the variables need to be initiali2ed with user supplied
values. o tac*le this problem, a constructor can be modified to accept the user supplied values
at the runtime..
he following code illustrates the use of parameters in constructors$
using System;
names.ace #alc
{
class #alculator
{
static int number1+ number!+ total;
::#onstructors defined /it( ! integer .arameters num1 and num!
#alculator(int num1+ int num!)
{
number1 = num1;
number! = num!;
*
.ublic void Add3umber()
{
total = number1 " number!;
*
.ublic void @is.lay3umber()
{
#onsole$%rite&ine('7(e 7otal is ) {0*'+ total);
*
.ublic static void Main(string[] args)
{
int var1+ var!;
#onsole$%rite&ine('5nter Value 1)');
var1 = #onvert$7o8nt9!(#onsole$,ead&ine());
#onsole$%rite&ine('5nter Value !)');
var! = #onvert$7o8nt9!(#onsole$,ead&ine());
#alculator c1 = ne/ #alculator(var1+ var!);
c1$Add3umber();
c1$@is.lay3umber();
#onsole$,ead&ine();
*
*

*
In the preceding code, the initiali2ation values are passed to the member variables at the time of
creating the object after accepting values from the user. herefore, the following statement$
#alculator c1 = ne/ #alculator(var1+ var!);
invo*es the constructor function and passes the initiali2ation values supplied by the user at
runtime, to the variables num; and numD, respectively.
+ote$
In the preceding e1a&ple, if yo! try to e1ec!te the state&ent,
#alculator c1 = ne/ #alculator();
it wo!ld generate an error #8o o%erload for &ethod Calc!lator ta,es 5;6 arg!&ents'.
Implementing &estructors
' destructor has the same name as its class but is prefi!ed with a c, which is the symbol of tilde.
&estructors cannot be inherited or overloaded. he following code modifies the declaration of the
"alculator class by using a destructor$
using System;
names.ace #alc
{
class #alculator
{
static int number1+ number!+ total;

#alculator():: #onstructor
{
number1 = !0;
number! = 90;
total = 0;
#onsole$%rite&ine('#onstructor 8nvo2ed');
*
S#alculator() ::@estructor
{
#onsole$%rite&ine('@estructor 8nvo2ed');
*
.ublic void Add3umber()
{
total = number1 " number!;
*
.ublic void @is.lay3umber()
{
#onsole$%rite&ine('7(e 7otal is ) {0*'+ total);
*
.ublic static void Main(string[] args)
{

#alculator c1 = ne/ #alculator();
c1$Add3umber();
c1$@is.lay3umber();

*
*

*
In the preceding code, the .+% (ramewor* automatically runs the destructor to destroy objects
in the memory and displays the message 6&estructor Invo*ed8.
+ote$
2o see the inp!t of the preceding progra&, press CtrlC"?.
%ven when you do not call the destructor, garbage collector releases the memory.
Earbage Collection
Karbage Collection is a process that automatically frees the memory of objects that are no more
in use. he decision to invo*e the destructor is made by a special program of "# *nown as the
garbage collector. :owever, an object loses scope at the end of the Bain() method, the destructor
is not necessarily invo*ed. herefore in "#, you cannot determine when the destructor is called.
5arbage collector also identifies the objects that are no more referenced in the program and
releases the memory allocated to them.
In "#, you cannot destroy an object e!plicitly in code. In fact, it has the feature of garbage
collection, which destroys the objects for the programmers. he process of garbage collection
happens automatically. It ensures that$
Objects get destroyed- It does not specify when the object shall be destroyed
Only unused objects are destroyed- 'n object is never destroyed if it holds the
reference of another object.
"# provides special methods that are used to release the instance of a class from memory,
(inali2e() and &ispose().
he (inali2e() destructor is a special method that is called from the class to which it belongs or
from the derived classes. he (inali2e() destructor is called after the last reference to an object is
released from the memory. he .+% (ramewor* automatically runs the (inali2e() destructor to
destroy objects in the memory. :owever, it is important to remember that the (inali2e() destructor
may not e!ecute immediately when an object loses scope. his is because "ommon 4anguage
Guntime ("4G) call the (inali2e() destructor using a system called reference-tracing garbage
collections. In the reference-tracing garbage collection, the "4G periodically chec*s for objects
that are not used by the application. 3hen such an object is found, the (inali2e() destructor is
called automatically and garbage collector of the "4G releases the object from the memory.
he &ispose() method is called to release a resource, such as database connection, as soon as
the object using such a resource us no longer in use. Hnli*e the (inali2e() destructor, the
&ispose() method is not called automatically and you must e!plicitly call it from a client
application when an object is no longer needed. he I&isposable interface contains he &ispose()
method. herefore, to call the &ispose() method, the class must implement the I&isposable
interface.
+ote$
.n interface defines properties, &ethods, and e%ents. Interface will be disc!ssed in detail in
chapter B.
Identifying the 4ife "ycle of an Object
he following code shows the life cycle of an object of the est"alculator class$
using System;
::life cycle of an obDect
names.ace FbDects
{
class 7est#alculator
{
7est#alculator()
{
#onsole$%rite&ine('#onstructor 8nvo2ed');
*
S7est#alculator()
{
#onsole$%rite&ine('@estructor 8nvo2ed');
*
.ublic static void Main(string[] args)
{
#onsole$%rite&ine('Main() 1egins');
7est#alculator calc1 = ne/ 7est#alculator();
{
#onsole$%rite&ine('8nner 1loc2 1egins');
7est#alculator calc! = ne/ 7est#alculator();
#onsole$%rite&ine('8nner 1loc2 5nds');
*
#onsole$%rite&ine('Main() 5nds');
*
*

*
he e!plantion of the output is as follows$
he calc; object has function scope. herefore, its constructor is e!ecuted after the
e!ecution of the Bain() begins
he calcD object has bloc* scope. herefore, its constructor is e!ecuted after the
e!ecution of the Inner 0loc* begins
he destructor of all objects is invo*ed when garbage collector is invo*ed.
Just a 'inute
Consider the following code snippet:
class Number
{
static myNumber;
public void NumDisplay()
{
...
}
static void Main(string[] args)
{
Number n1 ne! Number();
n1.NumDisplay();
"onsole.#ead$ine();
}
}
2he 8!&ber class has only one, static &e&ber %ariable called &yn!&ber. Hhich constr!ctor
wo!ld yo! !se to initliali<e &yn!&berI
Answer:
Static Constr!ctor
"ractice .uestions
;. 3hich of the following statement is true about garbage collection1
a. In garbage collection the objects are not destroyed
b. In garbage collection the objects are destroyed every time.
c. In garbage collection only unreferenced objects are destroyed
D. ' destructor has the same name as its class but is prefi!ed with MMMMMM
?. MMMMMMM process identifies the unused objects and releases them in "#
@. "onsider the following code and identify which line will generate an error on compilation
using System;
::life cycle of an obDect
names.ace FbDects
{
class @ra/
{
.ublic void S(a.e()
{
#onsole$%rite&ine('in s(a.e met(od');
*
.ublic @ra/() ::line 1
{
#onsole$%rite&ine('t(is is a constructor');
*
.ublic static void Main(string[] args)
{
@ra/ obD = ne/ @ra/(); ::line !tt
obD$@ra/(); ::line 9
obD$S(a.e(); ::line E
*
*


*
"onsider the preceding and answer the following /uestion. which line in the code will
generate an error on compilation
a) 4ine ;
b) 4ine D
c) 4ine ?
d) 4ine @
A. he I&isposable interface contains the MMMMMM method
)u!!ary
In this chapter, you learned that
"onstructors are member functions of a class and are invo*ed when an instance of the
class to which they belong is created
' constructor has the same name as its class
' destructor is invo*ed when any instance of a class ceases to e!ist.
' destructor has the same name as its class, but it is prefi!ed with a c (tilde)
"onstructors are special methods that are used to release the instance of a class from
memory
5arbage collection is a process that automatically frees the memory of objects that is no
more in use
he (inali2e() destructor is called after the last reference to an object is released from the
memory
he &ispose() method is called to release a resource, such as a database connection,
when the object using such a resource is no longer in use.
%!ercises
%!ercise ;
Predict the output of the following program
using System;
names.ace SCuareL3umber
{
class #alculateSCuare
{
int number;
.ublic void SCuare(int number)
{
#onsole$%rite&ine(number);
number >= number;
#onsole$%rite&ine(number);
*
#alculateSCuare()
{
number = 10;
SCuare(numbe r);
*
.ublic static void Main(string[] args)
{
#alculateSCuare cal = ne/ #alculateSCuare();
#onsole$,ead&ine();
*
*


*
%!ercise D
Predict the output of the following program
using System;
names.ace #alculate3umber
{
class #alculate
{
static int number1;
.ublic void @is.lay(int number)
{
#onsole$%rite&ine(number);
*
#alculate()
{
number1"";
@is.lay(number1);
*
static #alculate()
{
number1 = 10;
number1"";
*
.ublic static void Main(string[] args)
{
#alculate cal1 = ne/ #alculate();
#alculate cal! = ne/ #alculate();
#onsole$,ead&ine();
*
*


*
"hapter >
Polymorphism
Polymorphism is the ability that helps in e!ecuting different operations in response to the same
message. In OOP, you can implement polymorphism by creating more than one function within a
class that have the same name. the difference in functions lie in the number and the types of
parameters passed to each function.
his chapter introduces the concept of polymorphism. It e!plains how to implement function
overloading and operator overloading.
Objectives
In this chapter, you will learn to$
&escribe polymorphism
Implemetn function overloading
Implement operator overloading
Introducing Polymorphism
he term polymorphism was derived from the 5ree* words -poly. and -morphos., which mean
-many. and -forms., respectively. In OOP, polymorphism is often e!pressed by the phrase 6one
interface, multiple functions8. his e!pression means that polymorphism allows one interface to
be used for multiple functions. )ou can apply polymorphism for reducing the comple!ity wihtin the
functions of a class of your program.
Polymorphism can either be static or dynamic. In static polymorphism the response to a function
is decided at compile time. In dynamic polymorphism the response to the function is decided at
run time.
,tatic polymorphism
,tatic polymorphism refers to an entity, which e!ists in various forms simultaneaously. he
concept of static polymorphism is analogous to the role of a woman who can be a wife, a mother,
a daughter, a sister, and an e!ecutive at the same time.
he mechanism of lin*ing a function with an object during compile time is called early binding. It
is also *nown as static binding.
"# uses D approaches to implement static polymorphism. hese are$
(unction Overloading
Operator Overloading
(unction Overloading
his approach allows using the same name for D or more functions. %ach redefinition of a
function must use different types of parameters, se/uence of parameters, or a number of
parameters. he type, se/uence, or a number of parameters for a function is called the f!nciotn
signat!re. 3hen you have multiple functions with the same name, the compiler identifies the
function based on the parameters to the function.
"onsider an e!ample, to understand the benefit of function overloading where you need a
function that convers distance in *ilometers to miles, and *ilometers can either be an integer or a
float. One approach can be to have D functions of different names, as shown in the following
code$
int #onvert8nteger(int 2m);
int #onvert-loat(int 2m);
'nother approach can be using function overloading. )ou can have D functions with the same
name but with different parameters, as shown in the following code$
int #onvert(int 2m);
float #onvert(float 2m);
Operator Overloading

his approach allows user-defined types such as structures and classes, to use overloaded
operators for easy manipulation for their objects. Operator overloading can be achieved by
defining the static member functions using the operator *eyword. (or e!ample, you can redefine
the L operator or a user-defined class :our to add the hour value of two class objects. )ou can
then add D :our objects by using the L operator.
he following code is an e!ample showing the usage of operator (L)$
=our (1;
=our (!;
=our (9;
(9 = (1 " (!;
yna!ic "oly!orphis!
In dynamic polymorphism the decision about function e!ecution is made at run time. &ynamic
polymorphism is more useful as compared to static polymorphism because dynamic
polymorphism gives much more fle!ibility for manipulating objects.
he mechanism of lin*ing a function with an object at run time is called dynamic or late binding.
&ynamic binding supports virtual functions.
"# uses D approaches to implement dynamic polymorphism. hese are$
Abstract classes- 're the special type of base classes that consist of abstract class
members. 'll the class members that are derived directly from abstract classes must
implement all the abstract functions and properties.
1irtual Functions- 're the functions that do not really e!ists, however, appear to be
present in some parts of the program.
+ote$
.bstract classes and %irt!al f!nctions will be ta!ght in detail in chapter B.
#!ple!enting Function Overloading
(unction overloading is the most common way of implementing polymorphism. )ou can
implement function overloading by defining D or more functions in a class sharing the same
name. :owever, each definition of a function must differ in its function signature$
he following code is an e!ample of function overloading$
using System;
names.ace #alculateMaJ
{
class #alculateMaJ
{
.ublic int MaJ(int number1+ int number!)
{
if (number1 T number!)
{
return number1;
*
else
{
return number!;
*
*
.ublic float MaJ(float number1+ float number!)
{
if (number1 T number!)
{
return number1;
*
else
{
return number!;
*
*
*
class MaJ#alc
{
static void Main(string[] args)
{
#alculateMaJ calc = ne/ #alculateMaJ();
#onsole$%rite&ine('{0*'+ calc$MaJ(4$E-+O$G-));
::1ot( function calls differ
#onsole$%rite&ine('{0*'+ calc$MaJ(1N+1!));
::only in t(eir .arameters
#onsole$,ead&ine();
return 0;
*
*


*
In the preceding e!ample, the function Ba!() displays the ma!imum of D numbers, number; and
numberD. the function Ba!() is overloaded by passing the integer and float values into it.
(untion ,ignature
&uring a funciton call, a "# compiler needs to resolve the name of the function. he signature of
a function is defined by$
he number of parameters. "onsider the following e!ample$
void Add3umber(int);
void Add3umber(int+ float);
In the preceding code, there are two functions because the number of parameters is
different.
he data types of parameters. "onsider the following e!ample$
void @is.lay(int);
void @is.lay(c(ar);
In the preceding code, the two functions are difference because the data types of their
parameters are different.
he se/uence of parameters. "onsider the following e!ample$
void @is.lay(int+ c(ar);
void @is.lay(c(ar+ int);
In the preceding code, the two functions are difference because their parameters are
specified in different order.
+ote$
2he ret!rn type is 8O2 a part of a f!nction6s signat!re. 2herefore, the following two declarations
cannot occ!r in the sa&e class:
%oid display34N
char display34N
In addition to function overloading, you can also overload constructor.
"onstructor Overloading
"onstructors can also be parameteri2ed, and therefore, they can be overloaded. Overloaded
constructors are commonly used in "# to provide fle!ibility while creating an object.
he following is an e!ample of overloading constructors$
using System;
names.ace #alculate
{
class #alculate3umber
{
.rivate int number1+ number!+ total;
::default constructor
.ublic #alculate3umber()
{
number1 = number! = total = 0;
*
.ublic #alculate3umber(int num1+ int num!)::7/o argument
constructor
{
number1 = num1;
number! = num!;
total = 0;
*
.ublic void Add3umber()
{
total = number1 " number!;
*
.ublic void @is.lay3umber()
{
#onsole$%rite&ine('7(e sum of t/o numbers is {0*'+ total);
*
*
class #al3um
{
static void Main(string[] args)
{
::@efault constructor invo2ed
#alculate3umber cal1 = ne/ #alculate3umber();
::.arametric constructor
#alculate3umber cal! = ne/ #alculate3umber(E+ 9);
cal1$Add3umber(); ::add() invo2ed to calculate t(e sum of
members
cal1$@is.lay3umber();
cal!$Add3umber();::add() invo2ed to calculate t(e sum of
members
cal!$@is.lay3umber();
return 0;
*
*
*
Activity - isplaying ays using Function Overloading
"roble! )tate!ent
ime has to develop an application for primary school. he application should accept the month
entered by the student and display the total number of days of that month.
,olution
o develop the re/uired application, ime needs to perform the following tas*s$
;. "reate a console based application
D. 0uild and e!ecution an application.
as* ;$ "reating a "onsole-0ased 'pplication
/* ,elect )tart All "rogra!s Microsoft 1isual )tudio 0445 Microsoft 1isual
)tudio 0445* he )tart "age C Microsoft 1isual )tudio window will be displayed
0* ,elect File 2e( "roject* he 2e( "roject dialog bo! will be displayed
6* ,elect the project type as 1isual C$ from the "roject types pane and Console
Application from the Te!plates pane.
7* ype the name of the new project as "ri!ary)chool in the 2a!e te!t bo!.
5* ,pecify the location where the new project is to be created as c-Dchapter8DActivity/ in
the ,ocation combo bo!.
3* "lic* the O' button.
8* Open the )olution Explorer window and right-clic* the "rogra!*cs file.
9* ,elect the Rena!e option and type the new name as ayCount*cs
>* &ouble-clic* the ayCount*cs file in the solution explorer window. he code view of
the ayCount*cs file is displayed
/4* Geplace the e!isting code with the following code$
using System;
names.ace 6rimarySc(ool
{
class @ay#ount
{
int Mont(;
int Uear;
int @ays;
.ublic @ay#ount() ::constructor to initialiKe mont( and year to
0
{
Mont( = 0;
Uear = 0;
*
:: ,eturns 1 if year is a lea. year+ else returns 0
.ublic 1oolean &ea.Uear()
{
if (Uear R E == 0)
return true;
else
return false;
*
::Sets t(e mont( and year
.ublic void set@ate(int mont(1+ int year1)
{
Uear = year1;
Mont( = mont(1;
*
::Sets t(e mont(+ overloaded function
.ublic void set@ate(int mont(1)
{
Mont( = mont(1;
Uear = !00G;
*
::,eturns t(e name of t(e mont(
.ublic string mont(3ame()
{
s/itc( (Mont()
{
case 1) return 'Manuary';
case !) return '-ebruary';
case 9) return 'Marc(';
case E) return 'A.ril';
case 4) return 'May';
case G) return 'Mune';
case H) return 'Muly';
case O) return 'August';
case N) return 'Se.tember';
case 10) return 'Fctober';
case 11) return '3ovember';
case 1!) return '@ecember';
default) return '8nvalid Mont( S.ecified?';
*
*
::Sets t(e number of days in a mont(
.ublic void set@ays()
{
s/itc((Mont()
{
case 1)
case 9)
case 4)
case H)
case O)
case 10)
case 1!)
{
@ays = 91;
brea2;
*
case !)
{
@ays =!O;
if (&ea.Uear())
{
@ays = !N ::Assign !N days if lea. year
brea2;
*
*
case E)
case G)
case N)
case 11)
{
@ays = 90;
brea2;
*
*
*
.ublic void dis.lay()
{
string[] name = ne/ string[!4];
set@ays();
#onsole$%rite('7(e number of days in t(e mont( of' "
mont(3ame());
#onsole$%rite('is' " @ays);
*
static void Main(string[] args)
{
@ay#ount day#ount = ne/ @ay#ount();
int mont(+ year;
#onsole$%rite&ine('5nter t(e mont( in number)');
mont( = #onvert$7o8nt9!(#onsole$,ead&ine());
#onsole$%rite&ine('5nter t(e year)');
year = #onvert$7o8nt9!(#onsole$,ead&ine());
day#ount$set@ate(mont(+year);
day#ount$dis.lay();
#onsole$,ead&ine();
*
*
*
as* D$ 0uilding and %!ecuting an 'pplication
o build and e!ecute the application perform the following steps$
;. ,elect Auild Auild )olution or press F3 to build the solution
D. ,elect ebug )tart ebugging or press F5 to e!ecute the application
?. Cerify the output of the application
Implementing Operator Overloading
he concept of overloading a function can also be applied to operators. Operator overloading
provides additional capabilities to "# operators when they are applied to user-defined data types.
Only the predefined set of "# operators can be overloaded.
+eed for Operator Overloading
Bost built-in data types have predefined operators associated with them. (or e!ample, the "#
data types int with the operators L,-,X, and Y provides support for mathematical operations. ' class
is an e!ample of a user-defined data types. o ma*e operations on a user-defined data type is
not as simple as the operation on a built-in data type. o use operators with use-defined data
types, they need to be overloaded according to a programmer.s re/uirement.
he following is an e!ample of the 4ength class that implements the 0ritish standard of
measuring distance$
class &engt(
{
int i-eet;
float f8nc(;
.ublic &engt((int i-t+ float f8n)
{
i-eet = i-t;
f8nc( = f8n;
*
void @is.L&en(void)
{
#onsole$%rite&ine('&engt( = {0*+ {1*'+ i-eet+ f);
*
*
o add D distances stored in D objects of the 4ength class in the preceding e!ample, you need to
invo*e a function. "onsider, you have defined a function named 'ddM&ist. he following is the
code to invo*e the function$
obDect9$AddL@ist(obDect1+ obDect!);
In this case, object; is added to objectD and the result is stored in object?.
)ou might also want to compare two distances. he following code compares two objects of the
4ength class, using the "ompare&istance()$
obDect1$#om.are@istance(FbDect!);
In the preceding code, the member function "ompare&istance() of object; is invo*ed with objectD
as a parameter. his function compares the data members of object; with those of objectD and
returns the difference between them.
Instead of using the 'ddM&ist() to add two distances, it is easier to use the following statement$
obDect9 = obDect1 " obDect!;
In the preceding code, object;, objectD and object? are all objects of the 4ength class. his code
is an easier way of e!pressing your intent as opposed to a lengthy function call.
he objects of the 4ength class can be compared as shown in the following code$
obDect1 T obDect!;
or
obDect1 obDect!;
or

obDect1 == obDect!;
Hsers can understand the operator notation more easily than a function call because it is closer to
real life implementation. herefore, by associating a set of meaningful operators a user-defined
data type can be manipulated in a conventional and simple form. 'ssociating operators with user-
defined data types involves overloading them.
he following table describes the overload ability to the operators in "#.
)peratrs *escriptins
C, 9, O, P, CC, 99 2hese !nary operators ta,e one operand and can be
o%erloaded
C, 9, Q, R, S 2hese binary operators ta,e two operands and can be
o%erloaded
TT, OT, U, V, UT, VT 2he co&parison operators can be o%erloaded
WW, XX 2he conditional logical operators cannot be o%erloaded directly,
b!t they are e%al!ated !sing W and : which can be o%erloaded
CT, 9T, QT, RT, ST 2he assign&ent operators cannot be o%erloo,ed
T, ., I:, new , is, si<eof, typeof 2hese operators cannot be o%erloo,ed
O%erload .bility of Operators
8ote:
2he co&parison operators, if o%erloaded, &!st be o%erloaded in pairs: that is, if TT is o%erloaded,
O &!st also be o%erloaded. 2he re%erse is also tr!e. Si&ilarly, it is tr!e for U and V, and for UT and
VT.
'n operator can be overloaded by defining a function to it. he function for the operator is
declared by using the operator *eyword.
Operators may be considered as functions internal to the compiler. (or e!ample, the e!pression
aLb may be ta*en as L(a,b). ' programmer may also overload these functions by writing the
appropriate functions with similar signatures. (unctions that specify the additional tas* for the
operators are called operator functions. he *eyword operator along with the operator to be
overloaded is used as the function name.
(or e!ample, to overload the L operator, the following synta! is used to define the operator
function$
,uch a definition ma*es use of operators, realistic and easy to understand. (or e!ample, if the -L.
operator is overloaded for the class 4ength, then the process of adding two distance objects will
be simple statement, which is object;L objectD for the user. he compiler interprets the preceding
statement as operator L (object;, objectD), where the operator function of the first operand of the
operator.
0oth unary and binary operators can be overloaded
Overloading Hnary Operators
Hnary operators act on a single operand. ,ome e!amples of unary operators are the increment
(LL) and decrement (--) operators.
Hnary operators can be classified as$
,imple prefi! unary operators, for e!ample the 9 (minus) operator
Pre and post increment and decrement operators, for e!ample the LL() prefi! increment
operator
,imple Prefi! Hnary Operators
' simple prefi! operator may be defined by function that ta*es one parameter. (or e!ample, in the
following code the compiler resolves -object;. as$
o.erator 0 (obDect1)
he o.erator 0 () function can be associated with the class by ma*ing it a member function.
he o.erator 0 () function can be provided an object of the class as its parameter. his
effectively associates the class with the function.
he following code is an e!ample of the overlaoding 9 operator$
using System;
names.ace #alculator
{
class #alculator
{
.ublic int number1+ number!;
.ublic #alculator(int num1+ int num!)
{
number1 = num1;
number! = num!;
*
.ublic static #alculator o.erator 0(#alculator c1)
{
c1$number1 = 0c1$number1;
c1$number! = 0c1$number!;
return c1;
*
.ublic void 6rint()
{
#onsole$%rite&ine('number1 = ' " number1);
#onsole$%rite&ine('number! = ' " number!);
#onsole$,ead&ine();
*
*
class 5ntry6oint
{
static void Main(string[] args)
{
#alculator calc = ne/ #alculator(14+ 0!4);
::Vsing t(e overloaded 0 o.erator /it( t(e class obDect
calc = 0calc;
calc$6rint();
*
*
*
In the preceding code, - operator is overloaded to ma*e the variables of class "alculator
negative. In the statement calc ^ -calc, the operator is used with the object of the class "alculator,
which calls the operator overload and ma*es the variables negative.
Pre and Post Increment and &ecrement Operators
he increment operator increments the current value of an operand by ; and returns the result.
he decrement operator decrements the current value of an operand by ; ad returns the result.
3hen the increment and decrement operators are used, the value of the variable is the same
after the operation is completed. he difference in the value of the variable between the prefi!
and postfi! notation is the order in which they are applied.
here are certain rules, which are applied when declaring the prefi! and postfi! notationsR the
notations must be public, static and unary. he following is an e!ample of the increment operator
for the 3atch struct$
struct %atc(
{
.rivate int val;
$$$$$$
.ublic static %atc( o.erator"" (%atc( .arameter))
{
.arameter$val"";
return .arameter;
*
$$$$$
*
In "#, the single operator is used for both the prefi! and postfi! operators. he result of a postfi!
notation is the value of the operand before it ta*es place. he following e!ample statements give
the usage of postfi! notation$
%atc( / = ne/ %atc((G);
%atc( .ost-iJ = /"";
he preceding statements will result in assigning the value of variable w to variable post(i! and
then incrementing the value of variable w.
he result of a prefi! e!pression is the return value of the operator. he following e!ample
statements give the usage of prefi! notation$
%atc( / = ne/ %atc((G);
%atc( .re-iJ = ""/;
he preceding statements will result in incrementing the value of variable w and then assigning
the value of variable w to object pre(i!.
he following is an e!ample of overloading the pre increment and post increment operator, using
structures$
using System;
using System$#ollections$Ieneric;
using System$7eJt;
names.ace F.eratorFverload
{
struct 3umber#ount
{
.ublic int i;
.ublic 3umber#ount(int initval)
{
t(is$i = initval;
*
.ublic static 3umber#ount o.erator ""(3umber#ount arg)
{
arg$i"";
return arg;
*
*
class 7est#lass
{
static void Main(string[] args)
{
3umber#ount count1 = ne/ 3umber#ount(1);
3umber#ount count! = count1"";
#onsole$%rite&ine(count1$i);
#onsole$%rite&ine(count!$i);
count! = ""count1;
#onsole$%rite&ine(count1$i);
#onsole$%rite&ine(count!$i);
#onsole$,ead&ine();
*
*
*
)ou can also overload the prefi! and postfi! notations in classes.
+ote$
2he i&ple&entation of incre&ent and decre&ent operator o%erlaoding is different in classes as
co&pared to str!cts.
Operators in "lasses
he implementation of the increment operator used with structs cannot be implemented with
classes. If 3atch is a class, assigning of variable w to post(i! ma*es the varaible post(i! refer to
the same object as w. updating w will automatically update post(i!.
(or e!ample$
Operator L (a,b)R
he following code is an e!ample of using simple binary operators$
using System;
using System$#ollections$Ieneric;
using System$7eJt;
names.ace 1inaryFverload
{
class #alculator
{
.ublic int number;
.ublic #alculator()
{
number = 0;
*
.ublic #alculator(int n)
{
number = n;
*
.ublic static #alculator o.erator "(#alculator calc1+ #alculator
calc!)
{
#alculator calc9 = ne/ #alculator();
calc9$number = calc!$number " calc1$number;
return calc9;
*
.ublic void dis.lay()
{
#onsole$%rite&ine('{0*'+ number);
*
*
class #al3um
{
static void Main(string[] args)
{
#alculator num1 = ne/ #alculator(100);
#alculator num! = ne/ #alculator(40);
#alculator num9 = ne/ #alculator();
num9 = num1 " num!;
num1$dis.lay(); ::dis.lays 100
num!$dis.lay(); ::dis.lays 40
num9$dis.lay(); ::dis.lays 140
#onsole$,ead&ine();
*
*
*
In the preceding code, the L operator is overloaded to add two objects of the "alculator class.
he operator function recieves one object as a parameter. In the preceding code, num; is an
object of a class, of which the operator is a member function. Object numD is passed as a
parameter to the operator. 3hen an overloaded operator is invo*ed, the object on the left of the
parameter is a member and the object on the right of the operator is the parameter.
'ctivity$ Overloading an Operator
Problem ,tatement
(uncity 4and is a newly established amusement par* located in 3est Cirginia. 0rad is a chief
technical officer of (uncity 4adnd. :e is currently wor*ing on a project related with calculating
distances. his project will calculate the distance to reach (uncity 4and from various locations
because many visitors do not *now the e!act location of the par*.
0rad needs to develop a program, which would enter a visitor.s location and the distance traveled
by the visitor. 'fter analy2ing the location and the distance travelled by the visitor, the program
should display the remaining distance and the total distance traveled
:elp 0rad to develop an application by overloading by binary operator(L).
,olution
o develop the re/uired application, ime needs to perform the following tas*s$
?. "reate a console based application
@. 0uild and e!ecution an application.
as* ;$ "reating a "onsole-0ased 'pplication
//* ,elect )tart All "rogra!s Microsoft 1isual )tudio 0445 Microsoft 1isual
)tudio 0445* he )tart "age C Microsoft 1isual )tudio window will be displayed
/0* ,elect File 2e( "roject* he 2e( "roject dialog bo! will be displayed
/6* ,elect the project type as 1isual C$ from the "roject types pane and Console
Application from the Te!plates pane.
/7* ype the name of the new project as FunCity,and in the 2a!e te!t bo!.
/5* ,pecify the location where the new project is to be created as c-Dchapter8DActivity0 in
the ,ocation combo bo!.
/3* "lic* the O' button.
/8* Open the )olution Explorer window and right-clic* the "rogra!*cs file.
/9* ,elect the Rena!e option and type the new name as istance*cs
/>* &ouble-clic* the istance*cs file in the solution explorer window. he code view of the
istance*cs file is displayed
04* Geplace the e!isting code with the following code$
using System;
using System$#ollections$Ieneric;
using System$7eJt;
names.ace -un#ity&and
{
class @istance
{
int &engt(;
.ublic @istance()
{
&engt( =0;
*
.ublic static @istance o.erator "(@istance @istance1+ int Value)
{
@istance1$&engt( "= Value;
return @istance1;
*
.ublic void @is.lay@istance(int &engt(+ int @istance!)
{
int ,esult;
#onsole$%rite&ine('7(e distance travelled is {0*'+ &engt();
#onsole$%rite&ine('7(e remaining distance to reac( t(e
destination is {0*'+ @istance!);
,esult = @istance! " &engt(;
#onsole$%rite&ine('7(e total distance you (ave to travel is
{0*'+ ,esult);
*
*
class 5ntry6oint
{
.ublic static void Main(string[] args)
{
@istance @istance1 = ne/ @istance();
string &ocation;
int 7ravelled@istance;
#onsole$%rite&ine('5nter t(e location you (ave reac(ed) A+
1+ #');
&ocation = #onsole$,ead&ine()$7oV..er();
if (&ocation == 'A' WW &ocation == '1' WW &ocation == '#')
{
#onsole$%rite&ine('5nter t(e distance you (ave
covered)');
7ravelled@istance = #onvert$7o8nt9!(#onsole$,ead&ine());
s/itc((&ocation)
{
case 'A')
@istance1$@is.lay@istance(7ravelled@istance+
14);
brea2;
case '1')
@istance1$@is.lay@istance(7ravelled@istance+
!0);
brea2;
case '#')
@istance1$@is.lay@istance(7ravelled@istance+!4);
brea2;
*
*
else
#onsole$%rite&ine('8ncorrect Value');
#onsole$,ead&ine();
*

*
as* D$ 0uilding and %!ecuting an 'pplication
o build and e!ecute the application perform the following steps$
/* ,elect Auild Auild )olution or press F3 to build the solution
0* ,elect ebug )tart ebugging or press F5 to e!ecute the application
6* Cerify the output of the application
Practice `uestions
;. 3hich of the following options about implementing polymorphism is not true1
a$ )ou can implement polymorphism by implementing an interface
b$ )ou can also achieve polymorphism by inheritance
c$ )ou can implement polymorphism by encapsulation
d$ )ou can implement polymorphism by using abstract classes
D. "onsider the following statements$
,tatement '$ In dynamic polymorphism, appropriate methods of a program can be
invo*ed, depending in the conte!t.
,tatement 0$ In early binding, function calls are bound at run time.
3hich of the following options is true about these statements
a$ ,tatement ' is true and ,tatement 0 is false.
b$ ,tatement ' is false and ,tatement 0 is true
c$ 0oth statements are true
d$ 0oth statements are false
?. 3hich of the following is an e!ample of function overloading1
a$ Void eJam.le(); c(ar eJma.le();
b$ void eJma.le1();void eJma.le!();
c$ void eJma.le1(int+ int);void eJma.le!(float+ float);
d$ void eJma.le1(int+ int);void eJma.le1(float+ float);
e$
@. "onsider the following statements
,tatement '$ Overloading a binary operator is similar to overloading a unary operator
e!cept that a binary operator re/uires an additional parameter
,tatement 0$ 0inary operators include arithmetic assignment operators.
.
3hich of the following option is true about these statements1
a$ ,tatement ' is true and ,tatement 0 is false.
b$ ,tatement ' is false and ,tatement 0 is true
c$ 0oth statements are true
d$ 0oth statements are false
A. 3hich of the following statements is true about operator overloading
a$ he L operator cannot be overloaded
b$ 0inary operators are operators that wor* with two operands.
,ummary
In this chapter, you learned that$
he term polymorphism has been derived from 5ree* words -poly. and -morphos., which
means -many. and -forms., respectively.
Polymorphism allows one interface to be used for multiple functions.
,tatic polymorphism refers to an entity, which e!ists in different forms simultaneously
In dynamic polymorphism the decision about function e!ecution is made when code is
e!ecuted
(unction overloading is the process of using the same name for two or more functions in
a class.
he number, type, or se/uence of parameters of a function is called its function signature
Overloaded constructors are commonly used in "# to provide fle!ibility while creating an
object
Operator overloading provides additional capabilities to "# operators when they are
applied to user-defined data types.
he predefined "# operators can be overloaded by using the operator *eyword.
Operators may be considered as functions internal to the compiler.
Operators may be classified as unary and binary operators.
Hnary operators wor* with one operand and are classified as$
' prefi! unary operator may be defined by a member function that ta*es no parameters
or by a nonmember function that ta*es one parameter
0inary operators wor* with two operands
Overloading a binary operator is similar to overloading a unary operator, e!cept that a
binary operator re/uires an additional parameter.
%!ercises
%!ercise ;
3rite a program, which increments the number of pages of a boo* by the number of pages
entered by the user.
Chapter 9
#nheritance
%ntities do not e!ist in isolation. hey have some type of relationship with each other. ,imilarly, in
"#, the classes in a program can be related to each other. Identifying and establishing
relationships between classes is a critical aspect of OOP.
his chapter identifies the relationship between classes. It discusses the use of classes and
inheritance. In addition, this chapter discusses the use of abstract classes, sealed classes and
interfaces.
Objectives
In this chapter, you will learn to$
Identify relationships between classes
Hse classes and inheritance
Hse abstract classes
Hse sealed classes
Hse interfaces
Identifying Gelationships between "lasses
In software application classes and objects are related to each other. hey act and react with
other classes and objects. &epicting their dynamism in an application ma*es the application as
close as possible to the real world.
In the object oriented approach, objects perform actions in response to messages from other
objects defining the receiving object.s behavior. his approach specifies the relationships among
classes based on the behavior of individual class.
"onsider the similarities and differences among the objects or classes, including an automobile, a
car, a driver, and an engine. )ou can ma*e the following observations$
' truc* is a *ind of an automobile
' car is another *ind of an automobile.
'n engine is part of an automobile
' driver drives a car
0ased on the preceding observations, you can identify the relationships among the objects and
classes.
Jinds of Gelationships
here are various relationships between objects of different classes in an object-oriented
environment$
Inheritance relationship
"omposition relationship
Htili2ation relationship
Instantiation relationship
Inheritance Gelationship
OOP enables classes to inherit commonly used state and behavior from other classes. "onsider
the following e!ample$
'utomobile is the superclass of a car and a bus. "ar and bus inherits attributes and behavior
from the automobile. he car, bus, and automobile have a relationship where one object is a type
of another object. his means that every car is an automobile, but every automobile is not a car.
his type of relationship is *nown as inheritance. In "# programming, each class is allowed to
inherit from one class and each class can be inherited by unlimited number of classes.
In terms of classes, inheritance means that a class may inherit a set of attributes from another
class. he following figure is an e!ample of the hierarchy establishing the inheritance relationship
of the Bammals class.
In the preceding figure, notice there is a set of classes$ mammals, dogs, cats, humans, lions,
tigers and leopards. Bammals have the following set of characteristics$
're warm blooded
're vertebrates
:ave e!ternal ears
:ave hair on their body
he dog, cat and human classes also have similar characteristics and they have inherited these
attributes from the Bammals class.
,imilarly, you can establish the relationship between a superclass and its subclasses.
The simple hierarchy of Mammals
%ammals
.ogs /umans Cats
0eopards 1igers 0ions
,uperclass and ,ubclass
he following figure shows the hierarchy of the subclass of the superclass.
In the preceding figure, notice both the "ar and 0us classes inhertit the characteristics of an
'utomobile. he 'utomobile class is a superclass while 0us and "ar classes are its subclasses.
4et us continue considering the 'utomobile class e!ample. 'n automobile is a vehicle that has an
engine. he 'utomobile class inherits its characteristics from the vehicles class. ,ome of the
attributes of the 'utomobile class are$
:as wheels
:as an engine
:as a color
,ometime, you may not want to create an object of the 'utomobile class in your program.
Instead, you may want to use it only because you want it to act as a superclass for the "ar and
0us classes. In this case, 'utomobile is called the abstract superclass because there e!ists no
such entity as an automobile. It is simply used as a superclass from which other classes inherit
attributes. he superclass is generali2ed. 5enerali2ation means that multiple classes inherit from
the same superclass.
5enerali2ation is needed to create programs that can be customi2ed in accordance with new
re/uirements. Gecall the resilience to change is one of the features if OOP. "onsider a scenario
where you need to write a program that displays a string as an output. he simplest solution to
this problem will be to accept a string from a user and display it. :owever, there is a change in
your re/uirement and you want the output to be an integer. 3hat will you do in such a case1
)ou have a superclass data, which has a show method to display its value. )ou also have
character and float as the subclasses of data. o display an integer, you need to create a class
called integer, which is a subclass of data. 'dding a new subclass will not affect the e!isting
classes. herefore, you do not need to add a method show to each subclass because the
superclass has this method, and the subclasses will inherit the method.
Geusability is another important reason for a programmer to generali2e. 5enerali2ation is
implemented by using an abstract superclass, which is a conceptual class. 'n abstract class does
Automobile
Car Bus
Ford B%2 1o&ota %itsubishi
not e!ist in the real world but acts as a base from which other classes inherit properties.
5enerali2ation ensures that all subclasses have a consistent interface.
(or e!ample, consider the 5eometrical(igures class that has several subclasses, such as
,/uare, riangle and Polygon. he 5eometrical(igures class has attributes called
numberOf"oordinates and valueOf"oordinates. It also contains the get"oordinates and draw
functions. he get"oordinates function prompts the user to type the values of coordinates.
In case of a s/uare, the value of numberOf"oordinates is four. ' user will be prompted to enter
four coordinates. In case of a polygon, the user can enter five or more coordinates. o draw a
triangle, you will prompt the user to input three coordinates. Hsing these coordinates, the user
can call the draw function to create a triangle.
'nother way to draw geometrical figures is to allow each subclass to have its own method
get"oordinates, and then draw them by using those coordinates as parameters. hese methods
would have to be repeated in all the subclasses. he triangle class, for instance, might as* for the
) coordinate and then for the K coordinate. he s/uare class might do e!actly the opposite.
Gepeating methods can lead to confusion caused with the inconsistency in the interface. It would
be simpler to have the get"oordinates and draw methods in the superclass. hese methods will
be inherited by subclasses ensuring uniformity across all 5eometrical(igures.
3hile generali2ing, the structure and behavior that is common to different classes are combined
to form a common superclass. he superclass represents generali2ation and the subclass
represents speciali2ation, where attributes and methods from the superclass are added, modified,
or hidden.
In the object-oriented approach, the emphasis is on designing classes so that they share data
and methods. 't the same time, security has to be maintained. Hnauthori2ed classes should not
be allowed to tamper with members of other classes. %ncapsulation provides security to the data
as well as methods of a class.
here are no set rules to guide when you should generali2e and when you should not generali2e.
:owever, you should *eep some rules in mind while generali2ing. he e!istence of common
properties is one such rule. here are no set of rules defined to stop generali2ing classes.
(or e!ample, consider you are developing a payroll system, where you have the manager,
accountant and cler* classes. hese are the subclasses of a superclass, employee. 'ssemble
the common properties of these subclasses and put all these in the employee superclass. )ou do
not need to generali2e further to include a class called person because the payroll system does
not re/uire this *ind of generali2ation.
Fust a Binute
$!ild the hierarchy of the &i1er, VCR, color tele%ision, washing &achine, stereo class objects,
and generali<e where%er possible.
'nswer
2he fig!re shows the hierarchy of the class objects.
here can be need to redefine the function of the superclass. his process where the subclasses
redefine the function of the superclass is called overriding.
(or e!ample, consider the "ar and 0us subclasses of he 'utomobile superclass. he 'utomobile
class has a closeMwindow function. he implementation of this function will be different in "ar and
0us. o shut the window, you will roll it up in the case of a car, while you will slide to the
windowpane in case of a bus. In this case, the subclasses need to redefine the function.
"omposition Gelationship
OOP allows you to form an object, which includes another object as its part. his mechanism of
forming an object is called composition.
(or e!ample, a class named "ar consists of an engine. herefore, a car is composed of an
engine. his type of relationship between the car and the engine is *nown as the composition
relationship.
a*e another e!ample, consider the passenger class. %ach passenger of a train has a tic*et. he
attributes of a passenger are name, age, gender, mealMpreference, and tic*et. he tic*et class
has attributes such as trained, coach+umber, seat+umber, port+umber and fare. herefore, the
passenger class consists of the ic*et class.
Bany objects in the real world have this type of relationship. he composition relationship e!ists
when one class is made up of another class.
Fust a Binute
Identify the relationship between the following class pairs:
1. 2ele%ision 9 Spea,er
2. *a&&al 7 2iger
-. Kar&ent 7 Shirt
@. C!p 7 2ea
?. Co&p!ter 7 *icroprocessor
'nswer
2he relationships are as follows:
Electronic Items
Entertainment Items .tility Items
Color
Television
-C/ 0tereo #ixer 1ashin2
#achine
? and 1 are e1a&ples of co&position relationships
- and 2 are e1a&ples of inheritance relationships
@ does not e1hibit any relationship. 2ea is not an attrib!te of c!p.
Htili2ation Gelationship
OOP allows a class to ma*e use of another class. his *ind of relationship is called utili2ation. (or
e!ample, 0B3 is an object of the car class, and Patric* is an instance of a driver. Patric* drives a
0B3. 'nother driver, Fames, drives a bus. herefore, both the car and bus classes use the driver
class. his type of relationship between a driver and a bus or a driver and a car is *nown as the
utili2ation relationship.
a*e another e!ample$ a student writes with a pencil while a painter draws with a pencil. 0oth the
student and painter use the pencil class. he relationship between the student and the pencil, or
the painter and the pencil is the utili2ation relationship
Fust a Binute
Identify the classes and their !tili<ation relationship in the following scenario of a depart&ental
store.
2here are se%eral co!nters and each co!nter in the store is &anned by a single salesperson who
sells a specific prod!ct. . c!sto&er approaches a co!nter. (epending on the c!sto&er6s desire
to p!rchase a prod!ct, the salesperson sells the prod!ct to the c!sto&er and accepts pay&ent.
'nswer
2he !tili<ation relationships of the preceding scenario are:
1. Salespersons &an co!nters
2. 0ach co!nter deals in a specific prod!ct
-. 2he c!sto&er b!ys a prod!ct
@. 2he c!sto&er pays the salesperson.
Instantiation Gelationship
'n instantiation relationship, as the name suggests, is a relationship between a class and an
instance of that class. ,ome e!amples of instantiation relationships are$
' 0B3 is a car
' chest of drawers is a piece of furniture
-5one with the 3ind. is the title of a boo*.
)ou are a student.
:sing Classes and #nheritance
In "#, inheritance is the property by which the objects of a derived class possess copies of the
data members and the member functions of the base class. ' class that inherits or derives
attributes from another class is called the derived class. he class from which attributes are
derived is called the base class. In OOP, the base class is actually a superclass and the derived
class is a subclass.
#!ple!enting #nheritance
%ach instance of the derived class includes the attributes of the base class. herefore, the
derived class has a larger set of attributes than its base class. he derived class can, however,
modify some or all the attributes. Inheritance enables the easy maintenance of code. 'ny change
made to the base class automatically changes the behavior of its subclasses. In this class, the
subclasses automatically inherit the new behavior.
he synta! used in "# for creating derived classes is as follows$
access s.ecifierT class base classT
{
$ $ $
*
class derivedLclassT ) baseLclassT
{
$ $ $
*
eter!ining #nheritance Fierarchies
)ou can use a thumb rule to establish whether inheritance is re/uired while you are designing a
program. 'lways chec* the *ind of relationship between the derived classes and the base class.
%nsure the derived class is a *ind of the base class.

"onsider a scenario. )ou have an %mployee class and a rainee class. )ou re/uire the properties
of the %mployee class to e!ist in the rainee class. )ou can ensure the rainee class has the
properties of the %mployee class by writing code in the two ways. he following are e!amples of
code$
class 5m.loyee
{
7rainee tn;
.ublic void leave()
{
tn$#alcL&eave(); ::call a function of t(e em.loyee class
*
)
)
*
Or
class 7rainee ) 5m.loyee
{
.ublic void leave()
{
#alcL&eave(); :: -unction of t(e base class is available
*
)
)
*
,yntactically, there is nothing wrong with the preceding e!amples. :owever, one of these
e!amples is a badly designed class. 4et us use the rule of thumb. Is a trainee a *ind of an
employee1 he answer is no. 're any trainees employed1 he answer is yes. herefore, in the
preceding scenario, it ma*es more sense to use containment instead of inheritance. he inherited
classes can contain constructors and destructors. he invocation of the constructors and
destructors also follow the inheritance hierarchy.
#nvo@ing constructors
"onstructors are called in the order of base-to-derived. :owever, the e!ecution of destructors
cannot be controlled by the programmer.
he following code shows the use of constructors with inherited classes$
using System;
class 1ase
{
.ublic 1ase()
{
#onsole$%rite&ine('#onstructor of 1ase');
*
S1ase()
{
#onsole$%rite&ine('@estructor of 1ase');
*
*
class @erived ) 1ase
{
.ublic @erived()
{
#onsole$%rite&ine('#onstructor of @erived');
*
S@erived()
{
#onsole$%rite&ine('@estructor of @erived');
*
*
class 1ase@erived
{
static void Main(string[] args)
{
@erived obD = ne/ @erived();
*
*
Aase Class #nitialiBation
In inheritance, the derived class receives the base class member variables and methods. his
means that an order of inheritance must be followed during the construction of an object.
he superclass part of the object should be created before you create the subclass part, inclusive
of the member objects defined in the derived part. he instructions for superclass initiali2ation are
given in the member initiali2ation list, as shown in the following code$
class 6oint
{
.rivate int J+ y;
.ublic 6oint(int a+ int b)
{
J = a;
y = b;
*
void set<(int a)
{
J = a;
*
void setU(int b)
{
y = b;
*
int get<()
{
return J;
*
int getU()
{
return y;
*
S6oint()
{
J = y = 0;
*
*
class &ine ) 6oint
{
::Member 8nitialiKation
.ublic &ine(int J1+ int y1+ int J!+ int y!) ) base(10+ !0) { *
*
:sing Abstract Classes
"# enables you to create abstract classes that are used to provide partial class implementation of
an interface. )ou can complete implementation by using the derived classes. 'bstract classes
contain abstract methods, which can be implemented by the derived class. Polymorphism can be
implemented by using abstract classes and virtual functions. 3hen you create derived classes,
you provide more speciali2ed functionalityR polymorphism enables you to treat the new objects as
general objects$
he following code is an e!ample of the declaration of an abstract class$
abstract class 5Jam.leAbsract ::t(is is an abstract class
{
$$$$$
*
class 7estAbstract
{
static void Main(string[] args)
{
5Jam.leAbsract obD = ne/ 5Jam.leAbsract();
::abstract class cannot be instantiated
*
*
In the preceding code the abstract class is created by using the abstract *eyword. here are
certain rules governing the use of an abstract class. he rules are$
"annot create an instance of an abstract class
"annot create an abstract method outside an abstract class
"annot be declared sealed
+ote$
Sealed classes can ne%er be inherited.
:sing Abstract Methods
3hen using inheritance relationship, you can have a situation where you want to method in a
class to be implemented differently in the derived classes but not by the base class itself. 'bstract
methods are the methods without any body. he implementation of an abstract method is done by
the derived class. 3hen a derived class inherits the abstract method from the abstract class, it
must override the abstract methods. his re/uirement is enforced at compile time, and is also
called dynamic polymorphism.
he synta! for using the abstract method is
[access0modifiers] abstract return0ty.e met(od0name ([.arameters])
he following code is an e!ample of using abstract classes with abstract methods$
using System;
abstract class Animal
{
.ublic abstract void -ood=abits();
*
class #arnivorous ) Animal
{
.ublic override void -ood=abits()
{
#onsole$%rite&ine('7(e #arnivorous animals eat only meat');
*
*
class =erbivorous ) Animal
{
.ublic override void -ood=abits()
{
#onsole$%rite&ine('7(e =erbivorous animals eat only
.lants');
*
*
class 8m.lement
{
static void Main(string[] args)
{
#arnivorous cn = ne/ #arnivorous();
=erbivorous (n = ne/ =erbivorous();
cn$-ood=abits();
(n$-ood=abits();
*
*
In the preceding code e!ample, the abstract method is declared by adding the abstract modifier
to the method. 'bstract method (ood:abits() is declared in the abstract class 'nimal. 'nd then
the abstract method is inherited in "arnivorous and :erbivorous class. 'bstract methods cannot
contain any method body.
Hsing Cirtual (unctions
3hen you have a function defined in a class which you want to allow to be implemented by the
inherited classes, you can use virtual function could be implemented by the inherited classes on
their own way and the call to the method is decided at runtime.
he following code is an e!ample of using virtual function$
using System;
names.ace Virtual-unction
{
class Animal
{
.ublic virtual void -ood=abits()
{
#onsole$%rite&ine('Animals (ave different food (abits');
*
*
class #arnivorous ) Animal
{
.ublic override void -ood=abits()
{
#onsole$%rite&ine('7(e #arnivorous animals eat only meat');
*
*
class =erbivorous ) Animal
{
.ublic override void -ood=abits()
{
#onsole$%rite&ine('7(e =erbivorous animals eat only
.lants');
*
*
class 8m.lement
{
.ublic void call-unction(Animal #r)
{
#r$-ood=abits();
*
*
class #lassMain
{
static void Main(string[] args)
{
8m.lement 8m. = ne/ 8m.lement();
#arnivorous cn = ne/ #arnivorous();
=erbivorous (n = ne/ =erbivorous();
8m.$call-unction(cn);
8m.$call-unction((n);
#onsole$,ead&ine();
*
*

*
In the preceding code, the base class named 'nimal has a virtual function named (ood:abits.
he derived classes "arnivorous and :erbivorous override the method (ood:abits of the base
class 'nimal and implement their own functionality. he method named call(unction ta*es and
argument of 'nimal class and calls (ood:abits() method to, which in turn will call the most
appropriate derived method.
:sing )ealed Classes
here may be times when you do not need a class to be e!tended. )ou may even want to
deliberately force users not to inherit a class. )ou could restrict users from inheriting the class by
sealing the class using the sealed *eyword. he *eyword tells the compiler that the class is
sealed, and therefore, cannot be e!tended. +o class can be derived from a sealed class. he
following is a e!ample of a sealed class.
sealed class -inal#lass
{
.rivate int J;
.ublic void Met(od1()
{
*
*
he method can also be sealed, and in that case, the method cannot be overridden. he
following is an e!ample of using sealed method in a sealed class$
sealed class -inal#lass
{
.rivate int J;
.ublic sealed void Met(od1()
{
*
*
:sing #nterfaces
'n interface defines the syntactical contract that all the derived classes should follow. ,pecifically
the interface defines what part of the syntactical contract, and the classes implementing the
interface describe the how part of the contract. "# has full support for interfaces.
Interfaces also define properties, methods, and events which are *nown as members of the
interface. It is important to note that interfaces contain only the declaration of members. "lasses
and structures implement these interface members. Interface is used when you want to standard
structure of methods to be followed by the classes, where classes will implement the functionality.
3hereas, abstract classes are used in the situation where you want only few methods to declare
by the base class and the derived class will implement the functionality.
Interfaces enable you to separate the definition of objects from their implementation so that the
objects can evolve without the ris* of introducing incompatibility in e!isting application.
+or@ing (ith #nterfaces
3or*ing with interfaces includes interface declaration and implementation of interface by the
classes.
eclaring #nterfaces
)ou can declare interfaces using the interface *eyword. he declaration of interfaces is very
similar to class definition. Interface statements are public by default. he following code is an
e!ample of an interface declaration$
.ublic interface 8Frder@etails
{
::@eclare an interface member
void V.date#ustStatus();
void 7a2eFrder();
*
)ou can declare only methods, functions, and properties in interfaces. )ou cannot declare a
variable in interfaces.
Implementing Interfaces
Interfaces declare methods, which are implemented by classes. ' class can inherit from single
class but can implement from multiple interfaces. he following code is an e!ample of interface
implementation$
.ublic interface 8Frder@etails
{
::@eclare an interface member
void V.date#ustStatus();
void 7a2eFrder();
*
.ublic class 8tems@etails ) 8Frder@etails
{
.ublic void V.date#ustStatus()
{
$$$$
*
.ublic void 7a2eFrder()
{
$$$$
*
*
Interfaces can inherit members from an e!isting interface. he class which implements from an
interface needs to implement all the members of the interface.
Inheriting Interfaces
he following code shows how interfaces inherit from the e!isting interface$
.ublic interface ValidateL#ust
{
void ValidateL#ustname();
*
.ublic interface 8Frderdetails ) ValidateL#ust
{
void V.date#ustStatus();
*
' class or a structure that implements interfaces also implements the base interface of it inherited
interface. In the preceding e!ample, the IOrder&etails interface inherits the member,
CalidateM"ustname(), from the base interface, CalidateM"ust. If a class implements the
IOrder&etails interface, then it implicitly implements the CalidateMcust interface.
'ctivity$ Order-Processing ,ystem Hsing 'bstract "lasses
Problem ,tatement
(urniture and (itting "ompany (((") manufactures domestic furniture. "ustomers provide their
specifications to the company for the furniture they want. o cope with the received customer.s
orders, ((" decides to computeri2e the order-processing system. he system should accept the
values of furniture items, such as boo*shelf and a chair. )ou need to to develop the hierarchy of
these items.
,olution
o develop the re/uired application, ime needs to perform the following tas*s$
;. "reate a console based application
D. 0uild and e!ecution an application.
as* ;$ "reating a "onsole-0ased 'pplication
/* ,elect )tart All "rogra!s Microsoft 1isual )tudio 0445 Microsoft 1isual
)tudio 0445* he )tart "age C Microsoft 1isual )tudio window will be displayed
0* ,elect File 2e( "roject* he 2e( "roject dialog bo! will be displayed
6* ,elect the project type as 1isual C$ from the "roject types pane and Console
Application from the Te!plates pane.
7* ype the name of the new project as FFC in the 2a!e te!t bo!.
5* ,pecify the location where the new project is to be created as c-Dchapter9DActivity/ in
the ,ocation combo bo!.
3* "lic* the O' button.
8* Open the )olution Explorer window and right-clic* the "rogra!*cs file.
9* ,elect the Rena!e option and type the new name as Furniture*cs
>* &ouble-clic* the Furniture*cs file in the solution explorer window. he code view of the
Furniture*cs file is displayed
/4* Geplace the e!isting code with the following code$
using System;
names.ace --#
{
.ublic abstract class -urniture
{
.rotected string color;
.rotected int /idt(;
.rotected int (eig(t;
.ublic abstract void Acce.t();
.ublic abstract void @is.lay();
*
class 1oo2S(elf ) -urniture
{
.rivate int numFfLs(elves;
.ublic override void Acce.t()
{
string str!+ str9+ strE;
#onsole$%rite&ine('5nter values for 1oo2s(elf');
#onsole$%rite&ine('5nter color');
color = #onsole$,ead&ine();
#onsole$%rite&ine('5nter %idt(');
str! = #onsole$,ead&ine();
/idt( = #onvert$7o8nt9!(str!);
#onsole$%rite&ine('5nter =eig(t');
str9 = #onsole$,ead&ine();
(eig(t = #onvert$7o8nt9!(str9);
#onsole$%rite&ine('5nter 3o$ Ff S(elves');
strE = #onsole$,ead&ine();
numFfLs(elves = #onvert$7o8nt9!(strE);
*
.ublic override void @is.lay()
{
#onsole$%rite&ine('@8S6&AU83I VA&V5S -F, 1FFPS=5&-');
#onsole$%rite&ine('#olor is {0*'+ color);
#onsole$%rite&ine('%idt( is {0*'+ /idt();
#onsole$%rite&ine('=eig(t is {0*'+ (eig(t);
#onsole$%rite&ine('3umber of S(elves is {0*'+
numFfLs(elves);
*
*
class #(air ) -urniture
{
.rivate int numFfLlegs;
.ublic override void Acce.t()
{
string str!+ str9+ strE;
#onsole$%rite&ine('5375, VA&V5S -F, #=A8,');
#onsole$%rite&ine('5nter color');
color = #onsole$,ead&ine();
#onsole$%rite&ine('5nter %idt(');
str! = #onsole$,ead&ine();
/idt( = #onvert$7o8nt9!(str!);
#onsole$%rite&ine('5nter =eig(t');
str9 = #onsole$,ead&ine();
(eig(t = #onvert$7o8nt9!(str9);
#onsole$%rite&ine('5nter 3o$ Ff legs in a c(air');
strE = #onsole$,ead&ine();
numFfLlegs = #onvert$7o8nt9!(strE);
*
.ublic override void @is.lay()
{
#onsole$%rite&ine('@8S6&AU83I VA&V5S -F, #=A8,');
#onsole$%rite&ine('#olor is {0*'+ color);
#onsole$%rite&ine('%idt( is {0*'+ /idt();
#onsole$%rite&ine('=eig(t is {0*'+ (eig(t);
#onsole$%rite&ine('3umber of legs is {0*'+ numFfLlegs);
*
*
class 1oo2S(elf#(air
{
static void Main(string[] args)
{
1oo2S(elf b1 = ne/ 1oo2S(elf();
#(air c1 = ne/ #(air();
b1$Acce.t();
b1$@is.lay();
c1$Acce.t();
c1$@is.lay();
#onsole$,ead&ine();
*
*
*
as* D$ 0uilding and %!ecuting an 'pplication
o build and e!ecute the application perform the following steps$
/* 0uild the solution by pressing Ctlr G )hift Gb
0* ,elect ebug )tart ebugging or press F5 to e!ecute the application
6* Cerify the output of the application
Practice `uestions
;. "onsider the following statements
,tatement ' $ Inheritance reduces the redundancy in code
,tatement 0 $ Inheritance enables easy maintenance of code.
3hich of the following is true about the given statements
a. ,tatement ' is true, and ,tatement 0 is false
b. ,tatement ' is false, and ,tatement 0 is true
c. 0oth ,tatements ' and 0 are true
d. 0oth ,tatements ' and 0 are false.
D. "onsider the following code
a. Coid c() and void d()
b. Coid a() and void b()
c. Coid a(), void b(), void c() and void d()
d. Coid a(), void c() and void d()
?. 3hich of the following is true about abstract classes1
a. 'n abstract class defines the properties common to the classes derived from it.
b. 'n abstract class can be declared as final
c. 'bstract classes cannot be e!tended
d. "lasses declared using the abstract *eyword can be instantiated.
@. "onsider the following code$
interface a
{
void b();
*
class c
{
void a$b() { *
*
3hich of the following statement generates the compilation error in the preceding code1
a. Interface a
b. Coid b()
c. Coid a.b() NS
d. "lass c
A. "onsider the following statements$
,tatement '$ ' class cannot have more than one derived class.
,tatement 0$ Inheritance increases the functionality of a base class by adding additional
features to its derived classes.
3hich of the following statement is true1
a. ,tatement ' is true, and ,tatement 0 is false
b. ,tatement ' is false, and ,tatement 0 is true
c. 0oth ,tatements are true
d. 0oth ,tatements are false.
,ummary
In this chapter, you learned that$
he four *inds of relationships that e!ists among classes are$
o Inheritance relationship
o "omposition relationship
o Htili2ation relationship
o Instantiation relationship
OOP enables classes to inherit commonly used state and behavior from other classes.
5enerali2ation means that multiple classes can inherit from the same superclass.
he composition relationship e!ists when one class is made up of another class.
he utili2ation relationship e!ists between D or more unrelated classes if one class uses
the other.
'n instantiation relationship is a relationship between a class and an instance of that
class.
' class that inherits or derives attributes from another class is called the derived class
and the class from which it is derived is called the base class.
Inheritance avoids redundancy in code and enables easy maintenance of code.
"onstructors are called in the order of base-to-derived.
'n abstract superclass is a conceptual class that does not e!ist in real world but acts as
a base from which other classes inherit properties behavior
' sealed class tells the compiler that the class cannot be e!tended further. )ou cannot
derive a class from a sealed class.
'n interface defines properties, methods, and events. he properties, methods, and
events that are defined in the interface are *nown as the members of the interface.
%!ercises
%!ercise ;
Philip 'nderson is a software developer who wor*s for Bega echnnologies. :e is currently under
the project of geometric calculations. Philip has to develop a program, which performs the
following tas*s$
;. "alculate the area of the circle
D. "alculate the volume of the cube
:e has to develop the code using an interface
%!ercise D
,amuel ,mith a student of "alifornia university is currently pursuing 0achelors in Information
echnology (I). ,amuel has got an assignment to develop a program using the abstract classes,
which displays the following statements$
;. I.m a line
D. I.m a circle
?. I.m a s/uare
:e has to create a &raw() function in a program, to display the preceding statements
Chapter >
File #nput and Output
(or information to be saved permanently on a dis*, you can use a file. he file is a stream of
characters or a flow of related data. ,treams enable you to write and read bytes to and from a
storage medium, respectively. ,treams can be used to perform fundamental operations such as
read and write.
his chapter introduces the concept of the file input and output operations. It e!plains the process
of reading and writing in the te!t files ad the binary files. It also e!plains the process of browsing
through the 3indows (ile ,ystem.
Objectives
In this chapter, you will learn to$
Implement the file input and output operations
Implement read and write in te!t files
Implement read and write in binary files
Implement the 3indows (ile ,ystem
#!ple!enting the File #nput and Output Operations
'll programs accept input from a user, process the input, and produce an output. herefore, all
the programming languages support the input and output operations. (or information to be saved
permanently on a dis*, you can use a file. he file is a collection of data stored on a dis* with a
specific name and very often with a directory path. 3hen you open the file for reading data or
writing data, it becomes a stream.
he stream is a se/uence of bytes traveling from a source to a destination over a communication
path. he two basic streams used are the input and output streams. %ach stream has a particular
function. 'n input stream is used for a read operation and an output stream is used for performing
a write operation. )ou can perform both these operations over the stream.
he ,ystem.IO namespace includes various classes, which are used to perform operations, such
as file creation, file deletion, and read-write operations to files.
he following table describes some commonly used classes in the ,ystem. IO namespace.
C"ass Name *escriptin
"ileStrea& Is !sed to read fro& and write to any location within a file
$inaryReader Is !sed to read pri&iti%e data types fro& a binary strea&
$inaryHriter Is !sed to write pri&iti%e data types in a binary for&at
Strea&Reader Is !sed to read characters fro& a byte strea&
Strea&Hriter Is !sed to write characters to a strea&
StringReader Is !sed to read fro& string b!ffer
StringHriter Is !sed to write into a string b!ffer
(irectoryInfo Is !sed to perfor& operations on directories
"ileInfo Is !sed to perfor& operations on files
In .+%, you can wor* with streams by using the (ile,tream class. his class supports random
access to files, which means to read from and write to any location within a file.
(ile,tream "lass
Bost file InputYOutput (IYO) support in the .+% (ramewor* is implemented in the system.IO
namespace. )ou can use the (ile,tream class in the ,ystem.IO namespace to read from, to write
and to close files. his class inherits from the abstract class ,tream. Bany of its properties and
methods are also derived from the ,tream class.
o open an e!isting file or to create a new file, you need to create an object of type (ile,tream.
"onsider the following synta! for creating the object of type (ile,tream$
-ileStream obDect nameT = ne/ -ileStream(-ile 3ameT+ -ileMode
5numeratorT+ -ile AccessViolation5Jce.tion 5numeratorT+ -ileS(are
5numeratorT);
"onsider the following e!ample of creating the object of type (ile,tream$
-ileStream -ile1 = ne/ -ileStream('My-ile$7Jt'+ -ileMode$F.en+
-ileAccess$,ead+ -ileS(are$,ead);
In the preceding e!ample, the (ileBode, (ile'ccess and (ile,hare enumerations define
constants that are used by some of the (ile,tream and the Isolated,torage(ile,tream
constructors and some of the (ile.Open overloaded methods. hese constants affect the way in
which the underlying file is created, opened and shared
(ileBode %numerator
his enumerator defines various methods for opening files. he (ileBode enumerator parameter
is specified in many constructors for the (ile,tream, Isolated,torage(ile,tream constructors, and
in the Open methods of (ile and (ileInfo to restrict how a file is opened. he parameters to
(ileBode chec*s whether a file is overwritten, created, or opened.
he members of the (ileBode enumerator are$
Append$ Opens the file if it e!ists and places the cursor at the end of file, or creates a
new file.
Create- "reates a new file
Create2e(- ,pecifies to an operating system that it should create a new file
Open- Opens an e!isting file
OpenOrCreate- ,pecifies to the operating system that it should open a file if it e!istsR
otherwise, it should create a new file.
Truncate- Opens an e!isting file. 3hen opened, the file should be truncated so that its
si2e is 2ero bytes.
FileAccess Enu!erator
Hnless you specify a (ile'ccess enumerator, the file gets opened for both reading and writing.
his enumerator indicates whether you want to read data from the file, write to the file, or perform
both the operations.
he members of the (ile'ccess enumerator are Gead, Gead3rite, and 3rite.
File)hare Enu!erator
he (ile,hare enumerator contains constants for controlling the *ind of access that the other
(ile,tream constructors can have to the same file. ' typical use of this enumeration is to define
whether two different applications can simultaneously read from the same file.
he members of the (ile,hare enumerator are$
#nheritable- 'llows a file handle to pass inheritance to the child processes.
2one- &eclines sharing of a current file
Read- 'llows opening of a file for reading purposes
Read+rite- 'llows opening a file for the purpose of reading and writing
+rite- 'llows opening of a file for writing purpose.
#!ple!enting Reading and +riting in the Text Files
he ,tream class is used to read from and to write data in the te!t files. It is an abstract class,
which supports reading and writing bytes into it. If data of a file in only te!t, then you can use the
,treamGeader class and the ,tream3riter class to accomplish the reading and writing tas*s,
repectively.
,treamGeader "lass
he ,treamGeader class is inherited from the abstract class e!tGeader. he e!tGeader class
represents a reader which can read a series of characters.
he following code implements the ,treamGeader class$
-ileStream fs = ne/ -ileStream('Myfile$tJt'+ -ileMode$F.en+
-ileAccess$,ead);
Stream,eader sr = ne/ Stream,eader(fs);
sr$1aseStream$See2(0+ See2Frigin$1egin);
string str = sr$,ead&ine();
In the preceding code, the ,ee*() method allows the readYwrite position to be moved to any
position within the file. his method ta*es two parameters, a byte position and a reference point.
he byte position is relative is relative to the reference point. he reference point can be 0egin,
"urrent, or %nd. hese reference points are represented by the properties of the ,ee*Origin
class.
he reference point, 0egin, provides the see* reference position as the beginning of the stream.
"urrent provides the see* reference position as the current position within the stream and the
reference point. %nd, provides the see* reference position as the end of the stream. he objects f
the (ile,tream class are used to provide random access to files. he (ile,tream constructor
ta*es parameters that are used to initiali2e the member of the class.
he following table describes some of the commonly used methods of the ,treamGeader class.
'ethds *escriptin
Close Closes the object of Strea&Reader class and the !serlying strea&, and
releases any syste& reso!rces associates with the reader
ee, Ret!rns the ne1t a%ailable character b!t does not cons!&e it
Read Reads the ne1t character or the ne1t set of characters fro& the strea&
ReadJine Reads a line of characters fro& the c!rrent strea& and ret!rns data as a
string
See, .llows the readRwrite position to be &o%ed to any position within the file.
he following code snippet implements the ,treamGeader class the read data from the file$
using System;
using System$8F;
class -ile,ead
{
.ublic void ,ead@ata()
{
-ileStream fs = ne/ -ileStream('Myfile$tJt'+ -ileMode$F.en+
-ileAccess$,ead);
Stream,eader sr = ne/ Stream,eader(fs);
::6osition t(e file .ointer at t(e beginning of t(e file
sr$1aseStream$See2(0+ See2Frigin$1egin);
::,ead till t(e end of t(e file is encountered
string str = sr$,ead&ine();
/(ile (str ?= null)
{
#onsole$%rite&ine('{0*'+ str);
str = sr$,ead&ine();
*
::#lose t(e /riter and underlying file
sr$#lose();
fs$#lose();
*
.ublic static void Main(string[] args)
{
-ile,ead fr = ne/ -ile,ead();
fr$,ead@ata();
*
*
,tream3riter "lass
he ,tream3riter class is inherited from the abstract class e!t3riter. he e!t3riter class
represents a writer, which can write a series of characters.
he following table describes some of the commonly used methods of the ,tream3riter class.
'ethds *escriptin
Close Closes the c!rrent Strea&Hriter object and the !nderlying strea&.
"l!sh Clears all b!ffers for the c!rrent writer and ca!ses any b!ffered data to be
written to the !nderlying strea&
Hrite Hrites to the strea&
HriteJine Hrites data specified by the o%erloaded para&eters, followed by end of line.
he following code implements the ,tream3riter class to accept data from a user and write the
same into the file.
using System;
using System$8F;
class -ile%rite
{
.ublic void %rite@ata()
{
:: FbDect of filestream class is created
-ileStream fs = ne/ -ileStream('Myfile$tJt'+
-ileMode$A..end+ -ileAccess$%rite);
Stream%riter / = ne/ Stream%riter(fs);
::6rom.ting user to enter t(e string /(ic( needs to be
stored in t(e file
#onsole$%rite&ine('5nter a string');
::,eads t(e string entered by t(e user and stores in str
string str = #onsole$,ead&ine();
::%rite t(e string entered by t(e user in t(e file
Myfile$tJt
/$%rite(str)
::#lears all buffer of t(e current /riter
/$-lus(();
::#lose t(e current Stream%riter FbDect$
/$#lose();
fs$#lose();
*
.ublic static void Main(string[] args)
{
-ile%rite f/ = ne/ -ile%rite();
f/$%rite@ata();
*
*
In the preceding code, the (ileBode property value is 'ppend and the (ile'ccess property value
is 3rite. his opens the file, Byfile.t!t, in the append mode and prepares the stream for a write
operation. he statement, ,tream3riter w ^ new ,tream3riter(fs), creates a new instance of the
,tream3riter class for By(ile.t!t.
In addition, code accepts input from a user and writes the contents to Byfile.t!t. the functions that
can be used for the write operations are 3rite() and 3rite4ine(). he difference between 3rite()
and 3rite4ine() operations is that the 3rite() method is 3rite4ine() method is used to display the
information followed by a line terminator.
he (lush() methods clears the stream buffer. he "lose() method closes the stream and
releases any resources associated with the current stream.
Implementing Geading and 3riting in 0inary (iles
'll the information stored in the te!t format would be displayed on a screen as te!t. his means
-'. will be written as -'. in the files. ,imilarly, the number -;D?@A.I>< will be written as the string 6-
;D?@A.I><8. his means that you can directly display the contents of the file on the screen.
0inary read and write means that the number -;D?@A.I>< is written as a float representation
consuming four bytes of space. he 0inaryGeader and 0inary3riter classes are used for reading
and writing the binary data in to files.
0inaryGeader "lass
he 0iinaryGeader class is used to read binary data from a file. )ou can create 0inaryGeader
object by passing its constructors, a (ile,tream object, as shown in the following code snippet$
-ileStream fs = ne/ -ileStream(X'#)B75S7!$@A7'+ -ileMode$F.en+
-ileAccess$,ead);
1inary,eader br = ne/ 1inary,eader(fs);
he following table describes some of the commonly used methods of the 0inaryGeader class.
'ethd *escriptin
Close Closes the c!rrent reader and the !nderlying strea&
Read Reads characters fro& the !nderlying strea& and ad%ances the c!rrent position of
the strea&.
Ainary+riter Class
he 0inary3riter class is used to write binary data to a stream. )ou can create a 0inary3riter
object by passing its constructors, a (ile,tream object as shown in the following code snippet$
-ileStream fs = ne/ -ileStream(X'#)B75S7!$@A7'+ -ileMode$#reate3e/);
1inary%riter br = ne/ 1inary%riter(fs);
he following table describes some of the commonly used methods of the 0inary3riter class.
'ethd *escriptin
Close Closes the c!rrent $inaryHriter and the !nderlying strea&
See, Sets the position within the c!rrent strea&
Hrite Hrites a %al!e to the c!rrent strea&
"l!sh Clears all b!ffers for the c!rrent writer and ca!ses any b!ffered data to be written to
the !nderlying de%ice.
he following ode snippet shows the implementation of the 0inary Geading and 3riting classes to
a file$
using System;
using System$8F;
names.ace 1inary@ata
{
.ublic class ,%@ata
{
.ublic static void Main(string[] args)
{
1inary%riter dataout;
1inary,eader datain;
int i = 10;
double d = 10!9$4G;
bool b = true;
try
{
dataout = ne/ 1inary%riter(ne/ -ileStream('testdata'+
-ileMode$#reate));
*
catc( (8F5Jce.tion eJc)
{
#onsole$%rite&ine(eJc$Message " 'Bn#annot o.en file$');
return;
*
try
{
#onsole$%rite&ine('%riting' " i);
dataout$%rite(i);
#onsole$%rite&ine('%riting' " d);
dataout$%rite(d);
#onsole$%rite&ine('%riting' " b);
dataout$%rite(b);
#onsole$%rite&ine('%riting' " 1!$! > H$E);
dataout$%rite(1!$! > H$E);
*
catc( (8F5Jce.tion eJc)
{
#onsole$%rite&ine(eJc$Message " 'Bn %rite error$');
*
dataout$#lose();
#onsole$%rite&ine();
::3o/+ read t(em bac2$
try
{
datain = ne/ 1inary,eader(ne/ -ileStream('testdata'+
-ileMode$F.en));
*
catc( (-ile3ot-ound5Jce.tion eJc)
{
#onsole$%rite&ine(eJc$Message " 'Bn #annot o.en file$');
return;
*
try
{
i = datain$,ead8nt9!();
#onsole$%rite&ine(',eading' " i);
d = datain$,ead@ouble();
#onsole$%rite&ine(',eading' " d);
b = datain$,ead1oolean();
#onsole$%rite&ine(',eading' " b);
d = datain$,ead@ouble();
#onsole$%rite&ine(',eading' " d);
*
catc( (8F5Jce.tion eJc)
{
#onsole$%rite&ine(eJc$Message " ',ead error$');
*
#onsole$,ead&ine();
datain$#lose();
*
*
*
Implementing the 3indows (ile ,ystem
he ablity to browse and locate files and directories for a specific directory is essential for many
programming tas*s. )ou can wor* with files and directories by using classes such as the
&irectoryInfo and (ileInfo classes in combination. Hsing these classes is an efficient way to
gather the re/uired information about files and directories in a specific location.
&irectoryInfo
he &irectoryInfo class is derived from the (ile,ystemInfo class. he following table describes
some of the commonly used properties of the &irectoryInfo class.
Prperty *escriptin
.ttrib!tes Kets or sets attrib!tes associated with the c!rrent file. 2his property
is inherited fro& "ileSyste&Info.
Creation2i&e Kets or sets Creation2i&e of the c!rrent file. 2his property is
inhertied by "ileSyste&Info
01ists Kets a boolean %al!e indicating whether the directory e1ists or not.
01tension Kets a string containing the file e1tension. 2his property is inherited
fro& "ileSyste&Info
"!ll8a&e Kets a string containing the f!ll path of the directory. . 2his property
is inherited fro& "ileSyste&Info
Jast.ccess2i&e Kets the last accessed ti&e of the directory. 2his property is
inherited fro& "ileSyste&Info
8a&e Kets a string containing the na&e of a gi%en file.
he following table describes the most commonly used methods of the &irectoryInfo class.
'ethd *escriptin
Create Creates a directory
CreateS!bdirector
y
Creates a s!bdirectory
(elete (eletes a directory
Ket(irectories Ret!rns the directories in the c!rrent directory after watching all the criteria.
It also allows yo! to search s!bdirectories within directories
Ket"iles Ret!rns the files in the c!rrent directory
he following code snippet shows how to create a &irectoryInfo object$
@irectory8nfo Mydir8nfo = ne/ @irectory8nfo(X'#)B%83@F%S');
#onsole$%rite&ine('-ull3ame of t(e directory is {0*'+
Mydir8nfo$-ull3ame);
#onsole$%rite&ine('7(e directory /as last accessed on {0*'+
Mydir8nfo$&astAccess7ime$7oString());
he preceding code snippet creates the &irectoryInfo object by the name BydirInfo. he code
snippet displays the full path to the directory and the time when the directory was last accessed.
(ileInfo "lass
he (ileInfo class is derived from the (ile,ystemInfo class. he following table describes the
most commonly used methods of the (ileInfo class.
Prperty *escriptin
.ttrib!tes Kets or sets attrib!tes associated with the c!rrent file. 2his property is
inherited fro& "ileSyste&Info.
Creation2i&e Kets or sets Creation2i&e of the c!rrent file. 2his property is inhertied by
"ileSyste&Info
(irectory Kets an instance of the directory which the file belongs to
01ists Kets a $oolean %al!e indicating whether the file e1ists or not
01tension Kets a string containing the file e1tension. 2his property is inherited fro&
"ileSyste&Info
"!ll8a&e Kets a string containing the f!ll path of the file. . 2his property is inherited
fro& "ileSyste&Info
Jast.ccess2i&e Kets the last accessed ti&e of the file. 2his property is inherited fro&
"ileSyste&Info
JastHrite2i&e Kets the ti&e of the last written acti%ity to the file. . 2his property is inherited
fro& "ileSyste&Info
Jength Kets the si<e of the file
8a&e Kets a string containing the na&e of a gi%en file
he following table lists some of the commonly used methods of the (ileInfo class and their
functions.
'ethd +unctin
Create Creates a directory
.ppend2e1t .ppends a te1t to the file represented by the "ileInfo object
(elete (eletes a file
Open Opens file
OpenRead Opens a file in read9only &ode
he following code shows the use of the (ileInfo class$
using System;
using System$8F;
names.ace -ileL=andling
{
class 7ester
{
.ublic static void Main(string[] args)
{
::#reating an instance of @irectory8nfo class
@irectory8nfo Mydir8nfo = ne/ @irectory8nfo(X'#)B%83@F%S');
::get all t(e files in t(e directory and
::.rint t(eir name+ and siKe
-ile8nfo[] -iles8n@ir = Mydir8nfo$Iet-iles();
foreac( (-ile8nfo file in -iles8n@ir)
{
#onsole$%rite&ine('-ile 3ame) {0* SiKe) {1* bytes'+
file$3ame+ file$&engt();
*
*
*
*
In the preceding code, the 5et(iles() method is used to retrieve the list of all the files in the
directory. his code displays the list of all the files the directory and their si2es.
Practice `uestions
;. 3hich method in the following code writes the input to the stream1
a. ,tring str ^ "onsole.Gead4ine()R
b. ,w.3rite(,tr)R
c. ,w.(lush()R
d. ,w."lose()R
D. )ou need to access a file named By(ile.t!t. If the file already e!ists on the system, you
need to open itR else you need to ensure that a new file with the file name By(ile.t!t is
created. 3hich of the following statements would you write to do the preceding tas*1
a. (ile,tream (s ^ new (ile,tream(6c$QQBy(ile.t!t8, (ileBode."reate,
(ile'ccess.3rite)R
b. (ile,tream (s ^ new (ile,tream(6c$QQBy(ile.t!t8, (ileBode."reate+ew,
(ile'ccess.3rite)R
c. (ile,tream (s ^ new (ile,tream(6c$QQBy(ile.t!t8, (ileBode.Open,
(ile'ccess.3rite)R
d. (ile,tream (s ^ new (ile,tream(6c$QQBy(ile.t!t8, (ileBode.OpenOr"reate,
(ile'ccess.3rite)R
?. he method that is used to alter the positions from where a read and write operation can
occur is MMMMMM
@. Batch the following terms in column 0 to the description in column '
A B
.ttrib!te Kets or sets Creation2i&e of the c!rrent file
Creation2i&
e
Kets a $oolean %al!e indicating whether the directory e1ists or not
01its Kets or sets attrib!te associated with the c!rrent file. 2his property is
inherited fro& "ileSyste&Info
A. Fohn wants to perform a readYwrite operation on a file. :e does not want the file to be
overwritten when he is performing the write operation. 3hich (ileBode should he use1
)u!!ary
In this chapter, you have learned that$
' stream is an abstraction of a se/uence of bytes traveling from a source to a destination
over a communication path.
he two basic streams used are the input and output streams. 'n input stream is used for
a read operation and an output stream in used for performing a write operation
Bost file IYO support in .+% (ramewor* is implemented in the ,ystem.IO namespace.
)ou can use the (ile,tream class in the ,ystem.IO namespace to read from, to write and
to close files.
he (ile,tream class inherits from the abstract class ,tream.
he ,tream class is used to read and write data to the te!t files. It is an abstract class,
which supports reading and writing bytes into it.
he ,treamGeader class is inherited from the abstract class e!tGeader. he e!tGeader
class represents a reader which can read a series of characters.
he ,tream3riter class is inherited from the abstract class e!t3riter. he e!t3riter
class represents a writer which can write a series of characters.
he 0inaryGeader class allows reading of binary data from a file.
he 0inary3riter class allows writing of binary data to a stream.
he &irectoryInfo class is derived from (ile,ystemInfo class and its wor*s on a specific
directory and shows the fullpath of the current directory
he (ileInfo class is derived from (ile,ystemInfo class and its wor*s on a specific
directory to display the list of all the files.
Exercises
Exercise /
&avid is a team leader of !y2 organi2ation. :e wants to create a scheduler, which will store fields,
such as the appointment date, the name of the person to meet, and time. :e needs to develop an
application that will enable the user to fill these fields.
he application should display certain options. he options are$
Add appoint!ent$ ,hould accept values such as appointment date, name of the person
to be met, and time of the appointment.
1ie( appoint!ent$ ,hould display all the appointments of the user
)earch$ ,hould prompt the user to specify the date to view all the appointments of that
day
Exit$ 'llow the user to e!it the application
:int$ he date that the application should accept should be in the mmYddYyyyy format.
Exercise 0
)ou need to generate a program to play the :angman game. he program as*s a user to enter a
category as 0oo* or Bovie. 0ased on the category provided, a boo* name or movie name is
e!tracted and the user is as*ed to guess the name by giving the character and its position in the
string.
Chapter /4
Exception Fandling
'n e!ception is termed as an abnormal condition encountered by an application during e!ecution.
%!ception handling is the process of providing an alternative path of e!ecution when the
application is unable to e!ecute as desired.
his chapter describes e!ceptions. It e!plains how to implement the try, catch and finally bloc*s.
In addition, it also discusses the implementation of user-defined e!ceptions.
Objectives
In this chapter, you will learn to
&escribe e!ceptions
:andle e!ceptions
Implement the user-defined e!ceptions
&escribing %!ceptions
'n e!ception is an erroneous situation that occurs during program e!ecution. %!ceptional
situations arise when an operation cannot be e!ecuted normally. 3hen an e!ception occurs in an
application, the system throws an error. he error is handled through the process of e!ception
handling.
(or e!ample, the ,ystem.IO.IO%!ception error is thrown when you try to access an illegal stream
object. ,imilarly, if the denominator is 2ero, an integer division operation throws the
,ystem.&ivide0yaero%!ception error.
3henever an error occurs, runtime creates an e!ception object and sends it to the program in
which the e!ception occurred. his action is *nown as throwing an e!ception. he e!ception
object contains information about the type of error.
ypes of %rrors
here are ? types of errors that can occur in the applications. hese are$
,ynta! errors
Gun-time errors
4ogical errors
' syntac error occurs when compiler cannot compile code. ,uch an error can occur when
statements are not constructed properly, *eywords are misspelled, or punctuation is omitted. 't
compilation time all the statements in the application get connected with each other to ma*e a
single e!ecutable unit.
' run-time error occurs when an application attempts to perform an operation, which is not
allowed at runtime. 'n e!ample of such an error is division by 2ero. ' run-time error is also
termed as an e!ception. 'll the e!ceptions are defined in the predefined set of classes.
' logical error occurs when an application compiles and runs properly but does not produce the
e!pected results.
'll the e!ceptions are derived from the ,ystem.%!ception class, which is the parent class of all
e!ceptions.
%!ception "lasses
here are many e!ception classes which are directly or indirectly derived from the
,ystem.%!ception class. ,ome of the e!ception classes derived from the ,ystem.%!ception
classes are the ,ystem.'pplication%!ception and ,ystem.,ystem%!ception classes
he hierarchy of the e!ception classes is displayed in the following figure
he ,ystem.'pplication%!ception class is forwarded by a user program, and not by the "4G. If
any user-defined application re/uires its own e!ception, it should inherit the e!ception from the
'pplication%!ception class.
he ,ystem.,ystem%!ception acts as a base class for all the predefined system e!ceptions. he
following table describes some of the classes derived from the ,ystem.,ystem%!ception class.
E&ceptin C"asses *escriptins
%ystem.&'.&'()ception +andles IRO errors
%ystem.&nde)'uto*#ange()ception +andles errors generated when a &ethod to refers
to an array ele&ent, which is o!t of its bo!nd
%ystem.Null#e*erence()ception +andles errors generated d!ring the process of
dereferencing a n!ll object
%ystem.Divide+y,ero()ception +andles errors generated d!ring the process of
di%iding the di%ided with <ero
%ystem.&nvalid"ast()ception +andles errors generated d!ring typecasting
%ystem.'ut'*Memory()ception +andles &e&ory allocation to the application
errors.
:andling %!ceptions
)ou need to handle an e!ception in your program by using an e!ception-handler. his handler
processes the e!ception. In e!ception handling, the application is divided into bloc*s of code. '
bloc* that shows the probability of raising an error contains one or more e!ception handlers.
hese handlers follow a control structure and a uniform way of handling the system level and
application level errors.
he following e!ample shows an e!ception is a variable is divided by 2ero$
using System;
names.ace SystemL5Jce.tion
{
class AddL3um
{
.ublic static void AddingL3umbers(int number1+ int number!)
SystemException
SystemApplicationException
SystemSystemnException
{
int res = number1 : number!;
#onsole$%rite&ine(res);
*
static void Main(string[] args)
{
AddL3um$AddingL3umbers (10+0)
#onsole$,ead&ine();
*
*
*
he preceding code generates the @ivide1yYero5Jce.tion.
he @ivide1yYero5Jce.tion is thrown when an integer value is divided by 2ero. In the
preceding code, when the program tries to e!ecute a division by the 2ero statement, it results in
a run-time error. he program has not been guarded for e!ceptionsR therefore the default
e!ception-handler is invo*ed. he default e!ception-handler displays the error message and
allows you to troubleshoot the problem. If you do not want to troubleshoot the problem then you
can terminate the program.
"# provides the structured solution to error-handling problems in the form of try and catch bloc*s.
Hsing these bloc*s the core program statements can be separated from the error-handling
statements. he core program statements handle normal program flow. )ou can also use the
finally bloc* to handle errors.
hese bloc*s for e!ception handling can be implemented using the following *eywords$
ry
"atch
(inally
he try 0loc*
he try bloc* guards statements that may throw an e!ception.
try
{
::Statements t(at may cause an eJce.tion
*
he try bloc* governs statements that are enclosed within it and defines the scope of the
e!ception-handlers associated with it. In other words, if an e!ception occurs within the try bloc*,
an appropriate e!ception-handler that is associated with the try bloc* handles the e!ception. ' try
bloc* must have atleast one catch bloc*.
he "atch 0loc*
)ou can associate an e!ception-handler with the try bloc* by providing one or more catch
handlers, immediately after the try bloc*.
try
{
::Statements t(at may cause an eJce.tion
*
catc(($$$$)
{
::error (andling code
*
he catch statement of the catch bloc* ta*es an object of the e!ception class as a parameter,
which refers to the raised e!ception. 3hen the e!ception is caught, the statements within the
catch bloc* are e!ecuted. he following code illustrates the use of a catch bloc*$
using System;
using System$8F;
names.ace AddL3ums
{
class Add3umbers
{
.ublic static void AddingL3umbers(int number1+ int number!L
{
try
{
int res = number1:number!;
#onsole$%rite&ine(res);
*
catc((@ivide1yYero5Jce.tion e) ::5Jce.tion =andler
{
#onsole$%rite&ine('5Jce.tion #aug(t$ {0*'+ e);
*
:: 7(is eJecutes after t(e catc( bloc2
#onsole$%rite&ine('After (andling t(e eJce.tion');
*
static void Main(string[] args)
{
Add3umbers$AddingL3umbers(10+0);
#onsole$,ead&ine();
*
*
*
he (inally 0loc*
he finally bloc* is used to e!ecute a given set of statements, whether an e!ception is thrown or
not thrown. (or e!ample, a file has to be closed whether an e!ception is raised or not. )ou can
place code to close the file in both the try and catch bloc*s$
try
{
::Statements t(at may cause an eJce.tion
*
catc(($$$$)
{
::error (andling code
*
finally
{
::statements to be eJecuted
*
he catch bloc* is used to handle e!ceptions that occur in a try bloc*. he finally bloc* is used to
guarantee the e!ecution of statements, regardless of whether an e!ception has occurred or not
occurred. )ou can have only one finally bloc* for each try bloc*. It is however not mandatory to
have a finally bloc* after a try bloc*.
"onsider the following code, which shows the use of the finally bloc*$
using System;
using System$8F;
names.ace AddL3ums
{
class Add3umbers
{
int result;
Add3umbers()
{
result = 0;
*
.ublic void @ivide(int number1+ int number!)
{
try
{
result = number1 : number!;
*
catc( (@ivide1yYero5Jce.tion e)
{
#onsole$%rite&ine('5Jce.tion #aug(t$ {0*'+ e);
*
finally
{
#onsole$%rite&ine(',esult is {0*'+ result);
*
#onsole$%rite&ine('After (andling t(e eJce.tion');
*
static void Main(string[] args)
{
Add3umbers @ivision = ne/ Add3umbers();
@ivision$@ivide(10$0);
#onsole$,ead&ine();
*
*
*
8f t(e .receding code is modified /it( t(e .ositive values @ivide(E+!)+
t(en t(e out.ut is)
,esult is !$
7(erefore code /ill not raise an eJce.tion$
Activity) =andling 5Jce.tion for Arrays 1eyond &imit
6roblem Statement
@avid is /or2ing on a .roDect /(ere (e is calculating t(e sum of values
in an integer array$ @avid needs to (andle t(e eJce.tions+ /(ic( can
occur /(ile (e is /or2ing /it( t(e arrays$ 8f any eJce.tional condition
is reac(ed /(en @avid is eJecuting t(e a..lication+ t(e a..lication
needs to dis.lay an eJce.tion message$
=el. @avid to (andle t(e eJce.tions$
Solution
o develop the re/uired application, ime needs to perform the following tas*s$
;. "reate a console based application
D. 0uild and e!ecution an application.
as* ;$ "reating a "onsole-0ased 'pplication
/* ,elect )tart All "rogra!s Microsoft 1isual )tudio 0445 Microsoft 1isual
)tudio 0445* he )tart "age C Microsoft 1isual )tudio window will be displayed
0* ,elect File 2e( "roject* he 2e( "roject dialog bo! will be displayed
6* ,elect the project type as 1isual C$ from the "roject types pane and Console
Application from the Te!plates pane.
7* ype the name of the new project as ArrayException in the 2a!e te!t bo!.
5* ,pecify the location where the new project is to be created as c-Dchapter>DActivity/ in
the ,ocation combo bo!.
3* "lic* the O' button.
8* Open the )olution Explorer window and right-clic* the "rogra!*cs file.
9* ,elect the Rena!e option and type the new name as ArrayOutof#ndex*cs
>* &ouble-clic* the ArrayOutof#ndex*cs file in the solution explorer window. he code
view of the ArrayOutof#ndex*cs file is displayed
/4* Geplace the e!isting code with the following code$
using System;
names.ace Array5Jce.tion
{
class ArrayFutFf8ndeJ
{
.ublic void #alculateSum()
{
int sum=0;
int [] number = ne/ int[4] {1+!+9+E+4);
try
{
for (int init = 1; init =4; init"")
{
sum = sum " number[init];
*
#onsole$%rite&ine('7(e sum of t(e array is) {0*'+
sum);
*
catc( (8ndeJFutFf,ange5Jce.tion e)
{
#onsole$%rite&ine(e$Message);
*
*
*
class #lassMain
{
static void Main(string[] args)
{
ArrayFutFf8ndeJ obD = ne/ ArrayFutFf8ndeJ();
obD$#alculateSum();
#onsole$,ead&ine();

*
*
*
as* D$ 0uilding and %!ecuting an 'pplication
o build and e!ecute the application perform the following steps$
7* 0uild the solution by pressing Ctlr G )hift Gb
5* ,elect ebug )tart ebugging or press F5 to e!ecute the application
3* Cerify the output of the application
Implementing the Hser-&efined %!ceptions
In "#, you can create your own e!ception class. ,ometimes you may want to catch an e!ception,
so some wor* to handle the e!ception, and then pass the e!ception on to the calling code. ,uch
*inds of e!ceptions are *nown as the user-defined e!ceptions. he %!ception must be base class
for all the e!ceptions in "#. he user-defined e!ception classes must follow the hierarchy of
either the e!ception class or of one of the standard inherited classes.
"reating the Hser-&efined %!ceptions
Hser-&efined e!ception classes are derived from the 'pplication%!ception class.
"onsider the following e!ample of user-defined e!ception named the "ountIsaero%!ception
e!ception$
using System;
names.ace Vser@efine5J
{
class #ountYero
{
static void Main(string[] args)
{
#alculator calc = ne/ #alculator();
try
{
calc$@oAverage();
*
catc( (#ount8sYero5Jce.tion e)
{
#onsole$%rite&ine('#ount8sYero5Jce.tion) {0*'+
e$Message);
*
#onsole$,ead&ine();
*
*
.ublic class #ount8sYero5Jce.tion ) A..lication5Jce.tion
{
.ublic #ount8sYero5Jce.tion(string message)
) base(message)
{
*
*
.ublic class #alculator
{
int sum = 0;
int count = 0;
float average;
.ublic void @oAverage()
{
if (count == 0)
t(ro/ (ne/ #ount8sYero5Jce.tion('Yero count in
@oAverage'));
else
average = sum : count;
*
*
*
o implement user-defined e!ceptions you need to raise your e!ception and throw an object.
Gaising your Own %!ceptions
)ou can use the throw statement to raise your own e!ceptions, as shown in the following code$
.ublic void @oAverage()
{
if (count == 0)
t(ro/ (ne/ #ount8sYero5Jce.tion('Yero count in
@oAverage'));
else
average = sum : count;
*
In the preceding e!ample, the throw statement is used to raise the user-defined e!ception,
"ountIsaero%!ception. If the value of count variable becomes 2ero while calculating the averageR
then the application raises the "ountIsaero%!ception e!ception to notify a user that the value of
the count variable is 2ero on the &o'verage() method.
Bost of the time, e!ceptions e!pect either an appropriate message string as an input or a
parameter when they are generated. he message can be displayed when the e!ception is
pic*ed.
+ote$
8e%er create and throw objects of class e1ception
hrowing objects
)ou can throw an object if the object is either directly or indirectly derived from ,ystem.%!ception.
)ou can use a throw statement in the catch bloc* to throw the present object, as shown in the
following code$
catc( (5Jce.tion caug(t)
{
$ $ $
t(ro/ caug(t
*
)ou can also throw a new e!ception of a different type, as shown in the following e!ample$
catc( (8F5Jce.tion caug(t)
{
$ $ $
t(ro/ ne/ -ile3ot-ound5Jce.tion(filename)
*
In the preceding e!ample, IO%!ception is used for trapping the file input-output e!ception. he
object of the IO%!ception class is used to store the information about the e!ception if it is raised.
his information is lost when the e!ception is converted into the (ile+ot(ound%!ception object. '
better way to handle the e!ception is add new information while *eeping the previous information,
as shown in the following code$
catc( (8F5Jce.tion caug(t)
{
$ $ $
t(ro/ ne/ -ile3ot-ound5Jce.tion(filename+ caug(t)
*
' throw without any e!pression can only be used in the catch bloc*. ,uch a throw reverts the
e!ception that is currently being handled. herefore, the following statement will generate
identical results$
catc( (FutFfMemory5Jce.tion caug(t) { t(ro/ caug(t;)
$ $ $
catc( (FutFfMemory5Jce.tion) { t(ro/;)
"ractice .uestions
;. he base class of all e!ceptions is MMMMMM
D. he set of statements that need to be e!ecuted whether an e!ception is thrown or not
thrown is included in the MMMMMM bloc*.
?. "an a try bloc* have more than one catch holder1
@. ,tate whether the following statement is true or false$
' try bloc* ensures that an e!ception is handled.
A. 'n attempt to divide by 2ero throws the MMMMM e!ception.
,ummary
In this chapter, you learned that$
'n e!ception is an erroneous situation that occurs during program e!ecution.
here are ? types of error that can occur in an application
o ,ynta! error
o Gun-time error
o 4ogical error
%!ception handling provides a structured and uniform way of handling system-level and
application-level errors.
%!ception handling is implemented using the following *eywords
o ry
o "atch
o finally
%!ception handling is the process of providing an alternative path to be e!ecuted when
an application is not able to e!ecute in a desired way
In addition to handling pre-defined e!ceptions, users can create their own e!ceptions by
deriving an e!ception class from the 'pplication%!ception clas.
)ou can only throw an object if the types of objects either directly or indirectly derives
from ,ystem.%!ception.
)ou can use the throw statement to raise your own e!ceptions.
%!ercises
%!ercise ;
&avid wants to create to tic*et boo*ing application for a movie theater. he application should as*
the user for his choice, whether he wants to boo* the tic*ets or not. he application should also
as* the user for the total number of tic*ets to be boo*ed. 3hile boo*ing the tic*ets if the total
number of boo*ed tic*ets e!ceeds the available tic*ets, the application should raise an e!ception.
:int$ he total number of available tic*ets is ten.
Chapter //
Creating Multithreaded Applications
' program e!ecutes as a single, se/uential flow of control. ' program can also be designed to
e!ecute multiple tas*s. o e!ecute multiple tas*s in your program, you can use threads.
his chapter discusses implementation of threads and their life cycle. he chapter also discusses
implementing multiple threads and prioriti2ing threads. In addition, this chapter discusses thread
synchroni2ation and communication between processes.
Objectives
In this chapter, you will learn to$
Implement threads
&efine the life cycle of a thread
Implement multiple threads
Identify the thread priority
Hse synchroni2ation in threads
Identify communication between processes
#!ple!enting Threads
' thread is defined as the e!ecution path of a program. )ou can define a uni/ue flow of a control
in a program, using a thread. hreads are used to run applications that perform large and
comple! computations.
(or e!ample, a "entral Processing Hnit ("PH) performs various comple! tas*s simultaneously.
he processes include tas*s such as writing and printing a document, installing software, and
displaying the date and time on the status bar. 'll these processes are handled by separate
threads.
' process that is e!ecuted using one thread is *nows as a single-threaded process, where the
process is running instance of a program. ' single-threaded application can perform only one tas*
at a time. )ou have to wait for one tas* to complete before another tas* can start. he following
figure shows a single-threaded process.
o e!ecute more than one tas* at a time, you can create multiple threads in a program. ' process
that creates two or more threads is called a multithreaded process. (or e!ample, any 3eb
browser, such as Internet %!plorer is a multithreaded application. 3ithin the browser, you can
print a page in the bac*ground while you scroll the page. ,imilarly, you can play audio files and
watch animated images at the same time. %ach thread in a multithreaded process runs at the
same time and maintains a different e!ecution flow.
he following figure shows a multithreaded process with two threads.
he hread Bodel
' program uses threads to increase the efficiency of a "PH by preventing wastage of the "PH
cycles. In the single-threaded systems, an approach called event loop with polling is used. Polling
is the process in which a single event is e!ecuted at a time. In the event loop with polling
approach, a single thread runs in an infinite loop till its operation is completed. 3hen the
operation is completed, the event loop dispatches control to the appropriate event handler. +o
more processing can happen in the system until the event-handler returns. his results in the
wastage of the "PH time.
In a single-threaded application, if the thread is suspended from e!ecution because it is waiting
for a system resource, the entire program stops e!ecuting. his limitation can be overcome by
using multithreading, which eliminates the event loop with polling approach. In multithreading, the
time for which a thread waits for the "PH time can be utili2ed to perform another tas*.
In "#, you will use the hread class to wor* with threads. he ,ystem.hreading.hread class is
used to construct and access individual threads in a multithreaded application. he first thread to
be e!ecuted in a process is called the main thread.
he Bain hread
1hread
1hread
1wo
1hreads
he main thread is created automatically on the start up of a "# program e!ecution. he threads
which are created e!clusively using the hread class are called as child threads, where the main
thread is either called a parent thread or a primary thread.
)ou can access a thread using the "urrenthread property of the hread class.
he following code shows the e!ecution of main thread using its "urrenthread property in the
hread class$
using System;
using System$7(reading;
names.ace 7(read5Jam.le
{
class Main7(read5Jam.le
{
.ublic static void Main(String[] args)
{
7(read 7( = 7(read$#urrent7(read;
7($3ame = 'Main7(read';
#onsole$%rite&ine('7(e current t(read after name c(ange is)
{0*'+ 7($3ame);
#onsole$,ead&ine();
*
*

*
In the preceding code, a reference to the current thread is obtained by using the "urrenthread
parameter of the hread class and its reference is stored in the h Cariable. he +ame parameter
is used to set the name of the thread, and the information about the thread is displayed.
3or*ing with hreads
In "#, you create a thread by creating an object of type hread, giving its constructor a
hread,tart reference, and calling the new thread.s ,tart() method. he new thread starts
e!ecuting asynchronously with an invocation of the thread.s method. 3hen the method returns,
the thread dies.
he other methods of the hread class allow managing the lifetime of the thread and destroying
the thread when re/uired.
here are various methods available with the hread class. Hsing these methods, you can control
the e!ecution of threads. (ew of these methods are$
)tart%& $ ,tarts a thread
)leep%&$ Ba*es the thread to pause for a period of time
Abort%&$ erminates the thread
)uspend%&$ ,uspends a thread. If the thread is already suspended it has no effect
Resu!e%&- Gesumes the suspended thread.
3or*ing with threads involves creating, managing, and destroying threads.
"reating hreads
)ou can create threads by e!tending the hread class. he e!tended hread class calls the
,tart() method to begin the child thread e!ecution. )ou can use the following code to create a
thread by e!tending the hread class$
using System;
using System$7(reading;
names.ace 7(readSam.le
{
class 1asic7(readA..
{
.ublic static void #(ild7(read#all()
{
#onsole$%rite&ine('#(ild 7(read Started');
*
.ublic static void Main()
{
7(readStart #(ild,ef = ne/ 7(readStart(#(ild7(read#all);
#onsole$%rite&ine('Main 0 #reating #(ild 7(read');
7(read #(ild7(read = ne/ 7(read(#(ild,ef);
#(ild7(read$Start();
#onsole$%rite&ine('Main 0 =ave reCuested t(e start of c(ild
t(read');
#onsole$,ead&ine();
*
*

*
In the preceding output, the Bain() method prints before the message from the child thread
proving that the child thread is indeed wor*ing asynchronously.
he first statement in the preceding code is the using statement for the ,ystem.hreading
namespace. he first statement of the Bain() method specifies the methid to be invo*ed by the
thread$
7(readStart #(ild,ef = ne/ 7(readStart(#(ild7(read#all);
he ne!t statement instantiates a hread object where the constructor ta*es the object of the
hread,tart class as its argument$
7(read #(ild7(read = ne/ 7(read(#(ild,ef);
hen the ,tart() method of the hread object is called, and the method results in a call to the
"hildhread"all method. he e!tended hread class calls the ,tart() method to begin the child
thread e!ecution.
Managing Threads
here are many tas*s you might want to perform to manage the activity or life of a thread. )ou
can manage all these tas*s by using the various thread methods available with the hread class.
(or e!ample, when you re/uire the thread to pause for a period of time so that the thread is
allowed to e!ecute, you can call the hread.,leep() method. his method ta*es a single
argument that represents time in milliseconds for which you want the thread to pause. his
method is static method and cannot be called with an instance of a thread object. his is done to
avoid a call to the hread.,leep() method on any other thread e!cept the currently e!ecuting
method.
he static hread.,leep() method calls the static "urrenthread method, which then pauses that
thread for the specified amount of time. he following code shows the implementation of the
,leep() method$
using System;
using System$7(reading;
names.ace 7(readSam.le
{
class 1asic7(readA..
{
.ublic static void #(ild7(read#all()
{
#onsole$%rite&ine('#(ild 7(read Started');
int slee.7ime = 4000;
#onsole$%rite&ine('Slee.ing for {0* seconds'+
slee.7ime:1000);
7(read$Slee.(slee.7ime); ::Slee. for 4 seconds
#onsole$%rite&ine('%a2ing u.');
*
.ublic static void Main()
{
7(readStart #(ild,ef = ne/ 7(readStart(#(ild7(read#all);
#onsole$%rite&ine('Main 0 #reating #(ild 7(read');
7(read #(ild7(read = ne/ 7(read(#(ild,ef);
#(ild7(read$Start();
#onsole$%rite&ine('Main 0 =ave reCuested t(e start of c(ild
t(read');
#onsole$,ead&ine();
*
*

*
here is more than one way to call the ,leep() method. One way is to call hread.,leep() with a
value E, which will cause the current thread to hand over the unused balance if its timeslice. he
other way is to call hread.,leep() method with a value of imeout.Infinite, which results in the
thread being paused indefinitely until it is interrupted by another thread called the suspended
thread.s hread.Interrupt() method.
here is another method hread.,uspend(), which is used to suspend the e!ecution of a thread.
he hread.,uspend() method can be called on a currently e!ecuting thread or another thread.
3hen a thread is suspended in this fashion, only another thread can cause its resumption, with
the hread.Gesume() method. +otice, when a thread suspends another thread, the first thread is
not bloc*ed. he call returns immediately.
In addition, regardless of how many times the hread.,uspend() method is called for a given
thread, a single call to hread.Gesume() will cause the thread to resume e!ecution.
&estroying hreads
If the thread is re/uired to be destroyed, the hread.'bort() method will allow you to accomplish
the tas*. he runtime aborts the thread by throwing a hread'bort%!ception. his e!ception
cannot be caught. If the finally bloc* is present in the method, the runtime will send the control to
it.
)ou can use the following code to destroy threads$
using System;
using System$7(reading;
names.ace 7(readSam.le
{
class 1asic7(readA..
{
.ublic static void #(ild7(read#all()
{
try
{
#onsole$%rite&ine('#(ild 7(read Started');
#onsole$%rite&ine('#(ild 7(read 0 counting to 10');
for (int i = 0; i 10; i"")
{
7(read$Slee.(400);
#onsole$%rite&ine('{0*$$$$'+ i);
*
#onsole$%rite&ine('#(ild 7(read finis(ed');
*
catc( (7(readAbort5Jce.tion e)
{
#onsole$%rite&ine('5Jce.tion'+ e$Message);
*
finally
{
#onsole$%rite&ine('#(ild t(read 0 Vnable to catc( t(e
eJce.tion');
*
*
.ublic static void Main()
{
7(readStart #(ild,ef = ne/ 7(readStart(#(ild7(read#all);
#onsole$%rite&ine('Main 0 #reating #(ild 7(read');
7(read #(ild7(read = ne/ 7(read(#(ild,ef);
#(ild7(read$Start();

:: Iive t(e c(ild t(read time to start
#onsole$%rite&ine('Main 0 Slee.ing for ! seconds');
7(read$Slee.(!000);
#onsole$%rite&ine('Main 0 Aborting c(ild t(read');
#(ild7(read$Abort();
#onsole$,ead&ine();
*
*

*
In the preceding code, the main() method pauses for D seconds to ma*e sure that the runtime
has had time to start the wor*er thread. 3hen started, the wor*er thread starts counting to ten,
pausing for a second in between each number. 3hen the main() method resumes e!ecution after
its D seconds pause, it aborts the wor*er thread. +otice the finally bloc* is e!ecuted after the
abort.
Implementing hread 4ife "ycle
he life cycle of a thread starts when an object of the ,ystem.hreading.hread class is created.
he life cycle of the thread ends with the tas* e!ecution. here are various states in the life cycle
of a thread. hese states are
he Hnstarted state
he Gunnable ,tate
he +ot Gunnable ,tate
he &ead ,tate
he following figure shows the various thread states and methods, which can cause the thread to
move form one state to another.
The :nstarted )tate
3hen an instance of the hread class is created, the thread enters the unstarted state.
' new thread is an empty object of the hread class, and no system resources such as memory
are allocated to it. )ou have to invo*e the ,tart() method to start the thread.
The Runnable )tate
' thread remains in the unstarted state until the program calls the ,tart() method of the hread
class, which places the thread in the runnable state and immediately returns control to the calling
Start( )
starte
d
Work Complete
Stop( )
Sleep( )
Suspend
suspen
d
Wait/Join
Sleep
Stop Reg
Stoppe
dd
Time Expires
Thread respnds to
stop request
Interrrupt ( )
Resume ( )
thread. his state is also called as the ready or started state. he newly started thread and any
other threads in the program e!ecute concurrently.
' single processor cannot e!ecute more than one thread at a time. herefore, it maintains a
thread /ueue. 3hen a thread is started, a thread is /ueued up for the processor time and waits
for its turn to get e!ecuted. 's a result, the state of the thread is said to be runnable and not
running.
The 2ot Runnable )tate
he thread is not the runnable state if it is$
)leeping- ' thread is put into the sleeping mode by calling the ,leep() method. '
sleeping thread enters the runnable state after the specified time of sleep has elapsed.
+aiting- ' thread can be made to wait for some specified condition to be satisfied by
calling the 3ait() method. he thread can be notified of the condition by invo*ing the
Pulse() method of the hread class.
Aloc@ed- ' thread could be bloc*ed by an IYO operation. 3hen the thread is bloc*ed, it
enters the not runnable state.
The ead )tate
' running thread enters the dead state when the statements of the threads methods are
complete. his state is called the terminated state. ' program can force a thread into the dead
state by calling the 'bort() method of the hread class on the appropriate thread object. he
'bort() method throws a hread'bort%!ception in the thread, normally causing the thread to
terminate. 3hen a thread is in the dead state and there are no references to the thread object,
the garbage collector can remove the thread object from memory.
'ctivity$ :angman 5ame
Problem ,tatement
he ne!t door children re/uest you to create the :angman 5ame for them. he game as*s the
user to enter a category as 0oo* or Bovie. 0ased on the category, a boo* name or movie name
is e!tracted and the user is as*ed to guess the name of the game by giving the character and its
position in a string. ' user will get IE seconds to play the game.
&evelop the :angman game application.
,olution
o solve the preceding problem, you need to perform the following tas*s$
;. Identify the data source where the name of the boo* or movie is stored.
D. "reate a console-based application for the :angman game
?. 0uild and e!ecute the application
as* ;$ Identify the data source where the name of the boo* or movie is stored
o demonstrate the implementation of the :angman game, you need to perform the following
steps$
/* Identify the data source. he data source from where data needs to be retrieved is
TextTest*txt*
0* ,ave the TextTest*txt in " drive.
as* D$ "reate a console-based application for the :angman game
o create a console based application for the :angman game, you need to perform the following
steps$
/* ,elect )tart All "rogra!s Microsoft 1isual )tudio 0445 Microsoft 1isual
)tudio 0445* he )tart "age C Microsoft 1isual )tudio window will be displayed
0* ,elect File 2e( "roject* he 2e( "roject dialog bo! will be displayed
6* ,elect the project type as 1isual C$ from the "roject types pane and Console
Application from the Te!plates pane.
7* ype the name of the new project as Fang!anApp in the 2a!e te!t bo!.
5* ,pecify the location where the new project is to be created as c-Dchapter//DActivity/ in
the ,ocation combo bo!.
3* "lic* the O' button.
8* Open the )olution Explorer window and right-clic* the "rogra!*cs file.
9* ,elect the Rena!e option and type the new name as Fang!an*cs
>* &ouble-clic* the Fang!an*cs file in the solution explorer window. he code view of
the Fang!an*cs file is displayed
/4* Geplace the e!isting code with the following code$
:> 6rogram to .lay =angman game$ 7(e .rogram as2s a user to enter
> a category as 1oo2:Movie$ 1ased on t(e category .rovided+ a boo2 name
or category
> name is eJtracted and t(e user is as2ed to guess t(e name by giving
> t(e c(aracter and its .osition$ >:
using System;
using System$8F;
using System$7(reading;
names.ace Iame
{
.ublic class =angman
{
string randomString+ userString;
int data&engt(;
string #ategory;
string[] boo2@ata = ne/ string[4];
string[] movie@ate = ne/ string[4];
int boo2#ount = 0+ movie#ount = 0;
.ublic =angman()
{
-ill3ameValues();
*
::Stores t(e movie names and 1oo2 names in res.ective strings
.rivate void -ill3ameValues()
{
:: @eclaring t(e variables
string first&ine;
::o.en file for reading
Stream,eader s,ead = ne/ Stream,eader('c)BB7est7eJt$tJt');
s,ead$1aseStream$See2(0+ See2Frigin$1egin);
::,eading t(e content of t(e file
first&ine = s,ead$,ead&ine();
/(ile (first&ine ?= null)
{
::Storing t(e 1oo2 names in t(e 1oo2data array
if (first&ine$Substring(0+ 1) == '1')
{
int stringStart6os = first&ine$8ndeJFf(;););
boo2@ata[boo2#ount] =
first&ine$Substring(stringStart6os " 1);
boo2#ount"";
*
::storing t(e Movie names in t(e Movie@ata array
else
{
int stringStart6os = first&ine$8ndeJFf(;););
movie@ate[movie#ount] =
first&ine$Substring(stringStart6os " 1);
movie#ount"";
*
first&ine = s,ead$,ead&ine();
*
*
.ublic int Acce.t#ategory()
{
::Acce.ting t(e c(oice of t(e user in terms of t(e category
#onsole$%rite&ine('5nter t(e #ategory to .lay 0
1oo2:Movie');
#ategory = #onsole$,ead&ine();
#ategory = #ategory$7oV..er();
if (#ategory ?= '1FFP' ZZ #ategory ?= 'MFV85')
{
#onsole$%rite&ine('8nvalid #ategory $$$$Bn');
return 0;
*
else
{
5Jtract3ame();
return 1;
*
*
.ublic void 5Jtract3ame()
{
::#reating t(e obDect of t(e ,andom class
,andom ,andIen = ne/ ,andom();
if (#ategory == '1FFP')
{
::,andomly selecting boo2 name from t(e array
int ,nd = ,andIen$3eJt(0+ boo2#ount 0 1);
::#alling t(e .lay met(od
randomString = boo2@ata[,nd];
*
else
{
::,andomly selecting Movue name from t(e array
int ,nd = ,andIen$3eJt(0+ movie#ount 0 1);
::#alling t(e .lay met(od
randomString = movie@ate[,nd];
*
*
:> 7(is met(od /ill allo/ t(e user to give t(e c(aracters and
> dis.laying (is status as to %F3 or lost >:
.ublic void StartIame()
{
::#alculating t(e lengt( of movie:boo2 name
data&engt( = randomString$&engt(;

::declaring variables
c(ar locate#(ar;
int correct#nt = 0+ in#orrect#nt = 0;
int i+ 2;
::@eclaring string to store user in.ut
c(ar[] s = ne/ c(ar[randomString$&engt(];
::&oo. to acce.t t(e c(aracters and its .ositions
::&oo. allo/s user to attem.t ! times more t(an t(e total
c(aracters
8nitialiKeVserString();
S(o/Vser8n.utString();
if (#ategory == '1FFP')
{
#onsole$%rite&ine('7(e total number of c(aracters in t(e
boo2 ) {0*'+ randomString$&engt();
#onsole$%rite&ine('7(e total number of c(aracters you
can enter to guess t(e name of t(e boo2) {0*'+ randomString$&engt( " !);
*
else
{
#onsole$%rite&ine('7(e total number of c(aracters in t(e
movie ) {0*'+ randomString$&engt();
#onsole$%rite&ine('7(e total number of c(aracters you
can enter to guess t(e name of t(e movie) {0*'+ randomString$&engt( "
!);
*
for (i = 1+ 2 = 0; i = data&engt( " ! WW 2 == data&engt(;
i"")
{
if (correct#nt == data&engt( WW in#orrect#nt ==
data&engt()
brea2;
#onsole$%rite&ine('5nter t(e c(ar');
locate#(ar =
#onvert$7o#(ar(#onsole$,ead&ine()$7o&o/er());
int found6os = 0;
int found#(ar = 0;
::7o eJtract eac( c(aracter of a string
foreac( (c(ar c in randomString)
{
if (c == locate#(ar)
{
V.dateString(found6os+ locate#(ar$7oString());
2"";
found#(ar = 1;
*
found6os"";
*
if (found#(ar == 0)
{
#onsole$%rite&ine('%rong Attem.t$$$1etter &uc2 3eJt
time Bn Bn');
in#orrect#nt"";
*
else
{
correct#nt"";
*
S(o/Vser8n.utString();
#onsole$%rite&ine('7otal #orrect Attem.ts ) {0*Bt'+
correct#nt);
#onsole$%rite&ine('7otal 8ncorrect Attem.ts) {0*Bt'+
in#orrect#nt);
if (2 == data&engt()
brea2;
*
if (randomString == userString)
{
#onsole$%rite&ine('Uou (ave %on Bn');
*
else
{
#onsole$%rite&ine('7(e correct name is {0*'+
randomString);
#onsole$%rite&ine('Uou (ave &ost Bn');
*
*
.ublic void V.dateString(int f6os+ string u.dateStr)
{
string beforeString+ afterString;
if (f6os ?= 0 ZZ f6os ?= data&engt( 0 1)
{
if (f6os == 1)
beforeString = userString$Substring(0+ 1);
else
beforeString = userString$Substring(0+ f6os);
afterString = userString$Substring(f6os " 1+ data&engt(
0 (f6os " 1));
userString = beforeString " u.dateStr " afterString;
*
if (f6os == 0)
{
afterString = userString$Substring(f6os " 1+ data&engt(
0 (f6os " 1));
userString = u.dateStr " afterString;
*
if (f6os == data&engt( 0 1)
{
beforeString = userString$Substring(0+ f6os);
userString = beforeString " u.dateStr;
*
*
.ublic void 8nitialiKeVserString()
{
userString = ' ';
for (int i = 0; i data&engt(; i"")
{
userString = userString$8nsert(i+ '>');
*
*
.ublic void S(o/Vser8n.utString()
{
#onsole$#lear();
#onsole$%rite&ine('8n.ut value) {0*'+ userString);
*
*
class Iame
{
static void Main(string[] args)
{
#onsole$#lear();
#onsole$%rite&ine('Uou (ave to com.lete t(e game /it(in G0
seconds');
=angman obD = ne/ =angman();
int returnVal = obD$Acce.t#ategory();
if (returnVal == 1)
{
::obD$StartIame();
7(read t = ne/ 7(read(ne/ 7(readStart(obD$StartIame());
7(read$Slee.(G0000); ::Ma2ing t(e main t(read slee. for
N0 seconds
try
{
t$Abort();
#onsole$%rite&ine('7ime Fver');
*
::Pilling t(e ne/ t(read
catc( (7(readAbort5Jce.tion e)
{
#onsole$%rite&ine(e$Message);
*
*
#onsole$,ead&ine();
*
*
*
as* ?$ 0uild and e!ecute the application
o build and e!ecute the application perform the following steps$
/* 0uild the solution by pressing Ctlr G )hift Gb
0* ,elect ebug )tart ebugging or press F5 to e!ecute the application
6* Cerify the output of the application
#!ple!enting Multithreading
Bultithreading helps to perform various operations simultaneously and saves time of a user. a
multithreaded program has a main thread and other user-defined threads to perform multiple
tas*s simultaneously.
he microprocessor allocates memory to the processes that you e!ecute. %ach process occupies
its own address space or memory. :owever, all the threads in a process occupy the same
address space. Bultithreading allows you to achieve multitas*ing in a program. Bultitas*ing is the
ability to e!ecute more than one tas* at the same time. Bultitas*ing can be divided into the
following categories$
"rocess-based Multitas@ing- his multitas*ing feature enables you switch from one
program to another so fast that it appears as if the programs are e!ecuting at the same
time. (or e!ample, process-based multitas*ing enables you to run the "# compiler and
use the te!t editor at the same time.
Thread-based Multitas@ing- ' single program can contain D or more threads and
therefore, perform two or more tas*s simultaneously. (or e!ample, a te!t editor can
perform writing to a file and print a document simultaneously with separate threads
performing the writing and printing actions. In the te!t-editor, you can format te!t in a
document and print the document at the same time. here are fewer overloads when the
processor switches from one thread to another. herefore, threads are called lightweight
processes. On the other hand, when the processor switches from one process to another
process the overload increases.
'dvantages and 4imitation of Bultithreading
his section list some of the advantages and limitations of multithreading.
he advantages of multithreading are$
#!proved "erfor!ance- Provides improvement in the performance of the processor by
simultaneous e!ecution of computation and the IYO operations.
Mini!iBed syste! resource usage- Binimi2e the use of system resources by using
threads, which share the same address space and belong to the same process.
)i!ultaneously access to !ultiple applications- Provides access to multiple
applications at the same time because of /uic* conte!t switching among threads.
"rogra! structure si!plification- ,implifies the structure of comple! applications, such
as multimedia applications. %ach activity can be written in separate methods that ma*es
comple! program easy to design and code.
4imitations of multithreading
he limitations of multithreading are$
Race condition- 3hen two or more threads simultaneously access a variable, at least
one thread tries to write a value in the variable. his is called the race condition, which is
caused by the lac* of synchroni2ation between two threads. (or e!ample, in a word
processor program, there are D threads, one to read from a file and the other to write to a
file. he thread to read a file waits for the thread to write before performing its operation.
he race condition arises when the thread to read a file, reads the file, before the thread
to write to a file performs its operation.
eadloc@ condition- his condition arises in a computer system when two threads wait
for each other to complete their operations before performing their individual action. 's a
result, the two threads become loc*ed and the program fails. (or e!ample, there are two
threads, hread' and hread0. hread' is waiting for a loc* to be released by hread0,
and hread0 is waiting for the loc* to be released by hread' to complete its transaction.
his state is a deadloc*.
,oc@ starvation$ his limitation arises when the e!ecution of a thread is postponed
because of its low priority. he .+% runtime environment e!e!utes threads based on
their priority because the processor can e!ecute only one thread at a time. he thread
with the higher priority is e!ecuted before the thread with a lower priority.
Creating Multiple Threads
)ou can create multiple threads in a program by e!tending the hread class. )ou can use the
following code to create two child threads other than the main thread$
using System;
using System$8F;
using System$7(reading;
class 7(readSc(edule
{
.ublic static void #(ild7(read1()
{
#onsole$%rite&ine('#(ild 7(read 1 started');
#onsole$%rite&ine('#(ild 7(read 0 counting from 1 to 10');
for (int 7 = 1; 7 11; 7"")
{
for (int #nt = 0; #nt 100; #nt"")
{
#onsole$%rite&ine('$');
::code to imitatte /or2 being done
*
#onsole$%rite&ine('{0*'+ 7);
*
#onsole$%rite&ine('#(ild 7(read 1 is finis(ed');
*
.ublic static void #(ild7(read!()
{
#onsole$%rite&ine('#(ild 7(read ! started');
#onsole$%rite&ine('#(ild 7(read 0 counting slo/ly from 11 to
!0');
for (int 7 = 11; 7 !0; 7"")
{
for (int #nt = 0; #nt 100; #nt"")
{
#onsole$%rite&ine('$');
::code to imitatte /or2 being done
*
#onsole$%rite&ine('{0*'+ 7);
*
#onsole$%rite&ine('#(ild 7(read ! is finis(ed');
*
.ublic static void Main()
{
7(readStart #(ild1 = ne/ 7(readStart(#(ild7(read1);
7(readStart #(ild! = ne/ 7(readStart(#(ild7(read!);
#onsole$%rite&ine('Main 0 #reating #(ild 7(reads');
7(read 7(read1 = ne/ 7(read(#(ild1);
7(read 7(read! = ne/ 7(read(#(ild!);
7(read1$Start();
7(read!$Start();
*
*
#dentifying the Thread "riority
One of the attributes that controls the behavior of a thread is it priority. he .+% Gun-time
enviromement e!e!utes threads based on their priority. Only one thread is e!ecuted by the "PH
at a time. herefore, the threads, which are at the runnable state for e!ecution, /ueue up for their
turn to get e!ecuted by the processor. he threads are fi!ed priority scheduled. %ach thread with
its priority has its position in the thread /ueue of the processor.
&efining hread Priority
hread priority is the property that specifies the priority of one thread with respect to the priority of
another thread. %!ecution of multiple threads is scheduled on a single processor in a specified
order. hread priority can be defined as$
'bove normal
0elow normal
:ighest
4owest
+ormal
' thread with higher priority runs before threads, which have lower priority. If "# encounters
another thread with higher priority, the current thread is pushed bac*R and the thread with the
higher priority is e!ecuted.
' .+% runtime system selects the runnable thread with the highest priority of e!ecution when a
number of threads get ready to e!ecute. he ne!t thread of lower priority starts e!ecuting if the
higher priority thread stops or becomes not runnable. ' thread is pushed bac* in the /ueue by
another thread if it is waiting from an IYO operation. ' thread can also be pushed bac* in the
/ueue when the time for which the sleep() method was called on another higher priority thread is
over.
,etting the hread priority
)ou can set the thread priority after it is created using priority property of the hread class. he
following synta! shows how to set the priority property$
7(read1$6riority = 7(read6riority$=ig(est;
In the preceding synta!, the 7(read6riority$=ig(est property specifies the new priority
setting for a thread. hreads are scheduled for e!ecution based on their priority. %ven though
threads are e!ecuting within run time, all threads are assigned processor time slices by the
operating system. he details of the scheduling algorithm used to determine the order in which
threads are e!ecuted varies with each operating system.
In multiple threads with the same priority are available, the scheduler cycles through the threads
in that priority, giving each thread a fi!ed time slice in which to e!ecute. 's long as a thread with a
higher priority is available to run, lower priority threads do not get to e!ecute. 3hen there are no
more runnable threads at a given priority, the scheduler moves to the ne!t lower priority and
schedules the threads at that priority for e!ecution.
)ou can use the following code, to set the priority of the child threads$
using System;
using System$8F;
using System$7(reading;
class 7(readSc(edule
{
.ublic static void #(ild7(read1()
{
#onsole$%rite&ine('#(ild 7(read 1 started');
#onsole$%rite&ine('#(ild 7(read 0 counting from 1 to 10');
for (int 7 = 1; 7 11; 7"")
{
for (int #nt = 0; #nt 100; #nt"")
{
#onsole$%rite&ine('$');
::code to imitatte /or2 being done
*
#onsole$%rite&ine('{0*'+ 7);
*
#onsole$%rite&ine('#(ild 7(read 1 is finis(ed');
*
.ublic static void #(ild7(read!()
{
#onsole$%rite&ine('#(ild 7(read ! started');
#onsole$%rite&ine('#(ild 7(read 0 counting slo/ly from 11 to
!0');
for (int 7 = 11; 7 !0; 7"")
{
for (int #nt = 0; #nt 100; #nt"")
{
#onsole$%rite&ine('$');
::code to imitatte /or2 being done
*
#onsole$%rite&ine('{0*'+ 7);
*
#onsole$%rite&ine('#(ild 7(read ! is finis(ed');
*
.ublic static void Main()
{
7(readStart #(ild1 = ne/ 7(readStart(#(ild7(read1);
7(readStart #(ild! = ne/ 7(readStart(#(ild7(read!);
#onsole$%rite&ine('Main 0 #reating #(ild 7(reads');
7(read 7(read1 = ne/ 7(read(#(ild1);
7(read 7(read! = ne/ 7(read(#(ild!);
7(read1$6riority = 7(read6riority$=ig(est;
7(read!$6riority = 7(read6riority$&o/est;
7(read1$Start();
7(read!$Start();

*
*
3hen a processor is informed about the priority of a thread, the operating system eventually uses
the information as a part of its scheduling algorithm. he processor then relays that information.
In .+%, this algorithm is based on the priority level used with the 7(read1$6riority property,
as well as the process. priority class in the preceding code.
:sing )ynchroniBation in Threads
In a multithreaded application, when threads need to share data with each other, the application
should ensure that one thread does not change the data used by the other thread. (or e!ample, if
you have two threads, one that reads your salary from a file and another thread that tries to
update the salary, data corruption might occur. "# enables you to coordinate the actions of
multiple threads by using synchroni2ed methods or synchroni2ed statements.
)ynchroniBing Threads
,ynchroni2ation of threads ensures that if two or more threads need to access a shared resource
then that resource is used by only one thread at a time. )ou can synchroni2e your code using the
synchroni2ed *eyword. )ou can invo*e only one synchroni2ed method for an object at any given
time.
,ynchroni2ation is based on the concept of monitoring. ' monitor is an object that is used as a
loc* to the data members and methods of a class. 'll objects and classes are associated with the
monitor and only one thread can own the monitor at a given time. o enter an object.s monitor,
you need to call a method that has been modified with the synchroni2ed *eyword.
he monitor controls the way in which synchroni2ed methods access an object or a class. 3hen
a thread ac/uires a loc*, it is said to have entered the monitor. he monitor ensures that only one
thread has access to the resources at any given time.
3hen a thread is within a synchroni2ed method, all the other threads that try to call it on the same
instance have to wait. &uring the e!ecution of a synchroni2ed method, the object is loc*ed so that
no other synchroni2ed method can be invo*ed. he monitor is automatically released when the
method completes its e!ecution. he monitor can also be released when the synchroni2ed
method e!ecutes the 3ait() method.
3hen a thread calls the 3ait() method, it temporarily releases the loc*s that it holds. In addition,
the thread stops running and is added to the list of waiting threads for that object.
he following figure shows how to synchroni2ation is maintained among threads.
2
created
runnin2
Enterin2 monitor
/unnin2
monitor
1aitin2 condition
Dead
0i2nalin2
Condition
Leavin2
monitor
1ait $%
0i2naled
!y other
thread
Leave
monitor
Leave monitor
terminate 0tart$ %
,oc@ing Code using the Monitor ,oc@s
he ,ystem.Bonitor enables you to sterli2e the access to bloc*s of code by means of loc*s and
signals. (or e!ample, you have a method that writes content to a file and the method cannot be
e!ecuted by two or more threads at the same time. If the wor* being performed by this method is
especially time-consuming and you have multiple threads, any of which might call this method,
you could have a serious problem on your hands. his is where the Bonitor class proves useful.
"onsider an e!ample on synchroni2ation. )ou have two threads, both of which will call the
3rite&ata() method. o incorporate the Bonitor class in this e!ample, you can use two of its static
methods. he first method is called %nter. 3hen e!ecuted, this method attempts to obtain a
monitor loc* on the object. If another thread already has the loc*, the method will bloc* until that
loc* has been released. he Bonitor.%!it() method is then called to release the loc*.
he following e!ample forces the seriali2ation of access to the 3rite&ata () method$
names.ace 7(read5Jam.le
{
class -ileAccess
{
.ublic void %rite@ata(string @ata)
{
Monitor$5nter(t(is);
#onsole$%rite&ine('-ileAccess$%rite@ata 0 Started');
#onsole$%rite&ine('-ileAccess$%rite@ata 0 %or2ing');
for (int #nt = 0; #nt 100; #nt"")
{
#onsole$%rite&ine(@ata);
*
#onsole$%rite&ine('-ileAccess$%rite@ata 0 5nded');
Monitor$5Jit(t(is);
*
*
class 7(readMonitor#lass
{
.ublic static -ileAccess -d = ne/ -ileAccess();
.ublic static void #(ild7(read1()
{
#onsole$%rite&ine('#(ild 7(read 1 started');
#onsole$%rite&ine('#(ild 7(read 1 #alling
-ileAccess$%rite@ata');
-d$%rite@ata('71');
#onsole$%rite&ine('#(ild 7(read 1 0 ,eturned from out.ut');
*
.ublic static void #(ild7(read!()
{
#onsole$%rite&ine('#(ild 7(read 1 started');
#onsole$%rite&ine('#(ild 7(read 1 #alling
-ileAccess$%rite@ata');
-d$%rite@ata('71');
#onsole$%rite&ine('#(ild 7(read 1 0 ,eturned from out.ut');
*
.ublic static void Main()
{
7(readStart #(ild1 = ne/ 7(readStart(#(ild7(read1);
7(readStart #(ild! = ne/ 7(readStart(#(ild7(read!);
#onsole$%rite&ine('Main 0 #reating #(ild 7(reads');
7(read 7(read1 = ne/ 7(read(#(ild1);
7(read 7(read! = ne/ 7(read(#(ild!);
7(read1$Start();
7(read!$Start();
#onsole$,ead&ine();

*
*
*
Hsing Bonitor 4oc*s with the "# 4oc* ,tatement
he other way to loc* code is by using the "# loc* statement. 'lthough the "# loc* statement
does not support the full array of features found in the Bonitor class, it enables you to obtain and
release a monitor loc*. o use the loc* statement, simply specify the loc* statement with the code
being seriali2ed in braces. he braces indicate the starting and stopping point of code being
protected. herefore, there is no need for an unloc* statement.
he following code will produce a synchroni2ed output that is similar to the output of the
preceding code$
using System;
using System$8F;
using System$7(reading;
names.ace 7(read5Jam.le
{
class -ileAccess
{
.ublic void %rite@ata(string @ata)
{
loc2 (t(is)
{
#onsole$%rite&ine('-ileAccess$%rite@ata 0 Started');
#onsole$%rite&ine('-ileAccess$%rite@ata 0 %or2ing');
for (int #nt = 0; #nt 100; #nt"")
{
#onsole$%rite&ine(@ata);
*
#onsole$%rite&ine('-ileAccess$%rite@ata 0 5nded');
*
*
*
class 7(readMonitor#lass
{
.ublic static -ileAccess -d = ne/ -ileAccess();
.ublic static void #(ild7(read1()
{
#onsole$%rite&ine('#(ild 7(read 1 started');
#onsole$%rite&ine('#(ild 7(read 1 #alling
-ileAccess$%rite@ata');
-d$%rite@ata('71');
#onsole$%rite&ine('#(ild 7(read 1 0 ,eturned from out.ut');
*
.ublic static void #(ild7(read!()
{
#onsole$%rite&ine('#(ild 7(read ! started');
#onsole$%rite&ine('#(ild 7(read ! #alling
-ileAccess$%rite@ata');
-d$%rite@ata('71');
#onsole$%rite&ine('#(ild 7(read ! 0 ,eturned from out.ut');
*
.ublic static void Main()
{
7(readStart #(ild1 = ne/ 7(readStart(#(ild7(read1);
7(readStart #(ild! = ne/ 7(readStart(#(ild7(read!);
#onsole$%rite&ine('Main 0 #reating #(ild 7(reads');
7(read 7(read1 = ne/ 7(read(#(ild1);
7(read 7(read! = ne/ 7(read(#(ild!);
7(read1$Start();
7(read!$Start();
#onsole$,ead&ine();

*
*
*
#dentifying Co!!unication Aet(een "rocesses
' process is a running instance of a program. he communication between the processes at run
time wihtin the same computer or over a networ* is called the interprocess communication. o
allow the interprocess communication, special techni/ues and mechanisms are used.
"onsider an e!ample. Imagine you are typing a document. )ou use your fingers to type1 )our
brain wor*s while you are typing the document. )our brain directs one of your fingers to hit a *ey
while the other finger hits another *ey. )our brain synchroni2es typing with both your hands. It
directs you to type the letters of a word that come to your mind. he wor*ing of your brain is an
e!ample of interprocess communication within human body.
0ased on this e!ample, you can conclude that a medium is re/uired for communication between
various processes. ,imilarly, computer programs need some mechanism for communication.
Processes can use the available memory of the system to communicate with each other, but
memory is completely managed by the operating system.
' process will be allotted some part of the available memory for e!ecution by the operating
system. %ach process will e!ecute in its own uni/ue user space. he operating system will not
allow the memory alloted for one process to overlap with the memory allotted for another process.
o allow communication between various processes with a uni/ue address space, the operating
system.s *ernel acts as the communication channel.
Application o!ain
3henever you start an application in O, such as 3indows KP, the system starts a 3in?D
process and e!ecutes your application. hese processes use resource such as memory, objects,
and *ernel. %ach 3in?D process contains at the least one thread. If you were to run other tas*s
or open up other applications through your application, those tas*s will belong to the 3in?D
process running on a collection of multiple threads.
,o when an application is run, a new application domain is created. ,everal instantiations of an
application can e!ist on the same machine at a given time, and each has its own application
domain. 'n application domain enables application isolation by acting as a container for
application state.
In .+%, threads e!ecute in an application domain. ' thread in one process cannot invo*e a
method in a thread that belongs to another process. In .+%, however, threads can cross the
application domain boundaries, and a method in one thread can call a method in another
application domain. he application domain is a logical process inside a physical process.
he e!ecution of a process and running your code within it is usually the domain and choice of
the operating system. here are many comple! situations and issues that the operating system
has to handle while maintaining an active process. he following figure shows various application
domains interacting with each other.
he main purpose of the application domain is to isolate your applications from the other
applications. 'pplication domains run on a single process.
herefore, you run an application within an application domain and you run multiple application
domains within a single process. 3ith the .+% "4G.s ability to run a managed code, you can
further prevent memory lea*s and crashes. Objects in the same application domain
communication directly, while objects that e!ists in different application domains interact with
each other by transporting copies of the objects to each other.
Appomain A
!"#e$t %
Appomain &
!"#e$t '
Process 1 Process 2
Operation System Environment
)ou use the ,ystem.'pp&omain class to manage application domains. he 'pp&omain class
implements a set of events that enable applications to respond when an assembly is loaded,
when an application domain will be unloaded, or when an unhandled e!ception is thrown.
"ractice .uestions
;. 3hich of the following is true about the -not runnable. state of a thread1
a) ' sleeping thread enters that -not-runnable. state when the specified time has
elapsed
b) ' thread is in a -not-runnable. state if it is dead
c) 3hen the start() method is invo*ed, the thread enters the -not-runnable. state.
d) 3hen the thread is bloc*ed by another thread, it enters the -not-runnable. state.
D. )ou need to create a spreadsheet application with automatic recalculation facility. 3hich
of the following statements isYare true with respect to the re/uired application1
'. he application should be multithreaded
0. ' thread object has to be created for performing automatic
recalculation
". he thread ta*ing care of automatic recalculation should have the
highest priority.
b) ' only
c) ', 0 U "
d) 0 U "
e) ' U 0
?. 3hich class is used to construct and access individual threads in a multithreaded
application1
a) System$7(read
b) System$7(reading
c) System$ 7(read $7(reading
d) System$7(reading$7(read
@. )ou are creating an application, using the concept of multithreading, in which you can pla
audio files and watch animated images at the same time. 3hich of the following methods
should be invo*ed for a thread to enter the runnable state1
a) Start()
b) Slee.()
c) ,un()
d) ,esume()
A. )ou are developing a multithreaded application. 3hich of the following will you use to
ma*e a thread, animhread, enter the non-runnable state1
a) 7(read anim7(read = ne/ 7(read(t(is);
b) anim7(read$Slee.(!000);
c) anim7(read$,esume();
d) anim7(read$Start();
,ummary
In this chapter, you learned that$
' thread is defined as the path of e!ecution of a program. It is se/uence of instructions
that is e!ecuted to define a uni/ue flow of control.
' program that creates two or more threads is called a multithreaded program.
he types of multitas*ing are$
o Process-based multitas*ing
o hread-based multitas*ing
he advantage of multithreading are$
o Improved performance
o Binimi2ed system resources usage
o ,imultaneous access to multiple application
he various disadvantages of multithreading are$
o Gace condition
o &eadloc* condition
o 4oc* starvation
he ,ystem.hreading class is used to construct and access individual threads in a
multithreaded application.
he various states in the life cycle of a thread are$
o Hnstarted state
o Gunnable state
o +ot Gunnable state
o &ead ,tate
hread priority is the property that specifies the priority of one thread with respect to the
priority of another thread.
,ynchroni2ation of threads ensures that if two or more threads need to access a shared
resource then that resource is used by only one thread at a time.
he System$Monitor class enables you to seriali2e the access to bloc*s of code by
means of loc*s and signals
he communication between processes at runtime within the same computer or over a
networ* is called inter-process communication.
he application domain is a logical process inside a physical process. he main purpose
of the application domain is to isolate your applications from the other applications.
%!ercises
%!ercise ;
3rite an application to simulate the vehicles crossing a toll bridge on a motorway. (or the
purpose of this e!ercise, simulate the environment for five vehicles that are approaching the
bridge and the toll booth. he vehicles are numbered from one to five. he vehicles should
approach the bridge and the toll booth in se/uential order. he toll booth can only deal with one
vehicle at a time. he simulation is performed by having one thread for each vehicle, and consists
of three classes.
Cehicle$ ,imulate the behavior of a vehicle
ollbooth$ ,imulate the behavior of a ollbooth
,imulate$ "reates the vehicle and controls the simulation
Chapter /0
elegates and Events
"lasses are reference types that allow you to create instances of objects and use them in special
ways to meet your application.s re/uirement. 'nother reference type in "# is delegate. &elegates
allow you to change the reference to a method at runtime. his means that you can decide the
e!ecution of a method at runtime, based on the re/uirements of your application.
he method can be activated at the occurrence of an event, where an event is associated with
the delegate to call the method at runtime.
his chapter discusses the creation of delegates. his chapter also discusses how to implement
multicast delegates. In addition, it discusses how you can use events with delegates.
Objectives
In this chapter, you will learn to$
Implement delegates
Implement multicast delegates
Hse events with delegates
#ntroducing elegates
&elegates in "# allow you to dynamically change the reference to the methods in a class.
"onsider an e!ample of a coffee vending machine, which dispenses different flavors of coffee,
such as cappuccino and blac* coffee. On selecting the desired flavor of coffee, the vending
machine decides to dispense the ingredients, such as mil* powder, coffee powder, hot water,
cappuccino coffee powder. 'll the materials are placed in different containers inside the vending
machine. he re/uired material is dispensed when you select a flavor.
,uppose, you select blac* coffee, the vending machine will call methods to dispense hot water
and coffee powder only. he reference to these methods is made dynamically, when you press
the re/uired button to dispense blac* coffee.
' delegate is a reference type variable, which holds the reference to a method. his reference
can be changed at runtime, as desired. 'lthough, delegates are a general-purpose mechanism
for indirectly calling methods at runtime, their primary use in "# programming is for implementing
events and the call-bac* methods.
o implement delegates in your application you need to declare delegates, instantiate delegates
and use delegates.
&eclaring &elegates
he methods that can be referenced by a delegate are determined by the delegate declaration.
he delegate can refer to the methods, which have the same signature as that of the delegate.
"onsider the following e!ample of delegate declaration$
.ublic delegate void My@elegate(string s);
In the preceding e!ample, the declared delegate type can be used to reference any method. his
method should have a single parameter of string type and it does not return any value.
he following synta! is used for delegate declaration$
delegate return ty.eTdelegate0names.aceT6arameter listT
#nstantiating elegates
"reate the delegate object of the delegate type, which you have already created. 'ssign the
address of the re/uired method to the delegate object. his can be done by calling the
constructor of the delegate class and passing the method name. the following e!ample shows
how to assign the address of a method to a delegate variable$
.ublic void @elegate-unction(string 6assValue)
{
::Met(od 8m.lementation (ere
*
::@elegate @eclaration
.ublic delegate void My@elegate(string ArgValue);
.ublic void VseMet(od()
{
::@elegate 8nstantiation
My@elegate @elegateFbDect = ne/
My@elegate(@elegate-unction);
*
In the preceding e!ample, the signature and the return type of &elegate(unction matches with
the delegate declaration of the By&elegate delegate, the By&elegate delegate can hold the
address of @elegate-unction is assigned to the @elegateFbDect by passing, the name of
the function to the delegate constructor.
Hsing &elegate
)ou can call the delegate by giving the name of the delegate and by passing parameters, if
re/uired. Hsing delegates is similar to calling methods.
"onsider a situation where you need to print information to a file and a screen. here is some
common information that needs to go to the file and to the screen. here is also some specific
information for both. he methods to print the information to the file and screen are different. )ou
can call these methods at runtime by passing the common information.
he following e!ample shows how to use a delegate$
::7(is code is to .rint data to t(e out.ut device+ /(ic( is eit(er a
file or a screen
using System;
using System$8F;
::6rogram to /rite t(e data to t(e console and file
names.ace #(a.ter1!5J1
{
.ublic class 6rint7o@evice
{
::#reating t(e variables of Stream classes
static -ileStream -stream;
static Stream%riter S%riter;
::@efining a delegate
.ublic delegate void 6rint@ata(string s);
::Met(od to .rint a string to t(e console
.ublic static void %rite#onsole(string str)
{
#onsole$%rite&ine('{0* #onsole'+str);
*
::Met(od to .rint a string to a file
.ublic static void %rite-ile(string s)
{
::8nitialiKing stream obDects
-stream = ne/ -ileStream('#)BBStore@ata$tJt'+
-ileMode$A..end+ -ileAccess$%rite);
S%riter = ne/ Stream%riter(-stream);
s = s " '-ile';
::%riting string to t(e file
S%riter$%rite&ine(s);
::removing t(e content from t(e buffer
S%riter$-lus(();
S%riter$#lose();
-stream$#lose();
*
::Met(od to send t(e string data to res.ective met(ods
.ublic static void @is.lay@ata(6rint@ata 6Met(od)
{
6Met(od('7(is s(ould go to t(e ')'
*
.ublic static void Main()
{
::8nitialiKing t(e @elegate FbDect
6rint@ata #n =ne/ 6rint@ata(%rite#onsole);
6rint@ata -l = ne/ 6rint@ata(%rite-ile);
::8nvo2ing t(e @is.lay@ata met(od /it( t(e delegate obDect
as t(e argument
::Vsing t(e delegate
@is.lay@ata(#n);
@is.lay@ata(-l);
#onsole$,ead&ine();
*
*
*
In the preceding e!ample, the %rite#onsole () and %rite-ile () methods are used to write
the information to the screen and to the file. he delegate variable 6rint@ata is used to refer to
the %rite#onsole () and %rite-ile () methods.
&elegates are of two types and depending upon the re/uirement of the application the similar
type of delegate is selected.
ypes of &elegates
here are two types of delegates, ,ingle-cast delegate and Bulticast delegate. ' ,ingle-cast
delegate can call only one method at a time, whereas a Bulticast delegate can call multiple
methods at the same time.
,ingle-"ast &elegate
' single-cast delegate derives from the System$@elegate class. It contains reference to one
method only at a time. In the preceding e!ample, the delegate used is a single-cast delegate. he
%rite#onsole () and %rite-ile () methods are being referenced by the delegate,
6rint@ata, one after the other, at runtime.
"onsider the coffee vending machine e!ample. o provide blac* coffee a delegate that holds the
reference to the methods to dispense hot water and coffee powder is used. he reference to
these methods is made dynamically, but one after the other. his means coffee powder and hot
water will be dispensed from the machine serially.
Bulticast &elegate
' multicast delegate derives from the System$@elegate class. It contains an invocation list of
multiple methods. In multicasting you create a single delegate that invo*es multiple encapsulated
methods. )ou need to ensure the return type of all these delegates is same.
"onsider the coffee vending machine e!ample. )ou are dispensing blac* coffee, which in turn
calls the methods to dispense hot water and coffee powder. If you want the methods to dispense
hot water and coffee powder to be called at the same time, you can ma*e use of a multicast
delegate.
Bulticast delegates hold the reference of more than one method thereof, if you call a multicast
delegate it will e!ecute all the methods it wraps in the calling order. he multiple methods called
by the delegate in this case should not return any value because several multicast delegates are
called consecutively and you cannot wait to get the return value from each of these methods.
"onsider the preceding e!ample of printing a message to a file and to a screen in which the
%rite#onsole () and %rite-ile () methods are called by using a single-cast delegate. his
e!ample considers a situation where all the methods are called at the same instance. Hsing the
same delegate, multicasting helps to call both the %rite-ile () method and the %rite#onsole
() method in one call.
he following code shows how to use a multicast delegate$
::7(is code is to .rint data to t(e out.ut device+ /(ic( is eit(er a
file or a screen
using System;
using System$8F;
::6rogram to /rite t(e data to t(e console and file
names.ace #(a.ter1!5J1
{
.ublic class 6rint7o@evice
{
::#reating t(e variables of Stream classes
static -ileStream -stream;
static Stream%riter S%riter;
::@efining a delegate
.ublic delegate void 6rint@ata(string s);
::Met(od to .rint a string to t(e console
.ublic static void %rite#onsole(string str)
{
#onsole$%rite&ine('{0* #onsole'+ str);
*
::Met(od to .rint a string to a file
.ublic static void %rite-ile(string s)
{
::8nitialiKing stream obDects
-stream = ne/ -ileStream('#)BBStore@ata$tJt'+
-ileMode$A..end+ -ileAccess$%rite);
S%riter = ne/ Stream%riter(-stream);
s = s " '-ile';
::%riting string to t(e file
S%riter$%rite&ine(s);
::removing t(e content from t(e buffer
S%riter$-lus(();
S%riter$#lose();
-stream$#lose();
*
::Met(od to send t(e string data to res.ective met(ods
.ublic static void @is.lay@ata(6rint@ata 6Met(od)
{
6Met(od('7(is s(ould go to t(e ');
*
.ublic static void Main()
{
::8nitialiKing t(e @elegate FbDect
6rint@ata M8@elegate = ne/ 6rint@ata(%rite#onsole);
M8@elegate "= ne/ 6rint@ata(%rite-ile);
@is.lay@ata(M8@elegate);
M8@elegate 0= ne/ 6rint@ata(%rite-ile);
@is.lay@ata(M8@elegate);
#onsole$,ead&ine();
*
*
*
In the preceding e!ample, the multicast delegate, M8@elegate holds reference of both the
%rite#onsole () and %rite-ile () methods.
Fust a Binute
State whether the following state&ent is 2r!e or "alse:
*!lticast delegates inherit fro& the System$@elegate$Multicast@elegate class.
'nswer$
"alse.
3or*ing with %vents
'n event is an action or occurrence, such as clic*s, *ey presses, mouse movements, or system
generated notifications. 'pplications can respond to events when they occur. 'n e!ample of a
notification is interrupts. %vents are messages sent by the object to indicate the occurrence of the
event. %vents are an effective mean of inter-process communication. hey are useful for an
object because they provide signal state changes, which may be valuable to a client of the object.
"onsider an e!ample of an event and the response to the event. ' cloc* is an object that shows I
'B time and generates an event in the form of an alarm. )ou accept the alarm event and act
accordingly.
he following figure shows the alarm event and handling of an event.
he following figure is the generali2ed representation that e!plains events and event handling
In "#, delegates are used with events to implement event handling. he .+% (ramewor* event
model uses delegates to bind event notifications with methods *nown as event handlers. 3hen
an event is generated, the delegate calls the associated event handler.
Cloc3 shows time4
Time is &#
&larm plays a sound5 notifyin2
everyone that is &#
6ou hear the alarm
6ou 2et up and 2et ready for your
school
&n event occurs in an o!7ect
'!7ect notifies everyone that the
event has occurred
0omeone listens for the event
0omeone acts upon it
Hsing delegates with %vents
he events are declared and raised in a class and associated with the event handlers using
delegates within the same class or other classes. %vents are part of a class and the same class is
used to publish its events. he other classes can, however, accept these events or in other words
can subscribe to these events. %vents use the publisher and subscriber model.
' publisher is an object that contains the definition of the event and the delegate. he association
of the event with the delegate is also specified in the publisher class. he object of the publisher
class invo*es the event, which is notified to the other objects. ' subscriber is an object that wants
to accept the event and provide a handler to the event. he delegate of the publisher class
invo*es the method of the subscriber class. his method in the subscriber class is the event
handler. he publisher and subscriber model implementation can be defined by the same class.
he following figure shows the mechanism used by the publisher and subscriber object.
he implementation of an event includes events definition, events subscription and events
notification.
&efining an %vent
he definition of the event in a publisher class includes the declaration of the delegate as well as
the declaration of the event based on the delegate. the following code defines a delegate named
imeoGaise and an event named Ging'larm, which invo*es the imeoGaise delegate when it is
raised$
Declare a dele2ate
Declare an Event !ased
on the dele2ate
Fire the Event
0u!scri!ed Event
Event 8andler
Fires the event
handler
0u!scri!er
0u!scri!ed Event
Event 8andler
Fires the event
handler
0u!scri!er
9u!lisher
.ublic delegate void 7ime7o,aise();
.ublic event 7ime7o,aise ,ingAlarm;
,ubscribing to an %vent
he event of the publisher class needs to be associated with its handler. he event handler
method is associated with the event using the delegate. when the publisher object raises the
event, the subscribing object associates the method, which needs to be called.
"onsider the class named ,tudent which contains a method named 3a*eHp(). he re/uirement
states that the method 3a*eHp() should be called at I '.B. he re/uirement could be
implemented using events. he following code shows how the ,tudent class subscribes to the
event named imeoGaise$
Student 6@ = ne/ Student();
,ingAlarm = ne/ 7ime7o,aise(6@$%a2eV.);
+ote$
2he delegates that s!bscribe to an e%ent &!st be declared %oid.
2otifying )ubscribers to an Event
he subscriber object notifies the subscriber object to the publisher object. he event is raised to
notify the handler.
In the Ging'larm e!ample, you do not re/uire the %a2eV. () method to be e!ecuted through the
delegate because the event ta*es care of e!ecution. 3rite this bloc* of code at a place from
where you want to notify the event to the subscribers of the event$
if (,ingAlarm ?= null)
{
,ingAlarm();
*
he preceding code bloc* invo*es all the associated delegates. In this e!ample, the %a2eV. ()
method that subscribes to the event is activated. +otice, code chec*s if the event has at least one
subscribing delegate. without this chec*, code throws an e!ception if there are no subscribers.
"assing Event "ara!eters
he methods that subscribe an event might e!pect some input to be passed. he event class can
have these inputs at runtime on which the subscribing method wor*s. )ou need to define the
class that will pass the input to the event.
&erive this class from System$5ventArgs. o pass values to a subscribing method, you need
to enclose the parameters in a single class. he single class supplies a special method called the
accessor method to retrieve the value. his method is used to e!amine and modify the members
of a class. Cariables declared private are accessed indirectly through these methods.
In the preceding Ging'larm e!ample, the 3a*eHp() method needs to get information about time
so that it can wor*. herefore, you create the class to pass the information about time to the
subscriber through the event.
he following code passes the information about time to the subscriber through the event$
.ublic class 7ime8nfo5ventArgs ) 5ventArgs
{
.rivate int =our;
.rivate int Minute;
.rivate int Second;
.ublic 7ime8nfo5ventArgs(int =our+ int Minute+ int Second)
{
t(is$=our = =our;
t(is$Minute = Minute;
t(is$Second = Second;
*
.ublic int Iet=our
{
return =our;
*
.ublic int IetMinute
{
return Minute;
*
.ublic int IetSecond
{
return Second;
*
*
he 7ime8nfo5ventArgs class is the event class that will pass the value of hour, minute and
second. he class declares three accessor methods$ Iet=our , IetMinute and IetSecond$
'ctivity $ 'ttendence 4og
Problem ,tatement
In an air-conditioner manufacturing company, the wor*ing time is from = 'B and IPB. he
management of the company is fle!ible and it allows wor*ers to arrive to wor* late by ; hour. he
entry time of wor*ers is recorded electronically in a log file when they enter the premises of the
company. he application used for recording the attendance of each wor*er needs to log the
appropriate information.
:elp the company to design an application for logging attendance.
,olution
o design the application, you need to perform the following tas*s$
;. Identify the techni/ue that you will use in the application. his techni/ue will allow you to
call the respective methods dynamically to log the attendance entry.
D. "reate a console-based application to implement the attendance log of wor*ers
?. "ompile and e!ecute the application.
as* ;$ Identify the techni/ue that you will use in the application. his techni/ue will allow you to
call the respective methods dynamically to log the attendance entry.
o demonstrate the wor*ing of the 'ttendance 4og %ntry application, various methods are
re/uired to be called dynamically. )ou can use a delegate to call methods dynamically. )ou need
to *eep in mind that in the future the company may start new shifts. he attendance entry can be
treated as an event. hat event delegates attendance logging of wor*ers to methods.
as* D$ "reating a console-based application
o create a console based application for the :angman game, you need to perform the following
steps$
/* ,elect )tart All "rogra!s Microsoft 1isual )tudio 0445 Microsoft 1isual
)tudio 0445* he )tart "age C Microsoft 1isual )tudio window will be displayed
0* ,elect File 2e( "roject* he 2e( "roject dialog bo! will be displayed
6* ,elect the project type as 1isual C$ from the "roject types pane and Console
Application from the Te!plates pane.
7* ype the name of the new project as AttendanceApp in the 2a!e te!t bo!.
5* ,pecify the location where the new project is to be created as c-Dchapter/0DActivity/ in
the ,ocation combo bo!.
3* "lic* the O' button.
8* Open the )olution Explorer window and right-clic* the "rogra!*cs file.
9* ,elect the Rena!e option and type the new name as elegateEvent*cs
>* &ouble-clic* the elegateEvent*cs file in the solution explorer window. he code view
of the elegateEvent*cs file is displayed
/4* Geplace the e!isting code with the following code$
using System;
using System$8F;
names.ace AttendanceA..
{
::5vent 6ublis(er
.ublic class @elegate5vent
{
::@efine a delegate named Attendance&og=andler+ /(ic( /ill
::enca.sulate
::any met(od t(at ta2es a string as t(e .arameter and
::returns no value
.ublic delegate void Attendance&og=andler(string Message);
::@efine an 5vent based on t(e above delegate
.ublic event Attendance&og=andler 5vent&og;
::8nstead of (aving t(e &og6rocess() function ta2e a
::delegate
::as a .arameter+ /e;ve declared a 5vent&og event$
.ublic void &og6rocess()
{
string ,eason = null;
#onsole$%rite&ine('5nter your name');
string Vser3ame = #onsole$,ead&ine();
@ate7ime t = @ate7ime$3o/;
int (r = t$=our;
int m = t$Minute;
if (?((r T=N ZZ (r 10 WW ((r == 10 ZZ m == 0 )))
{
#onsole$%rite&ine('5nter t(e reason for not coming
/it(in t(e valid time)');
,eason = #onsole$,ead&ine();
*
Fn5vent&og('&ogging into 8nfo) ' " Vser3ame);
if ((r T= N ZZ (r 10 WW ((r == 10 ZZ m == 0))
if (m10)
Fn5vent&og('&ogged in at ' "(r$7oString() " ')0'
"m$7oString() " '%it(in 7ime');
else
Fn5vent&og('&ogged in at ' "(r$7oString() " ')'
"m$7oString() " '%it(in 7ime');
else
if (m10)
Fn5vent&og('&ogged in at ' "(r$7oString() " ')0'
"m$7oString() " '3ot %it(in 7ime because' ",eason);
else
Fn5vent&og('&ogged in at ' "(r$7oString() " ')'
"m$7oString() " '3ot %it(in 7ime because' ",eason);
Fn5vent&og(' ');
*
:: 1y default+ create an FnYYYY met(od+ to call t(e 5vent
.rotected void Fn5vent&og(string Message)
{
if (5vent&og ?= null)
{
5vent&og(Message);
*
*
*
::7(e Attendance&ogger class merely enca.sulates te( file 8:F
.ublic class Attendance&ogger
{
-ileStream -ileStr;
Stream%riter Stream%tr;
::#onstructor
.ublic Attendance&ogger(string -ile3ame)
{
-ileStr = ne/ -ileStream(-ile3ame+ -ileMode$A..end+
-ileAccess$%rite);
Stream%tr = ne/ Stream%riter(-ileStr);
*
::Member -unction /(ic( is used in t(e @elegate
.ublic void &ogger(string &og8nfo)
{
Stream%tr$%rite&ine(&og8nfo);
*
.ublic void #lose()
{
Stream%tr$#lose();
-ileStr$#lose();
*
*
::Subscriber of t(e 5vent
.ublic class ,ecordAttendance
{
static void &ogger(string &og8nfo)
{
#onsole$%rite&ine(&og8nfo);
*
static void Main(string[] args)
{
Attendance&ogger -ile&og = ne/
Attendance&ogger('#)BB.rocess$log');
@elegate5vent @5vent = ne/ @elegate5vent();
::Subscribe t(e -unctions &ogger and -ile&og$&ogger
@5vent$5vent&og "= ne/
@elegate5vent$Attendance&og=andler(&ogger);
@5vent$5vent&og "= ne/
@elegate5vent$Attendance&og=andler(-ile&og$&ogger);
::7(e 5vent /ill no/ be triggered in te( &og6rocess() met(od
@5vent$&og6rocess();
#onsole$,ead&ine();
-ile&og$#lose();
*
*
*
as* ?$ 0uild and e!ecute the application
o build and e!ecute the application perform the following steps$
/* 0uild the solution by pressing Ctlr G )hift Gb
0* ,elect ebug )tart ebugging or press F5 to e!ecute the application
6* Cerify the output of the application
Practice `uestions
;. Identify the correct statement about delegate
a$ 0efore you declare an event inside a class, you can optionally declare a delegate
by using the delegate *eyword
b$ he delegate type consists of the set of arguments that it receives from the
method that handles the event
c$ Bultiple events cannot share the same delegate
d$ 0y using a single-cast delegate, you can invo*e only one method corresponding
to different events
D. 3hich of the following code is correct to assign more than one method address to a
delegate1
a$ @elegateVariable = ne/ My@elegate(-unction1)
@elegateVariable "= ne/ My@elegate(-unction!)
b$ @elegateVariable = ne/ My@elegate(-unction1);
@elegateVariable "= My@elegate(-unction!);
c$ @elegateVariable = ne/ My@elegate(-unction1);
@elegateVariable "= ne/ My@elegate(-unction!"-unction!);
d$ @elegateVariable = ne/ My@elegate(-unction1);
@elegateVariable "= ne/ My@elegate(-unction!);
?. ,tate whether the given statement is rue or (alse
' publisher is an object that contains the definition of the event and the delegate
@. Batch the following delegate concepts with there implementation
*e"egate ,mp"ementatin Synta&
(eclaring delegates 2est(elegate %ar T new 2est(elegate3"!nc4N
Instantiating (elegates !blic delegate %oid 2est(elegate3string arg4N
Esing delegates 2est(elegate3#2est'4N
A. ,tate whether the given statement is rue or (alse
&elegates used with the events should be declared void.
)u!!ary
In this chapter, you learned that$
&elegates allow you to write code that can dynamically change the methods that it calls.
here are two types of delegates, ,ingle-cast delegate and Bulticast delegate.
' single-cast cast delegate can call only one function.
Bulticast delegate holds the reference of more than one method.
,ingle-cast delegate derives from the ,ystem.&elegate class and multicast delegate
derives from the ,ystem.Bulticast&elegate.
%vents are the messages sent by an object to indicate the occurrence of an event.
%vents use the publisher and subscriber model.
' publisher is an object that maintains its internal state.
' subscriber is an object that registers an interest in an event.
Exercises
Exercise /
3rite an application that creates a class named Gegistration. he application would be used by
the counselors of an I education center, while registering students. he registration data entry is
done differently for career registration and for Bodular registration. )ou application should have
separate class for the two categories of students. )ou need to record the student.s score of the
aptitude test for "areer registration. )ou need to record the student.s prior e!perience or
*nowledge for Bodular registration.
:int$ Hse delegate in the registration class while registering a student to call the appropriate
methods.
Chapter /6
Attributes and Reflection
'ttributes are a simple techni/ue for adding metadata information and behavior to code within
applications. )ou use the reflection techni/ue to pic* the attribute related information at runtime.
his chapter introduces attributes and reflection and the functions they perform in "#
applications. his chapter discusses attribute synta!, and how to use some of the predefined
attributes. his chapter also discusses how to create customi2ed user-defined attributes. In
addition, this chapter discusses reflection and how to use it to e!tract attribute related information.
Objectives
In this chapter, you will learn to$
&escribe attributes
Getrieve metadata using reflection
#ntroducing Attributes
'n object is described by the values of its attributes. (or e!ample, a car can be described by its
ma*e, model, or color. ,imilarly, a "# program has certain attributes which depict and influence
its behavior, for e!ample, compiler instructions.
'n attribute is a declarative tag that is used to convey information to runtime about the behavior
of programmatic elements such as classes, enumerators, and assemblies. ' declarative tag is
depicted by s/uare (OP) brac*ets placed above the definition of an element such as a class or a
method.
'ttributes are used for adding metadata, such as compiler instructions and other information such
as comments, description, methods, and classes to a program.
'pplying attributes
'ttributes are applied to different elements of the code. hese elements include assemblies,
modules, classes, structs, enums, constructors, methods, properties, fields, events, interfaces,
parameters, return values, and delegates. Information about attributes is stored with the metadata
of the elements they are associated with$
he following synta! enables you to specify an attribute$
[attribute(.ositionalL.arameters+nameL.arameter=value+ $ $$)] element
In the preceding synta!, an attribute name and its values are specified within s/uare brac*ets(O P)
before the element to which the attribute is applied. 'ttributes might re/uired one or more
parameters, positional or named. Positional parameters are used to specify essential information
of an attribute, whereas named parameters are used to convey optional information of an
attribute.
he .+% (ramewor* supports two categories of attributes to be used in "# program$ predefined
and custom. Predefined attributes are supplied as part of the "ommon 4anguage Guntime ("4G)
and they are integrated into .+% "ustom attributes are attributes that you create according to
your re/uirement.
Hsing Predefined 'ttributes
,ome commonly used predefined attributes provided with .+% (ramewor* are$
"onditional$ "auses conditional compilation of method calls, depending on the specified
value such as &ebug or race. (or e!ample, it displays the values of variables, when
debugging a code. :owever, this attribute only determines the action that will occur when
a method is called. If conditional compilation of a method is re/uired, the #if and #endif
directives are used in the code. he methods to which you can apply a conditional
attribute are subject to a number of restrictions. In particular, they must have a return type
of void and must not be mar*ed as an override, and the implementation of the method
should be from an inherited surface.
(or e!ample$
O "onditional(6&%0H58P)
he preceding statement ensures that the target element, whether a class or a method
ensures use of that element in debugging mode only. he other value of this attribute can
be$
O "onditional(6G'"%8P)
3ebBethod$ Identifies the e!posed method in a web service. ' web service is a web
application that allows you to e!pose business functionality to other application that
allows you to e!pose business functionality to other applications. (urthermore, the
various properties of this attribute enable you to configure the behavior of the e!posed
method.
he following code is an e!ample of using 3ebBethod attribute$
O3ebBethod (&escription^8"onverts temperature from (ahrenheit to "elsius.8)P
.ublic double 7em.#onvert(double my7em.)
{
return ((my7em. 0 9!) > 4) : N;
*
he preceding code provides an e!posed method of a 3eb ,ervice which converts
temperature from (ahrenheit to "elsius. he 3ebBethod attribute definition above
7em.#onvert() method tells the compiler that it is an e!posed method and the
&escription property of the 3ebBethod attribute provides information about wor*ing of
the 7em.#onvert () method
&llImport$ "alls an unmanaged code in programs developed outside the .+%
environment. 'n e!ample of such a program is the standard " program compiled into
&44 files. 0y using the &llImport attribute, the unmanaged code residing in &44s can be
called from the managed "# environment.
he following code is an e!ample of using &llImport attribute$
using System;
using System$,untime$8ntero.Services;
using System$8F;
names.ace AttendanceA..
{
class Ienerate1ee.s
{
[@ll8m.ort(L2ernel9!$dll$)]
[@ll8m.ort
.ublic static eJtern bool 1ee.(int f+ int d);
static void Main()
{
1ee.(1000+111);
*
*
*
he preceding code uses the 0eep() method defined in Jernel?D.dll and parameter f and
d signify the fre/uency and duration of beep to generate.
Obsolete$ %nables you to inform the compiler to discard a piece of target element such as
a method of a class. (or e!ample, when a new method is being used in a class but you
still want to retain the old method in that class, as a developer, you can mar* the old
method as obsolete. )ou mar* the old method as obsolete by displaying a message
stating that instead of the old method, the new method should be used.
he following code is an e!ample of using Obsolete attribute$
using System;
.ublic class My#lass
{
[Fbsolete('@on;t use t(e A() met(od+ instead use 1()
met(od'+ true)]
static void A() { *
static void 1() { *
.ublic static void Main()
{
A();
*
*
In the preceding code, the first parameter is string, which contains the message. he
second parameter tells the compiler to treat the use of the element as an error. he
default value is false, which means compiler generates a warning for this.
Creating Custo! Attributes
he .+% (ramewor* allows creation of custom attributes, which can be used to store information
and can be retrieved at run time. his information can be related to any target element depending
upon the design and the need of an application.
"onsider this scenario. ' software development company wants to *eep trac* of all the bug fi!es
as a part of its development process. 'lthough, the company maintains a bug database
generated during and after the developmental process, the program manager wants to attach
proper bug fi!ing reports in code itself. o address this re/uirement, developers might add
comment statements to code. his following code statement displaying a comment is a bug fi!
e!ample$
::1ug [ 1!! fiJed by Sara &evo on O:1!:!00G
'lthough, the preceding comment statement gives some information in the source code, but it
gives no direct association to 0ug [ 1!!, information of which might be stored in the bug
database. In such a situation, the custom attribute can help replace the preceding code statement
with the following code statement$
[1ug-iJingAttribute(1!!+'Sara &evo'+'O:1!:!00G') ,emar2s = '@ata 7y.e
Mismatc( at &ine EE']
' simple program can be written to read through the metadata to find the bug fi!ing notations and
to help update the bug database. Betadata is data about data. In other words, it is information
that is used to describe other data.
o create custom attributes, you need to$
&efine a custom attribute
+ame the custom attribute
"onstruct the custom attribute
'pply the custom attribute to target element
&efining ' custom attribute
' new custom attribute is derived from the ,ystem.'ttribute system class, as shown in the
following code$
.ublic class 1ug-iJingAttribute ) System$Attribute
)ou need to then apply the attribute target using a predefined attribute to the new custom
attribute class, 'ttributeHsage, as shown in the following code statement$
[AttributeVsage(Attribute7argets$#lass W Attribute7argets$#onstructor W
Attribute7argets$-ield W Attribute7argets$Met(od W
Attribute7argets$6ro.erty+ Allo/Multi.le=true)]
he AttributeVsage attribute allows two arguments. One argument is a set of flags that
indicates the target element. o continue with the bug fi!ing e!ample, the AttributeVsage
attribute will be the class and its constructor, fields, methods, and properties.
he other argument is a flag that indicates whether a given element might be applied with more
than one such attribute. In the preceding code, the Allo/Multi.le property is set to true,
indicating that more than one 1ug-iJingAttribute can be applied to class and its members.
0esides the Allo/Multi.le property there are other properties that can be used with the
attributes. hese properties are$
#nherited$ ' 0oolean value 6true8 for this property indicates that if an attribute is applied
to base class and all its derived classes. ' value of 6false8 stops the attribute when it is
applied to a subclass.
1alidOn$ his property helps define the target elements on which the custom attribute
can be applied. he element to which you attach an attribute is called an attribute target.
he Attribute7argets enumerator is used for setting all the possible attribute targets.
he following table lists the various member names of the Attribute7argets enumerator.
'em#er Name Attri#ute Targets
.ll, 0le&ents incl!ding asse&bly, class, class &e&ber, delegate, en!&,
e%ent, field, interface, &ethod, &od!le, para&eter, property, or str!ct
.sse&bly .sse&bly only
Class Instances of a class
Class*e&bers Classes, str!cts, en!&s, constr!ctors, &ethods, properties, fields,
e%ents, delegates, and interfaces
Constr!ctor Class constr!ctors
(elegate (elegate &ethods
0n!& (efined en!&eration
0%ent (efined e%ents
"ield "ields
Interface Interfaces
*ethod (efining &ethods
*od!le . single &od!le
ara&eter ara&eters of a &ethod
roperty roperties 3both get and set, if i&ple&ented4
Str!ct str!cts
2a!ing the Custo! Attribute
4et us continue with the bug fi!ing e!ample in which the new custom attribute is named as
1ug-iJingAttribute. he normal convention is to append the word Attribute to the
attribute name. he compiler supports appending by allowing you to call the attribute with the
shorter version of the name.
herefore, the attribute can be written as shown in the following code statement$
[1ug-iJingAttribute(1!!+'Sara &evo'+'O:1!:!00G') ,emar2s = '@ata 7y.e
Mismatc( at &ine EE']
he compiler first loo*s for the definition of an attribute named 1ug-iJing. 3hen it does not find
the definition it loo*s for the definition with the name 1ug-iJingAttribute$
Constrcuting the Custo! Attribute
%very attribute must contain at least one constructor. In the following bug fi!ing e!ample, the bug
number, developer.s name, and fi!ed date are positional parameters and remar*s is a named
parameter. Positional parameters are passed through the constructor in the order declared in the
constructor, as shown in the following code snnipet$
.ublic 1ug-iJingAttribute(int 1ug3o+ string @evelo.er+ string @ate-iJed)
{
t(is$1ug3o = 1ug3o;
t(is$@evelo.er = @evelo.er;
t(is$@ate-iJed = @ate-iJed;
*
+amed parameters are implemened as properties, as shown in the following code snnipet$
.ublic string ,emar2s
{
get
{
return ,emar2s;
*
set
{
,emar2s = value;
*
*
It is common to create read-only properties for the positional parameters$
.ublic int 1ug3o
{
get
{
return 1ug3o;
*
*
Applying the Custo! Attribute-
he attribute can be applied by placing it immediately before its target. o test the
1ug-iJingAttribute attribute for the preceding e!ample, you can create a program for a
simple class named "alculator and give it four functions. )ou need to assign the
1ug-iJingAttribute to the target element class to record its code-maintenance history, as
shown in the following code snnipet$
[1ug-iJingAttribute(1!4+'Sara &evo'+'O:14:!00G') ,emar2s = ',eturn
FbDect not s.ecified']
[1ug-iJingAttribute(14N+'Sara &evo'+'O:1H:!00G') ,emar2s = '@ata 7y.e
Mismatc(']
.ublic class #alculator
he 1ug-iJingAttribute attribute will be stored with the metadata. he following code shows
the complete lisitng of the bug fi!ing problem$
using System;
using System$,eflection;
using System$#ollections$Ieneric;
using System$7eJt;
names.ace AttributeL5Jam.le
{
::create a custom attribute to be assigned to class and its members
[AttributeVsage(Attribute7argets$#lass W
Attribute7argets$#onstructor W Attribute7argets$-ield W
Attribute7argets$Met(od W Attribute7argets$6ro.erty+ Allo/Multi.le =
true)]
.ublic class 1ug-iJingAttribute ) System$Attribute
{
.rivate int bug3o;
.rivate string develo.er;
.rivate string date-iJed;
.rivate string remar2s;
::attribute constructor for .ositional .arameters
.ublic 1ug-iJingAttribute(int 1ug3o+ string @evelo.er+ string
@ate-iJed)
{
t(is$bug3o = 1ug3o;
t(is$develo.er = @evelo.er;
t(is$date-iJed = @ate-iJed;
*
.ublic int 1ug3o
{
get
{
return bug3o;
*
*
.ublic string @evelo.er
{
get
{
return develo.er;
*
*
.ublic string @ate-iJed
{
get
{
return date-iJed;
*
*
.ublic string ,emar2s
{
get
{
return ,emar2s;
*
set
{
,emar2s = value;
*
*
*

[1ug-iJingAttribute(1!4+'Sara &evo'+'O:14:!00G'+ ,emar2s = ',eturn
FbDect not s.ecified')]
[1ug-iJingAttribute(14N+'Sara &evo'+'O:1H:!00G'+ ,emar2s = '@ata
7y.e Mismatc(')]
.ublic class #alculator
{
.ublic double Add(@ouble num1+ @ouble num!)
{
return num1"num!;
*
.ublic double Subtract(@ouble num1+ @ouble num!)
{
return num10num!;
*
[1ug-iJingAttribute(144+'Sara &evo'+'O:1G:!00G')]
.ublic double Multi.ly(@ouble num1+ @ouble num!)
{
return num10num!;
*
[1ug-iJingAttribute(14G+'Sara &evo'+'O:1H:!00G')]
.ublic double @ivide(@ouble num1+ @ouble num!)
{
return num1:num!;
*
*

class 5ntry6oint
{
static void Main(string[] args)
{
#alculator myFbD = ne/ #alculator();
#onsole$%rite&ine('7(e sum of s.ecified t/o nos are {0*'+
myFbD$Add(14+!0$4));
#onsole$,ead&ine();
*
*
*
'fter e!ecuting the preceding code, the program output would be displayed. Open the
'ttributeM%!ample.e!e using the B,I4 &isassembler (I4 &,'B.e!e). (ollowing are the steps to
open 'ttributeM%!ample.e!e using the B,I4 &isassembler$
/* ,elect )tart All "rogra!s Microsoft *2ET Fra!e(or@ )' v0*4 Tools
M)#, isasse!bler
0* ,elect File Open* he Open dialog bo! is displayed.
6* ,elect the AttributeHExa!ple*exe file from the ebug folder of the project.
7* "lic* the O' button. he #, A)M window is displayed,
5* %!pand the AttributeHExa!ple AttributeHExa!ple*Calculator node.
3* Press CTR,GM. he Metadata window is displayed. he Metadata window displays the
complete metadata information containing the created 0ug(i!ing custom attributes.
Retrieving Metadata :sing Reflection
Geflection is used in the process of obtaining type information at runtime. he classes that give
access to the metadata of a running program are in the ,ystem.Geflection namespace.
he ,ystem.Geflection namespace contains classes that allow programmers to obtain information
about the application that is running and to dynamically add types, values, and objects to that
application.
Geflection is generally used for the following tas*s$
1ie(ing !etadata$ 'llows viewing attribute information from the code at runtime
"erfor!ing type discovery$ 'llows e!amining the various types in an assembly and
instantiate those types
,ate binding to !ethods and properties- 'llows the developer to call properties and
methods on dynamically instantiated objects using type discovery
Reflection e!it- 'llows you to create new types at runtime and then to use those types
to perform tas*s
Ciewing Betadata
o view metadata using reflection, the BemberInfo object of the ,ystem.Geflection needs to be
instantiated. his object helps discover the attributes of a member and to provide access to
metadata. a*ing the bug fi!ing e!ample further, use reflection to read metadata in the "alculator
class. o do this you need to define an object of the "alculator class, as shown in the following
code statement$
7y.e ty.e = ty.eof(#alculator);
In the preceding code statement the typeof operator on the "alculator type, returns an object of
the 7y.e ty.e class. he 7y.e class is the root of the reflection class and it is the primary way
to access metadata. It encapsulates a representation of the type of an object. he BemberInfo
object of ,ystem.Geflection namespace derives from the ype class that encapsulates
information about the members of a class.
hen, you need to initiate a call on the 5et"ustom'ttributes() function. his function returns an
array of objects, each of type 0ug(i!ing'ttribute.
he following code shows the modified Bain() method of the bug fi!ing e!ample$
class 5ntry6oint
{
static void Main(string[] args)
{
#alculator myFbD = ne/ #alculator();
#onsole$%rite&ine('7(e sum of s.ecified t/o nos are {0*'+
myFbD$Add(14+ !0$4));
#onsole$,ead&ine();
7y.e ty.e = ty.eof(#alculator);
::iterating t(roug( t(e attributes of t(e #alculator class
foreac( (FbDect attributes in
ty.e$Iet#ustomAttributes(false))
{
1ug-iJingAttribute my1-AFbD =
(1ug-iJingAttribute)attributes;
if (null ?= my1-AFbD)
{
#onsole$%rite&ine('Bn 1ug [) {0*'+ my1-AFbD$1ug3o);
#onsole$%rite&ine('Bn @evelo.er [) {0*'+
my1-AFbD$@evelo.er);
#onsole$%rite&ine('Bn @ate -iJed [) {0*'+
my1-AFbD$@ate-iJed);
#onsole$%rite&ine('Bn ,emarts [) {0*'+
my1-AFbD$,emar2s);
*
*
::iterating t(roug( t(e attributes of all t(e met(ods of a
#alculator class
foreac( (Met(od8nfo met(od in ty.e$IetMet(ods())
{
foreac( (Attribute attributes in
met(od$Iet#ustomAttributes(true))
{
1ug-iJingAttribute my1-AFbDM =
(1ug-iJingAttribute)attributes;
if (null ?= my1-AFbDM)
{
#onsole$%rite&ine('Bn 1ug [) {0* for Met(od
{1*'+ my1-AFbDM$1ug3o+ met(od$3ame);
#onsole$%rite&ine('Bn @evelo.er [) {0*'+
my1-AFbDM$@evelo.er);
#onsole$%rite&ine('Bn @ate -iJed [) {0*'+
my1-AFbDM$@ate-iJed);
#onsole$%rite&ine('Bn ,emarts [) {0*'+
my1-AFbDM$,emar2s);
*
*
*
#onsole$,ead&ine();
*
*
he preceding code prints all the bug fi!ing related inforamtion defined using attributes.
"erfor!ing Type iscovery
Geflection also helps to e!plore and e!amine the contents of an assembly. It helps find the types
associated with a modulelR the methods, fields, properties, and events associated with a type, as
well as the signatures of each type of methodsR the interfaces supported by the typeR and the
type.s base class. he type discovery information can also be viewed through the Object 0rowser
window of Cisual ,tudio .+% I&%.
,ate Ainding to Methods and "roperties
0inding a method at runtime is called late-binding. Geflection provides the fle!ibility of choosing
an object you will bind at runtime and calling it programmatically. (or e!ample, by using late-
binding, you can enable your program to interact with calendar or the other components of a
running word processing application such as Bicrosoft 3ord.
Reflection E!it
Geflection emit allows creation of new types at runtime and further use those types to perform
certain tas*s. (or e!ample, an assembly can be defined to e!ecute dynamically or to save itself
to dis*. (urthermore, reflection emit enables you to define new modules and new types with
methods.
Activity- Creating and .uerying Custo! Attribute #nfor!ation
"roble! )tate!ent
Fohn is a developer in a software development company. he program manager wants Fohn to
ensure proper documentation of the business logic of the "alculator application as a part of
development process. 'lthough, the company maintains a separate sheet to describe the use
classes and their version number, the program manager wants to attach that sheet to classes.
O:int$ Hse the "alculator class given in the preceding section for providing the business logicP
,olution
o create a console-based application for "alculator application, Fohn needs to perform the
following tas*s$
;. "reate a console-based application
D. 0uild and e!ecute an application
as* ;$ "reating a "onsole-based application
o create a console based application, Fohn needs to perform the following steps$
/* ,elect )tart All "rogra!s Microsoft 1isual )tudio 0445 Microsoft 1isual
)tudio 0445* he )tart "age C Microsoft 1isual )tudio window will be displayed
0* ,elect File 2e( "roject* he 2e( "roject dialog bo! will be displayed
6* ,elect the project type as 1isual C$ from the "roject types pane and Console
Application from the Te!plates pane.
7* ype the name of the new project as Attrib2a!e)pace in the 2a!e te!t bo!.
5* ,pecify the location where the new project is to be created as c-Dchapter/0DActivity/ in
the ,ocation combo bo!.
3* "lic* the O' button.
8* Open the )olution Explorer window and right-clic* the "rogra!*cs file.
9* ,elect the Rena!e option and type the new name as escriptionAttribute*cs
>* &ouble-clic* the escriptionAttribute*cs file in the solution explorer window. he
code view of the escriptionAttribute*cs file is displayed
/4* Geplace the e!isting code with the following code$
using System;
using System$,eflection;
using System$#ollections$Ieneric;
using System$7eJt;
names.ace Attrib3ameS.ace
{
::create @escri.tionAttribute custom attribute to be assigned to
class members
[AttributeVsage(Attribute7argets$#lass+ Allo/Multi.le = true)]
[@escri.tionAttribute('7(is class contains definition of @escri.tion
Attribute'+ 1$0)]
.ublic class @escri.tionAttribute ) System$Attribute
{
.rotected string descri.tion;
.rotected double version;
::attribute constructor for .ositional .arameters
.ublic @escri.tionAttribute(string @escri.tion+ @ouble Version)
{
t(is$descri.tion = @escri.tion;
t(is$version = Version;
*
.ublic String @escri.tion
{
get
{
return t(is$descri.tion;
*
*
.ublic double Version
{
get
{
return t(is$version;
*
set
{
t(is$version = value;
*
*
*
[@escri.tionAttribute('7(is class contains t/o met(ods'+ 1$0)]
.ublic class #alculator
{
.ublic double Add(@ouble num1+ @ouble num!)
{
return num1 " num!;
*
.ublic double Subtract(@ouble num1+ @ouble num!)
{
return num1 0 num!;
*
.ublic double Multi.ly(@ouble num1+ @ouble num!)
{
return num1 0 num!;
*
.ublic double @ivide(@ouble num1+ @ouble num!)
{
return num1 : num!;
*
*
[@escri.tionAttribute('7(is class contains t(e main met(od'+ !$0)]
.ublic class 5ntry6oint
{
.ublic static void Main(string[] args)
{
#alculator myFbD = ne/ #alculator();
#onsole$%rite&ine('7(e sume of t(e s.ecified numbers is
{0*'+ myFbD$Add(14+ !0$4));
7y.e ty.e = ty.eof(#alculator);
::S.ecific call s(ould be made to retrieve an attribute
.ro.erties
::%(en ! or more custom attributes are t(ere in an
a..lication
foreac( (Attribute attributes in
ty.e$Iet#ustomAttributes(ty.eof(@escri.tionAttribute)+false))
{
@escri.tionAttribute my@AFbD =
(@escri.tionAttribute)attributes;

if (null ?= my@AFbD)
{
#onsole$%rite&ine('Bn #lass) #alculator 0
@escri.tion ) {0* 0 Version {1)'+ my@AFbD$@escri.tion+ my@AFbD$Version);

*
*
ty.e = null;
ty.e = ty.eof(5ntry6oint);
foreac( (FbDect attributes in
ty.e$Iet#ustomAttributes(false))
{
@escri.tionAttribute my@AFbD =
(@escri.tionAttribute)attributes;
#onsole$%rite&ine('Bn #lass) 5ntry6oint 0 @escri.tion )
{0* 0 Version {1)'+ my@AFbD$@escri.tion+ my@AFbD$Version);
*
#onsole$,ead&ine();
*
*
*
as* D$ 0uild and e!ecute the application
o build and e!ecute the application perform the following steps$
/* 0uild the solution by pressing Ctlr G )hift Gb
0* ,elect ebug )tart ebugging or press F5 to e!ecute the application
6* Cerify the output of the application
"ractice .uestions
;. ,tate whether the following statement is rue or (alse$
Geflection emit allows creation of new types at runtime.
D. "onsider the following statements
,tatement ' $ +amed parameters are used to specify essential information of an attribute.
,tatement 0$ Positional parameters are used to convey optional information in an
attribute.
a. ,tatement ' is false, ,tatement 0 is true
b. ,tatement 0 is true, ,tatement ' is false
c. 0oth ,tatements ' and 0 are true
d. 0oth ,tatements ' and 0 are false
?. 3hich predefined attribute allows you to call an unmanaged code in programs developed
outside the .+% environment1
a. "onditional
b. &44Import
c. Obsolete
d. 3ebBethod
@. 'ttribute property MMMMMMMM indicates that if an attribute is applied to base class and all
its derived classes
A. 3hich window displays the complete metadata information of an application containing
the custom attributes1
)u!!ary
In this chapter, you learned that$
'n attribute is a declarative tag that is used to convey information to runtime about the
behavior of programmatic elements such as classes, enumerators, and assemblies.
he .+% (ramewor* supports two categories of attributes to be used in "# programs$
predefined and custom.
Predefined attributes are supplied as part of the "4G, and they are interpreted into .+%
"ustom attributes are attributes that you create according to your re/uirement.
he element to which you attach an attribute is called an attribute target.
Geflection is used in the process of obtaining type information at runtime.
Geflection is generally used for the following tas*s
o Ciewing metadata
o Performing type discovery
o 4ate binding to methods and properties
o Geflection emit
Exercises
Exercise /
Berge the 0ugs (i!ing attribute and "lass description attribute together in a single application
and use reflection to retrieve data from the same.
Chapter /7
#ntroduction to *2ET Fra!e(or@
he .+% (ramewor* enables you to create robust and scalable applications. he .+%
(ramewor* consists of "ommon 4anguage Guntime, "ommon 4anguage ,pecification, and the
Fust-In-ime compiler.
0efore you can use Cisual ,tudio .+% for creating a console-based application, you need to
understand the .+% (ramewor* and the Cisual ,tudio .+% Integrated &evelopment
%nvironment.
his chapter introduces the features and components of the .+% (ramewor*. It e!plains the
process of creating and e!ecuting a console application in the Cisual ,tudio .+% I&%.
Objectives
In this chapter, you will learn to
Identify the components of the .+% (ramewor*
Hse the Cisual ,tudio .+% I&%
Identifying the "omponents of the .+% (ramewor*
Bicrosoft introduced the .+% (ramewor* with the intention of bridging the gap in interoperability
between applications. his framewor* aims at integrating various programming languages and
services. It is designed to ma*e significant improvements in code reuse, code speciali2ation,
resource management, Bultilanguage development, security, deployment, and administration. It
consists of all the technologies that help in creating and running robust, scalable, and distributed
applications. his suite consists of the .+% Products, .+% services and .+% (ramewor*$
.2ET "roducts- Bicrosoft has already introduced Cisual studio .+%, which is a tool for
developing .+et applications by using programming languages such as Cisual 0asic,
Cisual "# and Cisual "LL.
hese products aim at following developers to create applications, which are capable of
interacting seamlessly with each other. o ensure interaction between various
applications, all .+% products use eKtensible Bar*up 4anguage (KB4) for describing
and e!changing data between applications
+ote$
Y*J is a platfor& independent &ar,!p lang!age. It allows co&p!ters to store data is a
for&at, which can be interpreted by any other co&p!ter syste&. therefore, Y*J can be
!sed to transfer str!ct!red data between heterogeneo!s syste&s. Y*J is !sed as a
co&&on data interchange for&at in a n!&ber of applications.
.2ET )ervices$ .+% helps you to create software as 3eb ,ervices. ' 3eb ,ervices is
an application or business logic that is accessible through standard Internet protocols
such as :yperte!t ransfer Protocol (:P) and ,imple Object 'ccess Protocol (,O'P).
)ou can identify the service by a Hniform Gesource 4ocator (HG4). Its public interfaces
and bindings are described using KB4. herefore, users can subscribe to such a service
and use it as long as they need it, regardless of the hardware and software platform.
Bicrosoft has come up with its own set of 3eb ,ervices, *nown as By ,ervices. hese
,ervices are based on the Bicrosoft Passport 'uthentication service, which is used in
their web applications such as :otmail. his services allows users to access data by
lin*ing calendars, phoneboo*s, address boo*s, and personal references to the passport
authentication service
In addition, third party products and services can be integrated easily with the .+%
environment.
.2ET Fra!e(or@$ It is a foundation on which you design, develop and deploy
applications. It is consistent and simplified programming model that helps you to easily
build robust applications. It is the core of the .+% infrastructure because it e!ists as a
layer between the .+% applications and the underlying operating system. In other words,
the .+% (ramewor* encapsulates much of the basic functionality, such as debugging
and security services, which was earlier built in various programming languages, in the
form of a collection of services and classes
Co!ponents of the *2ET Fra!e(or@
he following figure shows the various components of the .+% (ramewor*.
he .+% (ramewor* consists of three main components$ "ommon 4anguage Guntime, .+%
(ramewor* 0ase classes and the user and program interfaces.
Co!!on ,anguage Runti!e %C,R&
he "4G is one of the most essential components of the .+% (ramewor*. "4G is the
environment where all programs using .+% technologies are e!ecuted. It provides services such
as code compilation, memory allocation, and garbage collection. he "4G allows the e!ecution of
code across different platforms by translating code into Intermediate 4anguage (I4). I4 is low level
language that the "4G understands.
I4 is converted into machine language during e!ecution by the Fust-In-ime (FI) compiler. &uring
FI compilation, code is also chec*ed for type safety. ype safety ensures that objects are always
accessed in a compatible way. If you try to assign an <-byte value to a variable of si2e of @ bytes,
the "4G will detect and trap such an attempt, "4G consists of a set of common rules followed by
all the languages of the .+% (ramewor*. his set of rules is *nown as "ommon 4anguage
,pecification ("4,). "4, enables an object or application to interact with the objects or
applications of other languages. he classes that follow the rules specified by "4, are termed as
"4,-complaint classes. he classes defined in the .+% (ramewor* class library are "4,-
compliant.
One of the specifications defined in "4, is "ommon ype ,ystem (",), which provides a type
system that is common across all languages. ", define how data types are declared, used and
managed in the code at run-time.
he ", also defines the rules that ensure that the data types of objects written in various
languages are able to interact with each other. (or e!ample, the si2e of integer and long
variables is the same across all "4,-complaint programming languages.
1indows Forms Console &pplications 1e! Forms : 1e! 0ervices
4,ET Framewor3 Base Class Li!raries
Common Lan2ua2e /untime
3hile e!ecuting the program, "4G plays an important role.
Identifying the Process of "ompilation
"ompilation is the process of creating an e!ecutable program from a source code. he source
code consists of instructions for the compiler, and an e!ecutable program consists of instructions
for the processor. herefore, compilation converts source code to machine language.
:owever, when you compile a program in .+%, the conversion of source code to machine
language happens in two stages. In the first stage, the compiler translates code into an I4. In
addition, during the process of compilation, the compiler also produces metadata about code,
such as classes and interfaces, dependencies and the versions of the components, used in the
application. I4 and metadata constitute an assembly.
'ssemblies contain metadata, which describe the assembly.s internal version number and details
of all the data and object types they contain. 3hen you compile a C"# application, Cisual
,tudio .+% creates an assembly that is a single file with the e!tension .e!e and .dll. 'ssemblies
can also contain one or more modules. (or e!ample, larger game projects may be planned in
such a way that several individual developers to wor* on separate modules, all creating a single
assembly.
he following figure shows the process of code compilation.
Identifying the Process of "ode %!ecution
&uring e!ecution, "4G performs the following steps$
4oading assemblies and identifying namespaces$ 'ssemblies are loaded in the memory.
'fter loading assemblies, "4G identifies namespaces for code in assemblies.
+amespaces are a collection of classes. he .+% (ramewor* uses namespaces to
organi2e its classes in a hierarchy. +amespaces implicitly have public access and this
cannot be changed.
FI compilation$ 0efore e!ecution, I4 is converted into machine language by the FI
compiler. +e!t, during the verification process, the I4 code is e!amined to confirm the
following points$
o he memory locations that code needs to access are available
o Bethods are called only through properly defined types
o I4 has been correctly generated
5arbage "ollection$ he garbage collection process begins after the FI compilation and
manages the allocation and de-allocation of memory for an application. 3henever you
create an object, the "4G allocates memory for the object from the managed heap. '
Program
Code
IL Metadata
Assembl&
3
Compile
managed heap is a region of the memory that is available for program e!ecution. If
sufficient memory is not available on the managed heap, the garbage collection process
is invo*ed.
he code developed in .+% is called managed code. he "4G manages the compilation and
e!ecution of the managed code to ensure proper functioning of the code. (or e!ample, the "4G
ta*es care of garbage collection, e!ception handling, and type safety for the managed code.
he unit of e!ecution in the "4G is an assembly. 'n assembly contains I4 and metadata that was
generated during compilation. It contains code that the "4G e!ecutes. 'll assemblies contain a
manifest, which contains information such as assembly name, version, and the list of files that
form the assembly. he I4 code cannot be e!ecuted if it does not have an associated assembly.
Instead of compiling the complete I4 code, the FI compiler compiles only the code that is
re/uired during e!ecution. It saves the time and memory re/uired to convert the complete I4 into
machine language.
he following figure shows the process of code compilation and e!ecution.
Set1opScore45
6gnoreScore45
777777777777777777
777777777777777777
777777777777777777
7
Set1opScore45
6gnoreScore45
777777777777777777
777777777777777777
777777777777777777
7
Cisual "# code I4 code
Code Co&pilation
I4 code Bachine 4anguage
FI
,etop,core()
invo*ed
Code 01ec!tion
Set1opScore45
6gnoreScore45
777777777777777777
777777777777777777
777777777777777777
7
Set1opScore45
In the preceding figure, two methods are shown, ,etop,core() and Ignore,core(). he
,etop,core() method will be invo*ed only if the current score of the player is higher than the top
score of the game. he Ignore,core() method will be invo*ed when the player is not the top
scorer and you do not want to add the player to the list of top scorers.
If the player has scored more than the top score, only the method ,etop,core() will be invo*ed.
3hen it is invo*ed, the code for the ,etop,core() method will be compiled by the FI compiler.
:owever, the code for the method Ignore,core() will not be converted to machine language by
the FI compiler because this method is not invo*ed.
The *2ET Fra!e(or@ Class ,ibrary
he .+% (ramewor* class library wor*s with any .+% language, such as C0.+%, C"LL .+%,
and C"#. his class library is built on the object-oriented nature of the runtime. he library
provides classes that can be used in the code to accomplish a range of common programming
tas*s, such as string management, data collection, database connectivity, and file access.
One of the most important features of the .+% (ramewor* class library is that it can be used in a
consistent manner across multiple languages. his means that you can use the same set of
classes for performing a specific tas* in C"# as well as in C"LL.
he .+% (ramewor* class library comprises namespaces, which are contained within
assemblies. 4et us loo* at what these two terms mean.
2a!espaces
+amespaces help you create logical groups of related classes and interfaces, which can be used
by any language targeting the .+% (ramewor*. +amespaces allow you to organi2e your classes
so that they can be easily accessed in other applications. +amespaces can be used to avoid any
naming conflicts between classes, which have the same names. (or e!ample, you can use two
classes with the same name in an application provided they belong to different namespaces.
)ou can access the classes belonging to a namespace by simply importing the namespace into
the application. he .+% (ramewor* uses a dot(.) as a delimiter between classes and
namespaces. (or e!ample, ,ystem."onsole represents the "onsole class of the ,ystem
namespace. +amespaces are also stored in assemblies.
Asse!blies
'n assembly is a single deployable unit that contains all the information about the implementation
of classes, structures, and interfaces. he assembly stores all the information about itself. his
information is called metadata and includes the name and version number of the assembly,
security information, information about the dependencies, and a list of the files that constitute the
assembly.
'll the applications developed using the .+% (ramewor* are made up of assemblies.
'ssemblies and the metadata provide the "4G with the information re/uired for e!ecuting an
application. (or e!ample, if an application uses a component, the assembly *eeps trac* of the
version number of the component used in the application. he assembly provides this information
to the "4G while the application is being e!ecuted. 'ssemblies also play an important role in
deployment and versioning.
:ser and "rogra! #nterfaces
't the presentation layer, .+% provides three types of user interfaces. hey are 3indows (orms,
3eb (orms, and console 'pplications. 3indow (orms are used in 3indows-based applications,
whereas 3eb (orms are used in 3eb-based applications for providing an interactive user
interface. hey provide a 3eb browser-based user interface. )ou can create character based
console applications that can be e!ecuted from the command line.
.+% provides a program interface, 3eb services, to communicate with remote components.
Advantages of the *2ET Fra!e(or@
,ome of the advantages offered by the .+% (ramewor* are$
Consistent progra!!ing !odel- he .+% (ramewor* provides a common OOPs
model across languages. his object model can be used in the code to perform several
tas*s, such as reading from and writing to files, connecting to databases, and retrieving
data.
Multi-platfor! applications$ here are several versions of 3indows most of which run
on !<I "PHs. ,ome versions, such as 3indows "% and I@-bit windows, run on non-!<I
"PHs as well. ' .+% application can e!ecute on any architecture that is supported by
the "4G. In future, a "4G version could even be built for non-windows platforms.
Multi-language integration- .+% allows multiple languages to be integrated. (or
e!ample, it is possible to create a class in C"# that derives from a class implemented in
C0.+%. o enable objects to interact with each other regardless of the language used to
develop them, a set of language features has been defined in "4,.
his specification includes the basic language features re/uired by many applications.
he "4, enhances language interoperability. he "4, also establishes certain
re/uirements, which help you to determine whether your managed code conforms to the
"4,. Bost of the classes defined in the .+% (ramewor* class library are "4,-complaint.
Auto!atic resource !anage!ent- 3hile creating an application, a programmer may
be re/uired to write code for managing resources such as files, memory, networ*
connections, and database resources. If a programmer does not free these resources,
the application may not e!ecute properly. he "4G automatically trac*s resource usage
and relieves a programmer of the tas* of manual resource management.
Easy of deploy!ent$ One of the goals of the .+% (ramewor* is to simplify application
deployment. .+% applications can be deployed simply by copying files to the target
computer. &eployment of components has also been simplified. ill now, Bicrosoft.s
"omponent object model ("OB) has been used for creating components. :owever, "OB
suffers from various problems relating to deployment. (or e!ample, every "OB
component needs to be registered before it can be used in an application.
Boreover, two versions of a component cannot run side-by-side. In such a case, if you
install a new application that installs the newer version of the component, the newly
installed application may function normally. :owever, the e!isting applications that
depend on the earlier version of the component may stop functioning. 's against this, the
.+% (ramewor* provides 2ero-impact deployment. Installation of new applications or
components does not have an adverse effect on the e!isting applications
In the .+% (ramewor*, applications are deployed in the form of assemblies. 'n
assembly stores metadata. herefore, registry entries are not re/uired for storing
information about components and applications. In addition, assemblies are store
information about the versions of components used by an application. herefore, the
problems relating to versioning are also eliminated in the .+% (ramewor*.
:sing the 1isual )tudio *2ET #E
he Cisual ,tudio .+% I&% provides you with a common interface for developing various *inds of
projects for the .+% (ramewor*. he I&% also provides you with a centrali2ed location for
designing the user interface for an application, writing code and compiling and debugging the
application.
he Cisual ,tudio .+% I&% is available to all the programmers who use languages in the Cisual
,tudio .+% suite. 0efore you start using Cisual ,tudio .+% for creating C"# applications, you
need to *now the various components of the Cisual ,tudio .+% I&%.
Creating "rojects and )olutions
In Cisual ,tudio .+%, an application can be made up of one or more items, such as files and
folders. o organi2e these items efficiently, Cisual ,tudio .+% has provided D types of containers$
projects and solutions.
' project typically contains items that ma*e up the application. hese items are interrelated. '
project allows you to manage, build, and debug the items that ma*e up an application. 3hen you
build a project, it usually results in the creation of an e!ecutable .e!e or .dll files. hese files that
are created as a result of building the project are called the project output.
' solution usually acts as a container for one or more projects. (or e!ample, you may create a
solution containing two projects, one for manipulation of data and the other for generation of
reports for the sales division of an organi2ation. hus, a solution allows you to wor* on multiple
projects within the same instance of the Cisual ,tudio .+% I&%.
' solution containing multiple projects is shown in the following figure.
o create a console application in Cisual ,tudio, you need to create a project. o create a project,
you need to perform the following steps$
;. ,elect )tart All "rogra!s Microsoft 1isual )tudio 0445 Microsoft 1isual
)tudio 0445* he )tart "age C Microsoft 1isual )tudio window will be displayed.
D. ,elect File 2e( "roject* he 2e( "roject dialog bo! will be displayed.
?. In the 2e( "roject dialog bo!, select 1isual C$ from the "roject Types pane and
Console Applications from the Te!plates pane
Project 8
Project -
%iscellaneous
Files
Solution Project 8 6tems
Project 8 6tems
Solution Containing Multiple Projects
here are many templates available in the Te!plates pane for a Cisual "# project. )ou can
select any one template described in the following table.
Temp"ate *escriptin
Hindows .pplication Creates an application with Hindows !ser interface
Class Jibrary Creates a class or a re!sable co&ponent that e1poses so&e
f!nctionality to be !sed in %ario!s projects
Hindows Control Jibrary Creates a c!sto& control that can be added to the !ser interface
Console .pplication Creates a console application that can r!n fro& the co&&and
line. . console application has a co&&and line interface
(e%ice .pplication Creates a for&s application for oc,et C 2;;- and later
Crystal Reports .pplication .dds a Hindows !ser interface and a sa&ple crystal Report in
the Vis!al C= application.
@. ,pecify the name of the application in the 2a!e te!t bo!.
A. ,pecify a location where the new project is to be created in the ,ocation combo bo!. )ou
can use the Aro(se button to browse to the folder in which the new project is to be
created.
I. "lic* the O' button.
:ser #nterface Ele!ents of 1isual )tudio *2ET #E
3hen you wor* with a console application project in Cisual ,tudio .+%, you can use the
following main elements in the Cisual ,tudio .+% I&%.
Carious standard interface elements are found in the 3indows environments, such as the menu
bar and the tool bar. In addition to these standard interface elements, the Cisual ,tudio .+% I&%
contains other elements. hese include the ,olution %!plorer window, Output window, as* 4ist
window, "lass Ciew window and the "ode %ditor window.
In addition, Cisual ,tudio .+% provides the ,tart Page and the Project properties window. he
,tart Page allows you to perform several tas*s and the Project Properties helps you to set the
projects compilation and configuration values.
,tandard oolbar
he standard toolbar is located below the menu bar. It provides shortcuts for menu commands.
he first few buttons of the toolbar enable you to perform tas*s common to many 3indow-based
programs, such as opening a new or an e!isting file, saving or printing a file, cutting and pasting
te!t and objects, and undoing or redoing the most recent actions. Other standard toolbar buttons
offer functions more specific to Cisual ,tudio .+% applications. he name and functions of the
various tools of the standard toolbar are listed in the following table.
Name +unctin
8ew Creates a new project
.dd 8ew Ite& .dd new ite& to the project
Sa%e Sa%es the progra&
Sa%e .ll Sa%e all the !nsa%ed ite&s of the application
C!t laces selected te1t or objects on the Hindows
Clipboard
Copy laces a copy of selected te1t or objects on the
Hindows Clipboard
aste astes the contents of the clipboard on the
doc!&ent
Start (eb!gging Co&piles and e1ec!tes the c!rrent project
The )tart "age
3hen you start Cisual ,tudio .+%, it displays the ,tart Page 9 Bicrosoft Cisual ,tudio window.
he ,tart Page is the default home page for the browser provided within the Cisual ,tudio .+%
I&%. his allows you to perform several tas*s, such as specifying your preferences, searching for
information on the new features of .+%, communicating with developers wor*ing on the .+%
platform, and searching for more information in the B,&+ Online 4ibrary.
3hen you open Cisual ,tudio .+%, the projects tab on the ,tart Page is selected by default. his
tab displays some of the recent projects and the last date of their modification. )ou can open any
one of these projects. If the project that you wish to wor* on is not listed, clic* the Open Project
button on the ,tart Page. If you wish to start with a new project, you can clic* the +ew Project
button on the ,tart Page.
The )olution Explorer
he ,olution %!plorer window lists the solution name, the project name, and all the classes that
are used in the project. )ou can open a particular file e!isting in a project by double-clic*ing the
file in the solution e!plorer window.
The Output +indo(
he Output 3indow displays messages for the status of various features provided in the Cisual
,tudio .+% I&%. (or e!ample, when you compile an application, this window displays the current
status. 'fter the compilation process is complete, it specifies the number of errors that occurred
during compilation. If this window is not visible, you can open it by selecting Ciew Output
3indow by pressing the "trlL3, O *eys simultaneously.
The Error ,ist +indo(
he %rror 4ist 3indow displays a list of errors along with the source (the file and the line number)
of the error. It helps you identify and locate problems that are detected automatically as you edit
and compile code. )ou can locate the source of a particular error by simply double-clic*ing the
error in the %rror 4ist 3indow. 'lternatively, you can press the "trlL3, % *eys simultaneously.
The Class 1ie( +indo(
he "lass Ciew 3indow displays the classes, methods, and properties associated with a
particular file. hey are displayed in a hierarchical tree-view depicting the containership of these
items. 3hen you double-clic* any one of the items in the "lass Ciew window, it brings up the
"ode %ditor window for that item, ma*ing it convenient to move through the code in the project.
he "lass Ciew 3indow has two buttons, one for sorting the items in the "lass Ciew 3indow and
the other for creating a new folder. If the class view window is not visible, you can open it either
by selecting Ciew "lass Ciew or by pressing the "trlL,hiftL" *eys simultaneously.
The Code Editor
he "ode %ditor allows you to enter and edit code. )ou may use this editor to add code for you
class.
Co!piling and Executing "roject
o compile and e!ecute the application, you need to perform the following steps$
;. ,elect Auild Auild )olution or press F3 to compile the application.
D. ,elect ebug )tart ebugging or press F5 to e!ecute the application.
"ractice .uestions
;. 3hat is Fust-In-ime compilation1
D. 3hich "4G feature ensures that data types are accessible across different applications1
?. 3hat is project output1
@. 3hich Cisual "# template allows to create a custom control that can be used in a 5HI
game1
a. 3indows "ontrol 4ibrary
b. &evice 'pplication
c. "lass 4ibrary
d. "rystal Geports 'pplication
A. )ou need to select the option from the debug menu to e!ecute a game developed in
Cisual ,tudio .+%
I. ,tate whether the given statement is rue or (alse
FI compilation saves time and memory re/uired to convert the complete I4 into machine
language
)u!!ary
In this chapter, you learned that$
he .+% (ramewor* is made up of many components, such as "4,, "4G, and FI
compiler.
"4, is a set of rules that are followed by all the languages of the .+% (ramewor*.
3hen a program is compiled using Cisual ,tudio .+% the compiler translates the code
into the I4 instead of machine language.
he FI compiler is used to translate code from I4 into machine language
he "4G is the environment where all .+% applications are e!ecuted.
he Cisual ,tudio .+% I&% provides you with a common interface for developing various
*inds of applications for the .+% (ramewor*
Cisual ,tudio .+% provides D types of containers, projects and solutions, to organi2e the
constituents of an applications.

Anda mungkin juga menyukai