You are on page 1of 390

TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA

(10MCA53)
.Net Programming
Syllabus
Module 1
Understanding previous states of affairs, The .Net Solution, The Building Block of the .Net Platform
(!", TS and !S#, The "ole of the .Net Base lass !i$raries, %hat & Brings to the Ta$le, 'n
(vervie) of .Net Binaries (or 'ssem$lies#, The "ole of the ommon *ntermediate !anguage, The "ole
of .Net T+pe Metadata, The "ole of the 'ssem$l+ Manifest, ompiling *! to Platform Specific
*nstructions.
Understanding the common t+pe s+stem, *ntrinsic TS ,ata T+pes, Understanding the ommon
!anguages Specification, Understanding the ommon !anguage "untime, ' tour of the .Net
Namespaces, *ncreasing -our Namespace Nomenclature, ,eplo+ing the .N.T "untime.
"ole of ommand !ine ompiler (csc.e/e#, Building & 'pplications using csc.e/e, %orking )ith
csc.e/e "esponse 0iles, 1enerating Bug "eports, "emaining & ompiler (ptions, The ommand !ine
,e$ugger (cord$g.e/e#, Using the 2isual Studio.N.T *,., The & 3Pre4processor5 ,irectives, 'n
*nteresting 'side6 S+stem..nvironment lass.
The 'natom+ of a Basic & lass, reating ($7ects6 onstructor Basics, The omposition of a &
'pplication, ,efault 'ssignment and 2aria$le scope, The & Mem$er *nitiali8ation S+nta/, Basic *nput
and (utput )ith the onsole lass, ,efining Program onstants, & *teration onstructs, & ontrols
0lo) onstructs, The omplete set of & (perators.
R.V.COLLEGE OF ENGINEERING Page 1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Understanding 2alue T+pes and "eference T+pes, The Master Node6 S+stem.($7ect, The S+stem ,ata
T+pes (and & 'liases#, onverting $et)een value t+pes reference t+pes6 Bo/ing and Un$o/ing.
,efining ustom lass Methods, Understanding Static Methods, Methods Parameter Modifiers,
'rra+ Manipulation in &, String Manipulation in &, & .numerations, ,efining Structures in &,
,efining ustom Namespaces.
0ormal ,efinition of the & lass, ,efinition the 3,efault Pu$lic *nterface5 of a T+pe, "ecapping the
Pillars of ((P, The 0irst Pillars6 &9s .ncapsulation Services, Pseudo .ncapsulation6 reating "ead4
(nl+ 0ields.
The Second Pillar6 &9s *nheritance Supports, :eeping famil+ secrets6 The 3Protected5 :e+)ord, Nested
T+pe ,efinitions, The Third Pillar6 &9s Pol+morphic Support, asting Bet)een.
Meaning of .rrors and ./ceptions, The "ole of .N.T ./ception ;andling, The S+stem. ./ception Base
lass, Thro)ing a 1eneric ./ception, atching ./ception, !" S+stem < !evel ./ception
(S+stem.S+stem./ception#, ustom 'pplication4!evel ./ception (S+stem.'pplication./ception#,
;andling Multiple ./ceptions, The 0inall+ Block, ,+namicall+ *dentif+ing 'pplication and S+stem
!evel ./ceptions.
Understanding ($7ect !ifetime, The *! of new, The Basics of 1ar$age ollection, 0inali8ation a t+pe,
The 0inali8ation Process, Building an ', ;oc ,estruction Method, 1ar$age ollection (ptimi8ations,
The S+stem. 1 T+pe.
,efining *nterfaces Using &, *nvoking *nterface Mem$ers at the o$7ect level, ./ercising the shapes
hierarch+, Understanding ./plicit *nterface *mplementation, *nterfaces as Pol+morphic 'gents, Building
*nterface ;ierarchies.
R.V.COLLEGE OF ENGINEERING Page =
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Understanding the *onverti$le *nterface, Building a ustom .numerator (*.nummera$le and
.numerator#, Building lonea$le o$7ects (*lonea$le#, Building ompara$le ($7ects (*ompara$le#,
./ploring the S+stem.ollections Namespace.
Understanding all$ack *nterfaces, Understanding the .N.T ,elegate T+pe, Mem$ers of
S+stem.Multicast ,elegate, The Simplest Possi$le ,elegate ./ample, Building More .la$orate ,elegate
./ample, Understanding 's+nchronous ,elegates, Understanding (and Using# .vents.
The advanced ke+)ords of &, Building a ustom *nde/er, (verloading operators, The *nternal
"epresentation of (verloading (perators, reating ustom onversion "outines, ,efining *mplicit
onversion "outines.
'n (vervie) of .N.T 'ssem$lies, ore Benefits of 'ssem$lies, Building a Single 0ile Test 'ssem$l+,
./ploring the Manifest, Building a Multifile 'ssem$l+.
Understanding Private 'ssem$lies, Pro$ing for Private 'ssem$lies (The Basics#, Private 'ssem$lies and
>M! onfiguration 0iles, Pro$ing for Private 'ssem$lies (The ,etails#, Understanding Shared
'ssem$l+, Understanding Strong Names, Building a Shared 'ssem$l+, Understanding ,ela+ed Signing,
*nstalling?"emoving Shared 'ssem$l+, Using a Shared 'ssem$l+.
.NET Programming
R.V.COLLEGE OF ENGINEERING Page @
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Module 1
Unit 1
CONTENTS:
1.1 ($7ectives
1.= *ntroduction
1.@ Understanding previous states of affairs
1.A The .Net Solution
1.B The Building Block of the .Net Platform (!", TS and !S#
1.C The "ole of the .Net Base lass !i$raries
1.D %hat & Brings to the Ta$le
1.E 'n (vervie) of .Net Binaries (or 'ssem$lies#
1.F The "ole of the ommon *ntermediate !anguage
1.1G The "ole of .Net T+pe Metadata
1.11 The "ole of the 'ssem$l+ Manifest
1.1= ompiling *! to Platform Specific *nstructions
1.1@ Summar+
1.1A :e+)ords
1.1B ./ercises
1.1 Objectives
't the end of this lesson, the students )ill understand6
The pro$lems )ith previous programming languages
The solution provided $+ .N.T
Building $locks of .N.T vi8. !", TS and !S
The role of Base lass !i$raries (B!#
The role of *!, Metadata and 'ssem$l+ manifest
1.= ntroduction
R.V.COLLEGE OF ENGINEERING Page A
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
;o)ever good a programming language is, it )ill $e overshado)ed $+ something $etter in the course of
time. The languages like , HH, 2isual Basic, Iava, the frame)orks like M0 (Microsoft 0oundation
lasses#, 'T!('ctive Template !i$rar+#, ST!(Standard Template !i$rar+# and the architectures like
(M (omponent ($7ect Model#, ("B' (ommon ($7ect "eJuest Broker 'rchitecture#, .IB
(.nterprise IavaBeans# etc. )ere possessing technologies )hich is needed $+ the programmer. But still,
the hunt for $etter one )ill $e going on even in future too.
1.@ Understanding !revious states o" a""airs
Before e/amining the specifics of the .N.T universe, it9s helpful to consider some of the issues that
motivated the genesis of Microsoft9s current platform. To get in the proper idea, let us discuss some of the
limitations of previous technologies.
#i"e as a C$%in&' (P Programmer
Building )indo)s applications using the ra) 'P* ('pplication Programming *nterface# and is
a comple/ task.
is a ver+ a$rupt language.
developers have to perform manual memor+ management.
involves ugl+ pointer arithmetic, and ugl+ s+ntactical constructs.
is a structured language and so lacks the $enefits provided $+ the o$7ect4oriented approach.
%hen +ou com$ine the thousands of glo$al functions and data t+pes defined $+ the %in@= 'P* to
a difficult language like , $ugs )ill increase rapidl+.
#i"e as a C))$M*C Programmer
The improvement over ra) ?'P* development is the use of the HH programming language.
Though HH provides ((Ps concepts like encapsulation, inheritance and pol+morphism, it is not
a)a+ from manual memor+ management and pointers.
R.V.COLLEGE OF ENGINEERING Page B
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
.ven )ith difficult+, man+ HH frame)orks e/ist toda+. 0or e/ample, the Microsoft 0oundation
lasses (M0# provides the developer )ith a set of HH classes that facilitate the construction of
%in@= applications.
The main role of M0 is to )rap a 3sane su$set5 of the ra) %in@= 'P* $ehind a num$er of
classes, magic macros, and numerous code4generation tools.
"egardless of the helpful assistance offered $+ the M0 frame)ork, HH programming remains a
difficult and error4prone e/perience, given its historical roots in .
#i"e as a +isual ,asic -.. Programmer
2BC is popular due to its a$ilit+ to $uild comple/ user interfaces, code li$raries, and simpler data
access logic.
.ven more than M0, 2BC hides the comple/ities of the ra) %in@= 'P* from vie) using a
num$er of integrated code )i8ards, intrinsic data t+pes, classes, and 2B4specific functions.
The ma7or do)nfall of 2BC is that it is not a full+ o$7ect4oriented language. 0or e/ample, 2BC
does not allo) the programmer to esta$lish 3is4a5 relationships $et)een t+pes.
2BC has no intrinsic support for parameteri8ed class construction.
2BC doesn9t provide the a$ilit+ to $uild multithreaded applications.
#i"e as a /ava$/'EE Programmer
Iava has greater strength $ecause of its platform independence nature.
Iava cleans up man+ unsavor+ s+ntactical aspects of HH.
Iava provides programmers )ith a large num$er of predefined 3packages5 that contain various
t+pe definitions.
'lthough Iava is a ver+ elegant language, one potential pro$lem is that using Iava t+picall+
means that +ou must use Iava front4to4$ack during the development c+cle.
So, language integration is difficult in Iava, )hich is against its primar+ goal (a single
programming language for ever+ need#.
Pure Iava is simpl+ not appropriate for man+ graphicall+ or numericall+ intensive applications.
R.V.COLLEGE OF ENGINEERING Page C
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
0or graphics oriented product, Iava )orks slo)l+ and compared to this, HH or )ould e/ecute
faster.
Iava provides a limited a$ilit+ to access non4Iava 'P*s and hence, there is little support for true
cross4language integration.
#i"e as a COM Programmer
(M is a group of classes, )hich )orks as a $lock of reusa$le code.
The $inar+ (M server can $e accessed in a language4independent manner. 0or e/ample, (M
classes )ritten using HH can $e used $+ 2BC.
But, (M9s language independence is some)hat limited as it )ill not support inheritance.
"ather, one must make use of 3has4a5 relationship to reuse (M class t+pes.
'lthough (M can $e considered a ver+ successful o$7ect model, it is e/tremel+ comple/ under
the internall+.
To help simplif+ the development of (M $inaries, numerous (M4a)are frame)orks have
come into e/istence.
.ven if )e choose a relativel+ simple (M4a)are language such as 2BC, )e are still forced to
contend )ith fragile registration entries and numerous deplo+ment4related issues.
#i"e as a %indo0s 1N( Programmer
The popularit+ of %e$ applications is ever e/panding.
Sadl+, $uilding a )e$ application using (M4$ased %indo)s ,N' (,istri$uted interNet
'pplications# is Juite comple/.
Some of this comple/it+ is $ecause %indo)s ,N' reJuires the use of numerous technologies
and languages like 'SP, ;TM!, >M!, IavaScript, 2BScript, ',( etc.
Man+ of these technologies are completel+ unrelated from a s+ntactic point of vie).
'lso each language and?or technolog+ has its o)n t+pe s+stem. 0or e/ample, an 3int5 in
IavaScript is not Juite the same as an 3*nteger5 in 2BC.
1.A T2e .NET Solution
R.V.COLLEGE OF ENGINEERING Page D
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
0or various pro$lems faced in previous technologies, the .N.T provides the solution. The .N.T
frame)ork is a completel+ ne) model for $uilding s+stems on the %indo)s famil+ of operating s+stems,
as )ell as on numerous non4Microsoft operating s+stems such as Mac (S > and various Uni/?!inu/
distri$utions. Some core features provided $+ .N.T are as follo)s6
Full interoperability with existing code: ./isting (M $inaries can mingle?interop )ith
ne)er .N.T $inaries and vice versa. 'lso, Platform *nvocation Services allo)s to call 4$ased
li$raries (including the underl+ing 'P* of the operating s+stem# from .N.T code.
Complete and total language integration: Unlike (M, .N.T supports cross4language
inheritance, cross4language e/ception handling, and cross4language de$ugging.
A common runtime engine shared by all .NET-aware languages: (ne aspect of this engine is a
)ell4defined set of t+pes that each .N.T4a)are language 3understands.5
A base class library: This li$rar+ protects the programmer from the comple/ities of ra) 'P* calls
and offers a consistent o$7ect model used $+ all .N.T4a)are languages.
No more COM plumbing: *lass0actor+, *Unkno)n, *,ispatch, *,! code, and 2'"*'NT4
compliant data t+pes (BST", S'0.'""'-, and so forth# have no place in a native .N.T $inar+.
A truly simpliied deployment model: Under .N.T, there is no need to register a $inar+ unit into
the s+stem registr+. 0urthermore, .N.T allo)s multiple versions of the same K.dll to e/ist on a
single machine.
NOTE! The .N.T platform has nothing to do )ith (M. *n fact, the onl+ )a+ .N.T and (M t+pes can
interact )ith each other is using the interopera$ilit+ la+er.
1.B T2e ,uilding ,loc3s o" .NET Plat"orm
The entities that make .N.T to provide several $enefits are !", TS, and !S. The .N.T can $e
understood as a ne) runtime environment and a comprehensive $ase class li$rar+.
R.V.COLLEGE OF ENGINEERING Page E
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
C#4:
The runtime la+er is properl+ referred to as the Common "anguage #untime 5C"#6.
The primar+ role of the !" is to locate, load, and manage .N.T t+pes.
The !" also takes care of a num$er of lo)4level details such as memor+ management and
performing securit+ checks.
CTS:
The Common Type $ystem %CT$6 specification full+ descri$es the entities like all possi$le data
t+pes and programming constructs supported $+ the runtime.
*t specifies ho) these entities can interact )ith each other.
*t also specifies ho) the+ are represented in the .N.T metadata format.
C#S:
' given .N.T <a)are language might not support each and ever+ feature defined $+ the TS.
The Common "anguage $peciication 5C"$6 is a related specification that defines a su$set of
common t+pes and programming constructs that all .N.T programming languages can agree on.
Thus, the .N.T t+pes that e/pose !S4compliant features can $e used $+ all .N.T4a)are
languages.
But, a data t+pe or programming construct, )hich is outside the $ounds of the !S, ma+ not $e
used $+ ever+ .N.T programming language.
1.C T2e 4ole o" ,ase Class #ibraries
*n addition to the !" and TS?!S specifications, the .N.T platform provides a $ase class li$rar+ that
is availa$le to all .N.T programming languages. This $ase class li$rar+ encapsulates various primitives
such as threads, file input?output (*?(#, graphical rendering, and interaction )ith various e/ternal
hard)are devices. *t also provides support for a num$er of services reJuired $+ most real4)orld
applications. 0or e/ample, the $ase class li$raries define t+pes
R.V.COLLEGE OF ENGINEERING Page F
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Figure 1.1 The CLR, CTS, CLS, and base class library relationship
R.V.COLLEGE OF ENGINEERING Page 1G
The Base Class Libraries
Data Access GUI Security XML/SOAP
Threading IL! I/O Debugging "et al#$
The C%&&%n Language 'unti&e
C%&&%n Ty(e Syste&
C%&&%n Language S(eci)icati%n
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
that facilitate data$ase access, >M! manipulation, programmatic securit+, and the construction of )e$4
ena$led, traditional desktop and console4$ased front ends. 0rom a high level, +ou can visuali8e the
relationship $et)een the !", TS, !S, and the $ase class li$rar+, as sho)n in 0igure 1.1.
1.D %2at C7 ,rings to t2e Table
& is a programming language that looks very similar to the s+nta/ of Iava. Man+ of the s+ntactic
constructs of & are taken from various aspects of 2isual Basic C.G and HH. 0or e/ample, like 2BC, &
supports the notion of formal t+pe properties, and the a$ilit+ to declare methods taking var+ing num$er of
arguments. !ike HH, & allo)s +ou to overload operators, as )ell as to create structures, enumerations,
and call$ack functions (via delegates#.
The features of & language can $e put together as <
No pointers reJuiredL & programs t+picall+ have no need for direct pointer manipulation
'utomatic memor+ management through gar$age collection. 1iven this, & does not support a
delete ke+)ord.
0ormal s+ntactic constructs for enumerations, structures, and class properties.
The HH4like a$ilit+ to overload operators for a custom t+pe, )ithout the comple/it+.
The s+nta/ for $uilding generic t+pes and generic mem$ers is ver+ similar to HH templates.
0ull support for interface4$ased programming techniJues.
0ull support for aspect4oriented programming ('(P# techniJues via attri$utes. This $rand of
development allo)s +ou to assign characteristics to t+pes and their mem$ers to further Jualif+
their $ehavior.
& produces the code that can e/ecute )ithin the .N.T runtime. The code targeting the .N.T runtime is
called as managed code. The $inar+ unit that contains the managed code is termed as assembly.
onversel+, code that cannot $e directl+ hosted $+ the .N.T runtime is termed unmanaged code.
R.V.COLLEGE OF ENGINEERING Page 11
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1.E (n Overvie0 o" .NET (ssemblies 5or ,inaries6
The .N.T $inaries are not descri$ed using (M t+pe li$raries and are not registered into the s+stem
registr+. The .N.T $inaries do not contain platform4specific instructions, $ut rather platform4agnostic
intermediate language (IL# and t+pe metadata. The relationship $et)een .N.T a)are compilers and
metadata are sho)n in 0ig. 1.=.
Note: The terms *!, MS*! (Microsoft *ntermediate !anguage# and *! (ommon *ntermediate
!anguage# are all descri$ing the same e/act entit+.
R.V.COLLEGE OF ENGINEERING Page 1=
C* S%urce C%de
Perl t% Perl #+!T
S%urce C%de
COBOL t%
COBOL# +!T
S%urce C%de
C,, t% MC,,
S%urce C%de
MSIL
and
Metadata
"DLL %r !X!$
C* C%&(iler
Perl t% Perl #+!T C%&(iler
COBOL t% COBOL# +!T
C%&(iler
C,, t% MC,, C%&(iler
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
*igure 1.' All .NET-aware compilers produce IL instructions and metadata.
0e) points to $e understood a$out $inaries?assem$lies are6
%hen a K.dll or K.e/e has $een created using a .N.T4a)are compiler, the resulting module is
$undled into an assembly.
'n assem$l+ contains *! code, ()hich is conceptuall+ similar to Iava $+tecode#. This is not
compiled to platform4specific instructions until a$solutel+ necessar+.
%hen a $lock of *! instructions (such as a method implementation# is referenced for use $+
the .N.T runtime engine, *! code )ill $e compiled.
'ssem$lies also contain metadata that descri$es the characteristics of ever+ 3t+pe5 living )ithin
the $inar+, in detail. 0or e/ample, if +ou have a class named Sportsar, the t+pe metadata
descri$es details such as Sportsar9s $ase class, )hich interfaces are implemented $+ Sportsar
(if an+#, as )ell as a full description of each mem$er supported $+ the Sportsar t+pe.
Unlike (M, the .N.T metadata is al)a+s present and is automaticall+ generated $+ a given
.N.T4a)are compiler.
*n addition to *! and t+pe metadata, assem$lies themselves are also descri$ed using metadata,
)hich is officiall+ termed as a maniest.
The manifest contains information a$out the current version of the assem$l+, culture information
(used for locali8ing string and image resources#, and a list of all e/ternall+ referenced assem$lies
that are reJuired for proper e/ecution.
Single8*ile and Multi"ile (ssemblies
*f an assem$l+ is composed of a single K.dll or K.e/e module, +ou have a single-file assembly. ' single4
file assem$l+ contains the assem$l+ manifest, the t+pe metadata, the *! code, and the resources. 0igure
1.@ sho)s a single4file assem$l+ and its contents.
Multifile assem$lies are composed of numerous .N.T $inaries, each of )hich is termed a module. %hen
$uilding a multifile assem$l+, one of these modules (termed the primary module# must contain the
assem$l+ manifest (and possi$l+ *! instructions and metadata for various t+pes#. The other related
R.V.COLLEGE OF ENGINEERING Page 1@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
modules contain a module level manifest, *!, and t+pe metadata. The primar+ module maintains the set
of reJuired secondar+ modules )ithin the assem$l+ manifest.
MyA((#dll
*igure 1.& Single-ile Assembly
*n other )ords, multifile assem$lies are used )hen different modules of the application are )ritten in
different languages. Multifile assem$lies make the do)nloading process more efficient. The+ ena$le +ou
to store the seldom used t+pes in separate modules and do)nload them onl+ )hen needed. The multifile
assem$l+ sho)n in 0igure 1.A consists of three files. The M+'pp.dll file contains the assem$l+ manifest
for the multifile assem$l+. The M+!i$.netmodule file contains the t+pe metadata and the MS*! code $ut
not the assem$l+ manifest. The .mplo+ee.gif is the resource file for this multifile assem$l+.
M+'pp.dll
M+!i$.netmodule .mplo+ee.gif
*igure 1.9 !ultiile Assembly
R.V.COLLEGE OF ENGINEERING Page 1A
Asse&bly Metadata
'es%urces
CIL C%de
Ty(e Metadata
CIL
Ty(e Metadata
Asse&bly Mani)est
CIL
Ty(e Metadata
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Thus, an assem$l+ is reall+ a logical grouping of one or more related modules that are intended to $e
initiall+ deplo+ed and versioned as a single unit.
1.F T2e 4ole o" Common ntermediate #anguage
*! is a language that sits a$ove an+ particular platform4specific instruction set. "egardless of )hich
.N.T4a)are language +ou choose (like &, 2B.N.T, 2HH.N.T etc#, the associated compiler produces
*! instructions. (nce the & compiler (csc.e/e# compiles the source code file, +ou end up )ith a single4
file K.e/e assem$l+ that contains a manifest, *! instructions, and metadata descri$ing each aspect of the
program#
,ene"its o" C#
The $enefits of compiling source code into *! rather than directl+ to a specific instruction set are as
given $elo)6
!anguage integration6 .ach .N.T4a)are compiler produces nearl+ identical *! instructions.
Therefore, all languages are a$le to interact )ithin a )ell4defined $inar+ arena.
1iven that *! is platform4agnostic, the .N.T 0rame)ork itself is platform4agnostic. So a single
code $ase can run on numerous operating s+stems, 7ust like Iava.
There is an international standard for the & language, and a large su$set of the .N.T platform and
implementations alread+ e/ist for man+ non4%indo)s operating s+stems. *n contrast to Iava, the .N.T
allo)s +ou to $uild applications using +our language of choice.
1.1G T2e 4ole .NET Ty!e Metadata
R.V.COLLEGE OF ENGINEERING Page 1B
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
*n addition to *! instructions, a .N.T assem$l+ contains full, complete, and accurate metadata. 0e)
points a$out metadata are descri$ed hereunder6
The metadata descri$es each and ever+ t+pe (class, structure, enumeration etc.# defined in the
$inar+, as )ell as the mem$ers of each t+pe (properties, methods, events etc.#.
*t is al)a+s the 7o$ of the compiler (not the programmer# to produce the latest and greatest t+pe
metadata.
's .N.T metadata is so careful, assem$lies are completel+ self4descri$ing entities and so .N.T
$inaries have no need to $e registered into the s+stem registr+.
Metadata is used $+ numerous aspects of the .N.T runtime environment, as )ell as $+ various
development tools.
0or e/ample, the *ntelliSense feature provided $+ 2isual Studio =GGB is made possi$le $+ reading
an assem$l+9s metadata at design time.
Metadata is also used $+ various o$7ect $ro)sing utilities, de$ugging tools, and the & compiler
itself.
To $e sure, metadata is the $ack$one of numerous .N.T technologies including remoting,
reflection, late $inding, >M! )e$ services, and o$7ect seriali8ation.
1.11 T2e 4ole (ssembly Mani"est
The .N.T assem$l+ also contains metadata that descri$es the assem$l+ itself, technicall+ termed a
maniest. 'mong other details, the manifest documents all e/ternal assem$lies reJuired $+ the current
assem$l+ to function correctl+, the assem$l+9s version num$er, cop+rig ht information, and so on. !ike
t+pe metadata, it is al)a+s the 7o$ of the compiler to generate the assem$l+9s manifest. The manifest
documents the list of e/ternal assem$lies reJuired $+ K.e/e(via the .assem$l+ e/tern directive# as )ell as
various characteristics of the assem$l+ itself (version num$er, module name, and so on#.
R.V.COLLEGE OF ENGINEERING Page 1C
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1.1= Com!iling C# to Plat"orm8S!eci"ic nstructions
Since assem$lies contain *! instructions, rather than platform4specific instructions, *! code must $e
compiled $efore use. The entit+ that compiles *! code into meaningful PU instructions is termed a
&ust-in-time 5'(T6 compiler, )hich is also kno)n as 'itter. The .N.T runtime environment forces a I*T
compiler for each PU targeting the !", each of )hich is optimi8ed for the platform it is targeting.
0or e/ample, if +ou are $uilding a .N.T application that is to $e deplo+ed to a handheld device (such as a
Pocket P#, the corresponding Iitter is )ell eJuipped to run )ithin a lo)4memor+ environment. (n the
other hand, if +ou are deplo+ing +our assem$l+ to a $ack4end server ()here memor+ is seldom an issue#,
the Iitter )ill $e optimi8ed to function in a high4memor+ environment. *n this )a+, developers can )rite a
single $od+ of code that can $e efficientl+ I*T4compiled and e/ecuted on machines )ith different
architectures. 0urthermore, as a given Iitter compiles *! instructions into corresponding machine code,
it )ill cache the results in memor+ in a manner suited to the target operating s+stem. *n this )a+, if a call
is made to a method named Print,ocument(#, the *! instructions are compiled into platform4specific
instructions on the first invocation and retained in memor+ for later use. Therefore, the ne/t time
Print,ocument(# is called, there is no need to recompile the *!.
1.1@ Summary
The point of this chapter )as to la+ out the conceptual frame)ork necessar+ for understanding the
su$7ect. %e $egan $+ e/amining a num$er of limitations and comple/ities found )ithin the technologies
prior to .N.T and follo)ed up )ith an overvie) of ho).N.T and & attempts to simplif+ the current
state of affairs. The !" is a$le to host an+ .N.T $inar+?assem$l+ that a$ides $+ the rules of managed
code. 's +ou have seen, assem$lies contain *! instructions (in addition to t+pe metadata and assem$l+
manifest# that are compiled to platform4specific instructions using a 7ust4in4time (I*T# compiler.
1.1A :ey0ords
R.V.COLLEGE OF ENGINEERING Page 1D
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
ommon !anguage "untime (!"#
ommon !anguage Specification (!S#
ommon T+pe S+stem (TS#
Base lass !i$rar+ (B!#
'ssem$lies?Binaries
ommon *ntermediate !anguage (*!#
'ssem$l+ Manifest
T+pe Metadata
Iust4in4Time ompiler (Iitter#
1.1B E;ercises
-# .ith a neat diagra&/ e0(lain the basic building bl%c1 %) #+!T )ra&e2%r1#
3# .hat d% y%u &ean by BCL4 !0(lain#
5# Bring %ut the i&(%rtant di))erences bet2een single and &ulti)ile asse&blies#
6# .hat are the 1ey )eatures %) C*4
7# Brie)ly discuss the state %) a))airs that e8entually led t% the #+!T (lat)%r&# .hat is the
#+!T s%luti%n and 2hat C* brings t% the table4
9# !0(lain the c%nce(t %) #+!T binaries#
:# !0(lain the r%le %) ;IT c%&(iler#
<# !0(lain the r%le %) CIL and the bene)its %) CIL in #+!T (lat)%r&4
R.V.COLLEGE OF ENGINEERING Page 1E
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Module 1
Unit '
CONTENTS:
1.1C ($7ectives
=.= *ntroduction
=.@ Understanding the common t+pe s+stem
=.A *ntrinsic TS ,ata T+pes
=.B Understanding the ommon !anguages Specification
=.C Understanding the ommon !anguage "untime
=.D ' tour of the .Net Namespaces
=.E *ncreasing -our Namespace Nomenclature
=.F ,eplo+ing the .N.T "untime
=.1G Summar+
=.11 :e+)ords
=.1= ./ercises
=.1 Objectives
't the end of this lesson, the students )ill understand the follo)ing tasks in detail6
The ommon T+pe S+stem
TS ,ata t+pes
The ommon !anguage Specification
The ommon !anguage "untime
Namespaces
=.= ntroduction
*n the previous unit, )e have seen the $asic $uilding $locks of .N.T frame)ork. ;ere, )e )ill ela$orate
each of these $uilding $locks in detail. 0or the thorough understanding of .N.T frame)ork and the
R.V.COLLEGE OF ENGINEERING Page 1F
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
languages that can $e )orked on the frame)ork, one should understand the concepts of !", TS and
!S in detail.
=.@ Understanding t2e Common Ty!e System
' given assem$l+ ma+ contain an+ num$er of distinct 3t+pes.5
*n the )orld of .N.T, 3t+pe5 is simpl+ a generic term used to refer to a mem$er from the set
Mclass, structure, interface, enumeration, delegateN.
%hen +ou $uild solutions using a .N.T4a)are language, +ou )ill most likel+ interact )ith each
of these t+pes.
0or e/ample, +our assem$l+ ma+ define a single class that implements some num$er of
interfaces. Perhaps one of the interface methods takes an enumeration t+pe as an input parameter
and returns a structure to the caller.
The ommon T+pe S+stem (TS# is a formal specification that documents ho) t+pes must $e
defined in order to $e hosted $+ the !".
Usuall+, the people )ho )ill $e $uilding tools and?or compilers that target the .N.T platform are
concerned )ith the inner )orkings of the TS.
;o)ever, for all .N.T programmers it is important to learn a$out ho) to )ork )ith the five t+pes
defined $+ the TS in their language of choice.
No), )e )ill discuss the usage of five t+pes defined $+ TS.
CTS Class Ty!es
.ver+ .N.T4a)are language supports, the notion of a class type, )hich is the $asis of o$7ect4oriented
programming (((P#. ' class ma+ $e composed of an+ num$er of mem$ers (such as properties, methods,
and events# and data points. *n &, classes are declared using the class ke+)ord. 0or e/ample,
$$ ( C7 class ty!e
pu$lic class alc
R.V.COLLEGE OF ENGINEERING Page =G
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
pu$lic int 'dd(int /, int +#
M
return / H +O
N
N
TS allo) a given class to support virtual and a$stract mem$ers that define a pol+morphic interface for
derived classes. But TS classes ma+ onl+ derive from a single $ase class (multiple inheritance is not
allo)ed fro class#.
%ll%2ing table lists nu&ber %) characteristics (ertaining t% class ty(es#
Class C2aracteristic Meaning
*s the class 3sealed5 or notP Sealed classes cannot function as a $ase class to other classes.
,oes the class implement an+
interfaces"
'n interface is a collection of a$stract mem$ers that provide a contract
$et)een the o$7ect and o$7ect user. The TS allo)s a class to implement
an+ num$er of interfaces.
*s the class a$stract or concreteP Abstract classes cannot $e directl+ created, $ut are intended to define
common $ehaviors for derived t+pes. #oncrete classes can $e created
directl+.
%hat is the 3visi$ilit+5 of this
classP
.ach class must $e configured )ith a visi$ilit+ attri$ute. Basicall+, this
feature defines if the class ma+ $e used $+ e/ternal assem$lies, or onl+ from
)ithin the defining assem$l+ (e.g., a private helper class#.
CTS Structure Ty!es
The concept of a structure is also formali8ed under the TS.
Structure is a user4defined t+pe (U,T#, )hich can $e thought of as a light)eight class t+pe
having value4$ased semantics.
TS structures ma+ define an+ num$er of parameteri$ed constructors.
TS structures are derived from a common $ase class6 $ystem.)alueType
R.V.COLLEGE OF ENGINEERING Page =1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
This $ase class configures a t+pe to $ehave as a stack4allocated entit+ rather than a heap4allocated
entit+.
The TS permits structures to implement an+ num$er of interfacesO $ut, structures ma+ not
$ecome a $ase t+pe to an+ other classes or structures. Therefore structures are e/plicitl+ sealed.
T+picall+, structures are $est suited for modeling geometric and mathematical data, and are
created in & using the struct ke+)ord.
onsider an e/ample6
$$ ( C7 structure ty!e
struct Point
M
$$ Structures can contain "ields.
pu$lic int /Pos, +PosO
$$ Structures can contain !arameteri<ed constructors.
pu$lic Point(int /, int +#
M
/Pos Q /O
+Pos Q +O
N
$$ Structures may de"ine met2ods.
pu$lic void ,ispla+(#
M
onsole.%rite!ine(R(MGN, M1N#R, /Pos, +Pos#O
N
N
R.V.COLLEGE OF ENGINEERING Page ==
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
CTS nter"ace Ty!es
Interfaces are nothing more than a named collection of a$stract mem$er definitions, )hich ma+
$e supported (i.e., implemented# $+ a given class or structure.
*nterfaces are the onl+ .N.T t+pe that does not derive from a common $ase t+pe.
This indicates that interfaces are pure protocol and do not provide an+ implementation.
(n their o)n, interfaces are of little use. ;o)ever, )hen a class or structure implements a given
interface, +ou are a$le to reJuest access to the supplied functionalit+ using an interface reference
in a pol+morphic manner.
%hen +ou create custom interfaces using a .N.T a)are programming language, the TS permits
a given interface to derive from multiple $ase interfaces.
This allo)s to $uild some interesting $ehaviors.
*n &, interface t+pes are defined using the interace ke+)ord, for e/ample6
$$ ( C7 inter"ace ty!e.
pu$lic interface *,ra)
M
void ,ra)(#O
N
CTS Enumeration Ty!es
Enumerations are a hand+ programming construct that allo)s +ou to group name?value pairs
under a specific name.
B+ default, the storage used to hold each item )ithin enumeration t+pe is a @=4$it integer
(S+stem.*nt@=#.
;o)ever, it is possi$le to alter this storage slot if needed (e.g., )hen programming for a lo)4
memor+ device such as a Pocket P#.
The TS demands that enumerated t+pes derive from a common $ase class, S+stem..num. This
$ase class defines a num$er of interesting mem$ers that allo) +ou to e/tract, manipulate, and
transform the underl+ing name?value pairs programmaticall+.
*n &, enumerations are defined using the ke+)ord enum.
R.V.COLLEGE OF ENGINEERING Page =@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsider an e/ample of creating a video4game application that allo)s the pla+er to select one of three
character categories (%i8ard, 0ighter, or Thief#. "ather than keeping track of ra) numerical values to
represent each possi$ilit+, +ou could $uild a custom enumeration as6
// A C# enumeration type
(ublic enu& CharacterTy(e
=
.i>ard ? -@@/
ighter ? 3@@/
Thie) ? 5@@
A
CTS 1elegate Ty!es
%elegates are the .N.T eJuivalent of a t+pe4safe 4st+le function pointer.
The ke+ difference is that a .N.T delegate is a class that derives from S+stem.Multicast,elegate,
rather than a simple pointer to a ra) memor+ address.
,elegates are useful )hen +ou )ish to provide a )a+ for one entit+ to for)ard a call to another
entit+.
,elegates provide intrinsic support for multicasting, i.e. for)arding a reJuest to multiple
recipients.
The+ also provide as+nchronous method invocations.
The+ provide the foundation for the .N.T event architecture.
. *n &, delegates are declared using the delegate ke+)ord as sho)n in the follo)ing e/ample6
$$ T2is C7 delegate ty!e can =!oint to= any met2od
$$ returning an integer and ta3ing t0o integers as in!ut.
pu$lic delegate int Binar+(p(int /, int +#O
R.V.COLLEGE OF ENGINEERING Page =A
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
CTS Ty!e Members
%e have seen till no) that most t+pes in TS can take an+ num$er of members. 0ormall+ speaking, a
type member is constrained $+ the set Mconstructor, finali8er, static constructor, nested t+pe, operator,
method, propert+, inde/er, field, read onl+ field, constant, eventN. The TS defines various 3adornments5
that ma+ $e associated )ith a given mem$er. 0or e/ample, each mem$er has a given visi$ilit+ feature
(e.g., pu$lic, private, protected#. Some mem$ers ma+ $e declared as a$stract to enforce a pol+morphic
$ehavior on derived t+pes as )ell as virtual to define a canned ($ut overrida$le# implementation. 'lso,
most mem$ers ma+ $e configured as static ($ound at the class level# or instance ($ound at the o$7ect
level#. The construction of t+pe mem$ers is e/amined later in detail.
=.A ntrinsic CTS 1ata Ty!es
TS provide a )ell4defined set of intrinsic data t+pes used $+ all .N.T a)are languages. 'lthough a
given language t+picall+ has a uniJue ke+)ord used to declare an intrinsic TS data t+pe, all language
ke+)ords ultimatel+ resolve to the same t+pe defined in an assem$l+ named mscorli$.dll.
0ollo)ing ta$le lists ho) ke+ TS data t+pes are e/pressed in various .N.T languages#
.NET ,ase Ty!e 5CTS
1ata Ty!e6
+,.NET :ey0ord C7 :ey0ord Managed E;tensions "or
C)) :ey0ord
S+stem.B+te B+te $+te unsigned char
S+stem.SB+te SB+te s$+te signed char
S+stem.*nt1C Short short short
S+stem.*nt@= *nteger int int or long
S+stem.*ntCA !ong long SSintCA
S+stem.U*nt1C UShort ushort unsigned short
S+stem.U*nt@= U*nteger uint unsigned int or unsigned
long
S+stem.U*ntCA U!ong ulong unsigned SSintCA
S+stem.Single Single float 0loat
S+stem.,ou$le ,ou$le dou$le ,ou$le
S+stem.($7ect ($7ect o$7ect ($7ectT
R.V.COLLEGE OF ENGINEERING Page =B
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
S+stem.har har char )charSt
S+stem.String String string StringT
S+stem.,ecimal ,ecimal decimal ,ecimal
S+stem.Boolean Boolean $ool Bool
=.B Understanding Common #anguage S!eci"ication
%e kno) that, different languages e/press the same programming constructs in uniJue, language specific
terms. 0or e/ample, in & +ou denote string concatenation using the plus operator (H#, )hile in 2B .N.T
)e use the ampersand (U#. .ven )hen t)o distinct languages e/press the same programmatic idiom (e.g.,
a function )ith no return value#, the chances are ver+ good that the s+nta/ )ill appear Juite different on
the surface6
= +, .NET met2od returning not2ing.
Pu$lic Su$ M+Method(#
= Some code...
.nd Su$
$$ C7 met2od returning not2ing.
pu$lic void M+Method(#
M
$$ Some code...
N
Since the respective compilers (like v$c.e/e and csc.e/e# produce similar *! instructions, the variation
in s+nta/ is minor for .N.T runtime. ;o)ever, languages can also differ )ith regard to their overall level
of functionalit+. 0or e/ample, & ma+ allo) to overload some t+pe of operator )hich 2B.N.T ma+ not.
R.V.COLLEGE OF ENGINEERING Page =C
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1iven these possi$le variations, it )ould $e ideal to have a $aseline to )hich all .N.T4a)are languages
are e/pected to conform.
The ommon !anguage Specification (!S# is a set of rules that descri$e the small and complete set of
features. These features are supported $+ a .N.T4a)are compiler to produce a code that can $e hosted $+
!". 'lso, this code can $e accessed $+ all languages in the .N.T platform.
*n man+ )a+s, the !S can $e vie)ed as a subset of the full functionalit+ defined $+ the TS. The !S
is ultimatel+ a set of rules that compiler $uilders must follo), if the+ plan their products to function
properl+ )ithin the .N.T universe. .ach rule descri$es ho) this rule affects those )ho $uild the
compilers as )ell as those )ho interact )ith them. 0or e/ample, the !S "ule 1 sa+s6
#ule *: !S rules appl+ onl+ to those parts of a t+pe that are e/posed outside the defining assem$l+.
1iven this rule, )e can understand that the remaining rules of the !S do not appl+ to the logic used to
$uild the inner )orkings of a .N.T t+pe. The onl+ aspects of a t+pe that must match to the !S are the
mem$er definitions themselves (i.e., naming conventions, parameters, and return t+pes#. The
implementation logic for a mem$er ma+ use an+ num$er of non4!S techniJues, as the outside )orld
)on9t kno) the difference.
To illustrate, the follo)ing 'dd(# method is not !S4compliant, as the parameters and return values make
use of unsigned data ()hich is not a reJuirement of the !S#6
pu$lic class alc
M
$$ E;!osed unsigned data is not C#S com!liant>
pu$lic ulong 'dd(ulong /, ulong +#
R.V.COLLEGE OF ENGINEERING Page =D
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
return / H +O
N
N
%e can make use of unsigned data internall+ as follo)s6
pu$lic class alc
M
pu$lic int 'dd(int /, int +#
M
$$ (s t2is ulong variable is only used internally?
$$ 0e are still C#S com!liant.
ulong tempO
tempQ /H+O
return tempO
N
N
No), )e have a match to the rules of the !S, and can assured that all .N.T languages are a$le to invoke
the 'dd(# method.
*n addition to "ule 1, the !S defines numerous other rules. 0or e/ample, the !S descri$es ho) a given
language must represent te/t strings, ho) enumerations should $e represented internall+ (the $ase t+pe
used for storage#, ho) to define static mem$ers, and so on. But the internal understanding of the TS and
!S specifications is for tool?compiler $uilders.
R.V.COLLEGE OF ENGINEERING Page =E
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Ensuring C#S Com!liance
& does define a num$er of programming constructs that are not !S4compliant. But, )e can instruct the
& compiler to check the code for !S compliance using a single .N.T attri$ute6
$$ Tell t2e C7 com!iler to c2ec3 "or C#S com!liance.
Vassem$l+6 S+stem.!Sompliant(true#W
This statement must $e placed outside the scope of an+ namespace. The V!SompliantW attri$ute )ill
instruct the & compiler to check each and ever+ line of code against the rules of the !S. *f an+ !S
violations are discovered, )e )ill receive a compiler error and a description of the offending code.
=.C Understanding Common #anguage 4untime
Programmaticall+ speaking, the term runtime can $e understood as a collection of e/ternal services that
are reJuired to e/ecute a given compiled unit of code. 0or e/ample, )hen developers make use of the
Microsoft 0oundation lasses (M0# to create a ne) application, the+ are a)are that their program
reJuires the M0 runtime li$rar+ (i.e., mfcA=.dll#. (ther popular languages also have a corresponding
runtime. 2BC programmers are also tied to a runtime module (e.g., msv$vmCG.dll#. Iava developers are
tied to the Iava 2irtual Machine (I2M# and so on.
The .N.T platform offers a runtime s+stem, )hich can $e descri$ed as follo)s6
The ke+ difference $et)een the .N.T runtime and the various other runtimes is that the .N.T runtime
provides a single )ell4defined runtime la+er that is shared $+ all languages and platforms that are
.N.T4a)are.
The root of the !" is ph+sicall+ represented $+ a li$rar+ named mscoree.dll (ommon ($7ect
"untime ./ecution .ngine#.
R.V.COLLEGE OF ENGINEERING Page =F
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
%hen an assem$l+ is referenced for use, mscoree.dll is loaded automaticall+, )hich in turn loads the
reJuired assem$l+ into memor+.
The runtime engine is responsi$le for a num$er of tasks.
0irst and foremost, it is the entit+ in4charge of resolving the location of an assem$l+ and finding the
reJuested t+pe )ithin the $inar+ $+ reading the contained metadata.
The !" then la+s out the t+pe in memor+, compiles the associated *! into platform4specific
instructions, performs an+ necessar+ securit+ checks, and then e/ecutes the code in Juestion.
*n addition to loading +our custom assem$lies and creating +our custom t+pes, the !" )ill also
interact )ith the t+pes contained )ithin the .N.T $ase class li$raries )hen reJuired.
'lthough the entire $ase class li$rar+ has $een $roken into a num$er of discrete assem$lies, the ke+
assem$l+ is mscorli$.dll. The mscorli$.dll contains a large num$er of core t+pes that encapsulate a )ide
variet+ of common programming tasks as )ell as the core data t+pes used $+ all .N.T languages. %hen
+ou $uild .N.T solutions, +ou automaticall+ have access to this particular assem$l+.
0igure =.1 illustrates the )orkflo) that takes place $et)een the source code ()hich is making use of $ase
class li$rar+ t+pes#, a given .N.T compiler, and the .N.T e/ecution engine.
R.V.COLLEGE OF ENGINEERING Page @G
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
R.V.COLLEGE OF ENGINEERING Page @1
#+!T s%urce
c%de 2ritten
in s%&e
#+!TBa2are
Language
Base Class
Libraries
"&sc%rlib#dll
and s% %n$
S%&e #+!T
c%&(iler
DLL %r !X!
Asse&bly
"CIL/ Metadata and
Mani)est$
.NET Execution Engine (mscoree.dll)
Class L%ader
;itter
Plat)%r&B
S(eci)ic
Instructi%ns
!0ecute the
a((licati%n
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
*igure '.1 mscoree.dll in action
=.D ( Tour o" t2e .NET Names!aces
Unlike , HH and Iava, the & language does not provide an+ language4specific code li$rar+. *nstead,
& provides the language4neutral .N.T li$raries. To keep all the t+pes )ithin the $ase class li$raries,
the .N.T platform makes e/tensive use of the namespace concept. ' namespace is a grouping of related
t+pes contained in an assem$l+. *n other )ords, namespace is a )a+ to group semanticall+ related t+pes
(classes, enumerations, interfaces, delegates and structures# under a single um$rella. 0or e/ample, the
S+stem.*( namespace contains file *?( related t+pes, the S+stem.,ata namespace defines $asic data$ase
t+pes, and so on. *t is ver+ important to point out that a single assem$l+ (such as mscorli$.dll# can contain
an+ num$er of namespaces, each of )hich can contain an+ num$er of t+pes.
The advantage of having namespaces is that, an+ language targeting the .N.T runtime makes use of same
namespaces and same t+pes as a & developer. 0or e/ample, consider follo)ing programs )ritten in &,
2B.N.T and MHH.
$$ C7 code
R.V.COLLEGE OF ENGINEERING Page @=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
using S+stemO
pu$lic class Test
M
pu$lic static void Main(#
M
onsole.%rtie!ine(3;ello %orld5#O
N
N
$$ +,.NET code
*mports S+stem
Pu$lic Module Test
Su$ Main(#
onsole.%rtie!ine(3;ello %orld5#
.nd Su$
.nd Module
$$ MC)) code
&using Xmscorli$.dllY
using namespace S+stemO
void Main(#
M
onsole66%rtie!ine(3;ello %orld5#O
N
R.V.COLLEGE OF ENGINEERING Page @@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Note that each language is making use of #onsole class defined in the System namespace. 'part from
minor s+ntactic variations, three programs look ver+ similar, $oth ph+sicall+ and logicall+.
There are numerous $ase class namespaces )ithin .N.T. The most fundamental namespace is System.
The System namespace provides a core $od+ of t+pes that the programmer need to control time. *n fact,
one cannot $uild an+ sort of functional & application )ithout at least making a reference to the S+stem
namespace. 0ollo)ing ta$le sho)s some of the namespaces6
.NET Names!ace Meaning
S+stem S+stem contains numerous useful t+pes dealing )ith intrinsic data,
mathematical computations, random num$er generation, environment
varia$les, and gar$age collection, as )ell as a num$er of commonl+
used e/ceptions and attri$utes.
S+stem.ollections These namespaces define a num$er of stock container o$7ects
S+stem.ollections.1eneric ('rra+!ist, Zueue etc#, as )ell as $ase t+pes and interfaces that allo)
+ou to $uild customi8ed collections. 's of .N.T =.G, the collection
t+pes have $een e/tended )ith generic capa$ilities.
S+stem.,ata
S+stem.,ata.(d$c
S+stem.,ata.(raclelient
S+stem.,ata.(le,$
S+stem.,ata.SJllient
These namespaces are used for interacting )ith data$ases using
',(.N.T.
S+stem.,iagnostics ;ere, +ou find numerous t+pes that can $e used to programmaticall+
de$ug and trace +our source code.
S+stem.,ra)ing
S+stem.,ra)ing.,ra)ing=,
S+stem.,ra)ing.Printing
;ere, +ou find numerous t+pes )rapping graphical primitives such as
$itmaps, fonts, and icons, as )ell as printing capa$ilities.
S+stem.*(
S+stem.*(.ompression
S+stem.*(.Ports
These namespaces include file *?(, $uffering, and so forth. 's of .N.T
=.G, the *( namespaces no) include support compression and port
manipulation.
S+stem.Net This namespace (as )ell as other related namespaces# contains t+pes
related to net)ork programming (reJuests?responses, sockets, end
points, and so on#.
S+stem."eflection
S+stem."eflection..mit
These namespaces define t+pes that support runtime t+pe discover+ as
)ell as d+namic creation of t+pes.
S+stem."untime.*nteropServices This namespace provides facilities to allo) .N.T t+pes to interact )ith
3unmanaged code5 (e.g., 4$ased ,!!s and (M servers# and vice
versa.
S+stem."untime.
"emoting
This namespace (among others# defines t+pes used to $uild solutions
that incorporate the .N.T remoting la+er.
S+stem.Securit+ Securit+ is an integrated aspect of the .N.T universe. *n the securit+4
centric namespaces +ou find numerous t+pes dealing )ith permissions,
cr+ptograph+, and so on.
S+stem.Threading This namespace defines t+pes used to $uild multithreaded applications.
S+stem.%e$ ' num$er of namespaces are specificall+ geared to)ard the
R.V.COLLEGE OF ENGINEERING Page @A
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
development of .N.T )e$ applications, including 'SP.N.T and >M!
)e$ services.
S+stem.%indo)s.0orms This namespace contains t+pes that facilitate the construction of
traditional desktop 1U* applications.
S+stem.>ml The >M!4centric namespaces contain numerous t+pes used to interact
)ith >M! data.
(ccessing a Names!ace Programmatically
' namespace is a convenient )a+ to logicall+ understand and organi8e related t+pes. onsider the S+stem
namespace. 0rom programmer9s perspective, S+stem.onsole represents a class named #onsole that is
contained )ithin a namespace called System. ;o)ever, in the e+es of the .N.T runtime, it is a single
entit+ named System.#onsole.
*n &, the using ke+)ord simplifies the process of referencing t+pes defined in a particular namespace. *n
a traditional desktop application, )e can include an+ num$er of namespaces like <
using S+stemO // General base class library ty(es#
using S+stem.,ra)ingO // Gra(hical rendering ty(es#
(nce )e specif+ a namespace, )e can create instances of the t+pes the+ contain. 0or e/ample, if )e are
interested in creating an instance of the Bitmap class, )e can )rite6
using S+stemO
using S+stem.,ra)ingO
class M+'pp
M
pu$lic void ,ispla+!ogo(#
M
$$ create a '.;'. !i;el bitma!.
R.V.COLLEGE OF ENGINEERING Page @B
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Bitmap $m Q ne) Bitmap(=G, =G#O
...
N
N
's this application is referencing S+stem.,ra)ing, the compiler is a$le to resolve the Bitmap class as a
mem$er of this namespace. *f )e do not specif+ the S+stem.,ra)ing namespace, )e )ill get a compiler
error. ;o)ever, )e can declare varia$les using a fully &ualified name as )ell6
using S+stemO
class M+'pp
M
pu$lic void ,ispla+!ogo(#
M
$$ Using "ully @uali"ied name.
S+stem.,ra)ing.Bitmap $m Qne) S+stem.,ra)ing.Bitmap(=G, =G#O
...
N
N
"emem$er that $oth the approaches (a short4hand method )ith using and making use of full+ Jualified
name# results in the e'act same underl+ing *! and has no effect on performance or the si8e of the
assem$l+.
R.V.COLLEGE OF ENGINEERING Page @C
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
=.E ncreasing Aour Names!ace Nomenclature
There are thousands of namespaces in .N.T frame)ork. But )hat makes a namespace uniJue is that the
t+pes it defines are all someho) semantically related. So, depending on our reJuirement, )e can make
use of onl+ reJuired namespaces. 0or e/ample, if )e are $uilding console applications, then )e need not
)orr+ a$out System.(indows.orms and System.%rawing namespaces. To kno) more a$out specific
namespaces, )e can use an+ one of the follo)ing6
.N.T S,: online documentation (MS,N < Microsoft ,eveloper Net)ork#
The ildasm.e/e utilit+
The lass 2ie)er %e$ application
The )incv.e/e desktop application
The 2isual Studio.N.T integrated ($7ect Bro)ser
=.F 1e!loying t2e .NET 4untime
The .N.T assem$lies can $e e/ecuted onl+ on a machine that has the .N.T 0rame)ork installed. 's an
individual )ho $uilds .N.T soft)are, this should never $e an issue, as +our development machine )ill $e
properl+ configured at the time +ou install the freel+ availa$le .N.T 0rame)ork =.G S,: or a
commercial .N.T development environments such as 2isual Studio =GGB.
But, )e can not cop+ and run a .N.T application in a computer in )hich .N.T is not installed. ;o)ever,
if +ou deplo+ an assem$l+ to a computer that does not have .N.T installed, it )ill fail to run. 0or this
reason, Microsoft provides a setup package named dotnetx.exe that can $e freel+ shipped and installed
along )ith +our custom soft)are. This installation program is included )ith the .N.T 0rame)ork =.G
S,:, and it is also freel+ do)nloada$le from ))).microsoft.com.
R.V.COLLEGE OF ENGINEERING Page @D
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
(nce dotnetf/.e/e is installed, the target machine )ill no) contain the .N.T $ase class li$raries, .N.T
runtime (mscoree.dll#, and additional .N.T infrastructure (such as the 1', 1lo$al 'ssem$l+ ashe#.
Note that if +ou are $uilding a .N.T )e$ application, the end user9s machine does not need to $e
configured )ith the .N.T 0rame)ork, as the $ro)ser )ill simpl+ receive generic ;TM! and possi$l+
client4side IavaScript#
=.1G Summary
*n this Unit, )e have e/plored the TS, !" and !S in detail. %e have e/amined a num$er of tools
that allo) +ou to check out the t+pes )ithin a given .N.T namespace. %e )rapped up )ith a $rief
e/amination of the process of configuring a given machine to host the .N.T runtime. %ith this necessar+
pream$le complete, +ou can no) $egin to $uild .N.T assem$lies using &.
=.11 :ey0ords
Structure
.numeration
lass
*nterface
,elegate
Microsoft ommon ($7ect "untime ./ecution .ngine (mscoree#
Namespaces
using
=.1= E;ercises
-# .hat are na&es(aces4 List and e0(lain the (ur(%se %) at least )i8e na&es(aces#
3# !0(lain 2ith a neat diagra&/ the 2%r1)l%2 that ta1es (lace bet2een y%ur s%urce c%de/ a
gi8en #+!T c%&(lier and the #+!T e0ecuti%n engine#
5# !0(lain c%&&%n ty(e syste& in detail#
6# .hat are basic CTS data ty(es4 !0(lain#
R.V.COLLEGE OF ENGINEERING Page @E
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Module 1
Unit &
CONTENTS:
1.1D ($7ectives
@.= *ntroduction
@.@ "ole of ommand !ine ompiler (csc.e/e#
@.A Building & 'pplications using csc.e/e
@.B %orking )ith csc.e/e "esponse 0iles
@.C 1enerating Bug "eports
@.D "emaining & ompiler (ptions
@.E The ommand !ine ,e$ugger (cord$g.e/e#
@.F Using the 2isual Studio.N.T *,.
@.1G The & 3Pre4processor5 ,irectives
@.11 'n *nteresting 'side6 S+stem..nvironment lass
@.1= Summar+
@.1@ :e+)ords
@.1A ./ercises
@.1 Objectives
't the end of this lesson, the students )ill understand the follo)ing tasks in detail6
The "ole of ommand !ine ompiler
R.V.COLLEGE OF ENGINEERING Page @F
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Building 'pplications using csc.e/e
"esponse files
Bug "eports
ompiler (ptions
ommand !ine ,e$ugger
@.= ntroduction
& is one of man+ possi$le languages )hich ma+ $e hosted $+ 2isual Studio.N.T (2S.N.T#. Unlike
previous editions of Microsoft *,.s (*ntegrated ,evelopment .nvironments#, the professional and
enterprise versions of 2S.N.T ma+ $e used to $uild various t+pes of pro7ects like &, I&, 2B.N.T, MH
H and so on. *n this unit, )e )ill e/amine ra) & compiler. %e )ill see ho) to set up environment
varia$les to run & applications using command line compiler, ho) to generate $ug reports, ho) to
generate response files, )hat are preprocessor directives and so on. This unit also offers a grand tour of
the ke+ features of the 2S.N.T *,. )ithin the conte/t of &.
@.@ T2e 4ole o" Command #ine Com!iler 5csc.e;e6
There are a num$er of techniJues to compile & source code. (ne )a+ is to use the & command4line
compiler, csc.exe ()here csc stands for #-S)arp #ompiler#. This tool is included )ith the .N.T
0rame)ork =.G S,:. Though )e ma+ not $uild a large4scale application using the command4line
compiler, it is important to understand the $asics of ho) to compile K.cs files $+ hand. 0e) reasons for
having a grip on the process are6
The most o$vious reason is the simple fact that one ma+ not have a cop+ of 2isual Studio =GGB.
But onl+ free .N.T S,:.
(ne ma+ plan to make use of automated $uild tools such as MSBuild or N'nt.
(ne ma+ )ant to understand & deepl+. %hen +ou use graphical *,.s to $uild applications, +ou
are ultimatel+ instructing csc.e/e ho) to manipulate +our & input files. *n this light, it is $etter
to see )hat takes place $ehind the scenes.
R.V.COLLEGE OF ENGINEERING Page AG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
'nother $enefit of )orking )ith csc.e/e is that +ou $ecome that much more comforta$le in
manipulating other command4line tools included )ith the .N.T 0rame)ork =.G S,:. Moreover,
a num$er of important utilities are accessi$le onl+ from the command line.
Con"iguring t2e C7 Command8#ine Com!iler
Before starting the & command4line compiler, )e need to ensure that our development machine
recogni8es the e/istence of csc.e/e. *f the machine is not configured correctl+, )e have to specif+ the full
path to the director+ containing csc.e/e $efore compiling & files. %e have to set the path $+ follo)ing
the steps6
1. "ight4click the M+ omputer icon and select Properties from the pop4up menu.
'. Select the 'dvanced ta$ and click the .nvironment 2aria$les $utton.
&. ,ou$le4click the Path varia$le from the S+stem 2aria$les list $o/.
9. 'dd the follo)ing line to the end of the current Path value6
6[%indo)s[Microsoft.N.T[0rame)ork[v=.G.BG=1B
Note that, the a$ove line ma+ not $e e/actl+ the same in ever+ computer. %e must enter the current
version and location of .N.T 0rame)ork S,:. To check )hether the setting has $een done properl+ or
not, open a command prompt and t+pe
csc 4P (r csc ?P
*f settings )ere correct, )e )ill see a list of options supported $+ the & compiler.
Con"iguring (dditional .NET Command8#ine Tools
%e have to set Path varia$le )ith one more line as
6[Program 0iles[Microsoft 2isual Studio E[S,:[v=.G[Bin
R.V.COLLEGE OF ENGINEERING Page A1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
This director+ contains additional command4line tools that are commonl+ used during .N.T development.
%ith these t)o paths esta$lished, )e )ill $e a$le to run an+ .N.T utilit+ from an+ command )indo). To
confirm this ne) setting, enter the follo)ing command in a command prompt to vie) the options of the
1' (glo$al assem$l+ cashe# utilit+, gacutil.e/e6
gacutil 4P
Note that the ab%8e e0(lained &eth%d is t% c%&(ile the C* (r%gra& in any c%&&and (r%&(t# In
stead %) that/ 2e can directly use the SDC in the Disual Studi% T%%ls &enu#
@.A ,uilding C7 (!!lications Using csc.e;e
To $uild a simple & application, open a notepad and t+pe the follo)ing code6
$$ ( sim!le C7 a!!lication.
using S+stemO
class Test
M
pu$lic static void Main(#
M
onsole.%rite!ine(R;ello %orldLLLR#O
N
N
No), save this file in an+ convenient location as Test.cs. No), )e have to provide the option for )hich
t+pe of output file )e )ant. The options for output are given in the follo)ing ta$le6
*ile Out!ut
O!tion
Meaning
R.V.COLLEGE OF ENGINEERING Page A=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
?out This option is used to specif+ the name of the assem$l+ to $e created. B+ default, the
assem$l+ name is the same as the name of the initial input K.cs 4file (in the case of a
K.dll# or the name of the t+pe containing the program9s Main(# method (in the case of
an K.e/e#.
?target6e/e This option $uilds an e/ecuta$le console application. This is the default file output
t+pe, and thus ma+ $e omitted )hen $uilding this application t+pe.
?target6li$rar+ This option $uilds a single4file K.dll assem$l+.
?target6module This option $uilds a module.Modules are elements of multifile assem$lies.
?target6)ine/e 'lthough +ou are free to $uild %indo)s4$ased applications using the ?target6e/e
flag, the ?target6)ine/e flag prevents a console )indo) from appearing in the
$ackground.
To compile Test'pp.cs, use the command6
csc ?target:e;e Test.cs
Most of the & compilers support an a$$reviated version, such as ?t rather than ?target. Moreover, ?target
is a default option. So, )e can give simpl+,
csc Test.cs
No) an e/e file )ill $e created )ith the name Test.e/e. No) the program can $e run $+ t+ping <
Test.e/e
at the command prompt.
4e"erencing E;ternal (ssemblies
;ere )e )ill see ho) to compile an application that makes use of t+pes defined in a separate .N.T
assem$l+. Note that mscorli$.dll is automatically referenced during the compilation process. To illustrate
the process of referencing e/ternal assem$lies, consider an e/ample <
using S+stemO
using S+stem.%indo)s.0ormsO
class Test
M
R.V.COLLEGE OF ENGINEERING Page A@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic static void Main(#
M
MessageBo/.Sho)(R;ello...R#O
N
N
Since )e have made use of the MessageBo/ class, )e must specif+ the S+stem.%indo)s.0orms.dll
assem$l+ using the ?reference flag )hich can $e a$$reviated to ?r as <
csc ?r:System.%indo0s.*orms.dll Test.cs
No), running the application )ill give the output as <
Com!iling Multi!le Source *iles 0it2 csc.e;e
%hen )e have more than one K.cs source file, then )e can compile them together. 0or illustration,
consider the follo)ing e/ample <
0ile Name6 M+Test.cs
using S+stemO
using S+stem.%indo)s.0ormsO
R.V.COLLEGE OF ENGINEERING Page AA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
class M+Test
M
pu$lic void displa+(#
M
MessageBo/.Sho)(R;ello...R#O
N
N
0ile Name6 Test.cs
using S+stemO
class Test
M
pu$lic static void Main(#
M
M+Test t Q ne) M+Test (#O
t.displa+(#O
N
N
%e can compile & files $+ listing each input file e/plicitl+6
csc ?r6S+stem.%indo)s.0orms.dll Test.cs MyTest.cs
's an alternative, the & compiler allo)s +ou to make use of the )ildcard character (K# to inform csc.e/e
to include all K.cs files contained in the pro7ect director+6
R.V.COLLEGE OF ENGINEERING Page AB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
csc ?r6S+stem.%indo)s.0orms.dll B.cs
4e"erencing Multi!le E;ternal (ssemblies
*f )e )ant to reference numerous e/ternal assem$lies, then )e can use a semicolon4delimited list. 0or
e/ample6
csc ?r:System.%indo0s.*orms.dllC System.1ra0ing.dll K.cs
@.B %or3ing 0it2 csc.e;e 4es!onse *iles
%hen )e are $uilding comple/ & applications, )e ma+ need to use several flags that specif+ numerous
referenced assem$lies and K.cs input files. To reduce the $urden of t+ping those flags ever+ time, the &
compiler provides response iles. & response files contain all the instructions to $e used during the
compilation of a program. These files end in a K.rsp (response# e/tension.
onsider the follo)ing file, )hich is a response file for the e/ample Test.cs discussed in the previous
section.
# This is the response ile or the Test.exe app
# External assem!ly reerences.
/rESyste&#.ind%2s#%r&s#dll
# output and iles to compile (using "ildcard syntax).
/targetEe0e /%utETest#e0e F#cs
R.V.COLLEGE OF ENGINEERING Page AC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Note that 7 s+m$ol is used for comment line. *f )e have saved this file in the same director+ as the &
source code files to $e compiled, )e have to use follo)ing command to run the program.
csc DTest.rs!
*f needed, )e can specif+ multiple K.rsp files as input (e.g., csc \0irst0ile.rsp \Second0ile.rsp
\Third0ile.rsp#. *n case of multiple response files, the compiler processes the command options as the+
are encountered. Therefore, command4line arguments in a latter K.rsp file can override options in a
previous response file.
'lso note that flags listed e/plicitl+ on the command line $efore a response file )ill $e overridden $+ the
specified K.rsp file. Thus, if )e use the statement,
csc $out:MyCool(!!.e;e \Test.rsp
the name of the assem$l+ )ould still $e Test.e/e (rather than M+ool'pp.e/e#, given the ?out6Test.e/e
flag listed in the Test.rsp response file. ;o)ever, if )e list flags after a response file, the flag )ill
override settings in the response file.
Note The *reference flag is cumulative. "egardless of )here +ou specif+ e/ternal assem$lies ($efore,
after, or )ithin a response file# the end result is a summation of each reference assem$l+.
T2e 1e"ault 4es!onse *ile 5csc.rs!6
R.V.COLLEGE OF ENGINEERING Page AD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
& compiler has an associated default response file (csc.rsp#, )hich is located in the same director+ as
csc.e/e itself (e.g., 6[%indo)s[Microsoft.N.T[0rame)ork[v=.G.BG=1B#. *f )e open this file using
Notepad, )e can see that numerous .N.T assem$lies have alread+ $een specified using the ?r6 flag. %hen
)e are $uilding our & programs using csc.e/e, this file )ill $e automaticall+ referenced, even if )e
provide a custom K.rsp file. Because of default response file, the current Test.e/e application could $e
successfull+ compiled using the follo)ing command set
csc ?out6Test.e/e K.cs
*f )e )ish to disa$le the automatic reading of csc.rsp, )e can specif+ the ?noconfig option6
csc \Test.rsp $nocon"ig
@.C Eenerating ,ug 4e!orts
The & compiler provides a flag named ?$ugreport to specif+ a file that )ill $e populated $+ csc.e/e )ith
various statistics regarding current $uildO including an+ errors encountered during the compilation. The
s+nta/ for using this flag is<
csc ?$ugreport6$ugs.t/t K.cs
%e can enter an+ corrective information for possi$le errors in the program, )hich )ill $e saved to the
specified file. 0or e/ample, consider the program <
using S+stemO
class Test
M
pu$lic static void Main(#
R.V.COLLEGE OF ENGINEERING Page AE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
onsole.%rite!ine(3;ello5# ??note that O is not given
N
N
%hen )e compile this file using ?$ugreport flag, the error message )ill $e displa+ed and corrective action
is e/pected as sho)n <
Test.cs (=@, 11#6 .rror S1GG=6 O e/pected
44444444444444444
Please descri$e the compiler pro$lem6 S
No) if )e enter the statement like
*O4EOT TO TAPE SEMCO#ON
then, the same )ill $e stored in the bugs.t't file.
@.D 4emaining C7 Com!iler O!tions
& compiler has man+ flags that can $e used to control ho) the .N.T assem$l+ to $e generated.
0ollo)ing ta$le lists some of the flags and their meaning.
Command #ine
"lags o" csc.e;e
Meaning
\ 'llo)s to specif+ a response file used during compilation
?P (r ?help Prints the list of all command line flags of csc.e/e
?addmodule Used to specif+ the modules to add to a multifile assem$l+
?$aseaddress Used to specif+ the preferred $ase address at )hich to load a K.dll
?$ugreport Used to $uild te/t4$ased $ug reports for the current compilation
?checked Used to specif+ )hether integer arithmetic that overflo)s the $ounds of the data
R.V.COLLEGE OF ENGINEERING Page AF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
t+pe )ill cause an e/ception at run time
?codepage Used to specif+ the code page to use for all source code files in the compilation
?de$ug 0orces csc.e/e to emit de$ugging information
?define Used to define preprocessor s+m$ols
?doc Used to construct an >M! documentation file
?filealign Specifies the si8e of sections in the output file
?fullpaths Specifies the a$solute path to the file in compiler output
?incremental .na$les incremental compilation of source code files
?li$ Specifies the location of assem$lies referenced via ?reference
?linkresource Used to create a link to a managed resource
?main Specifies )hich Main(# method to use as the program9s entr+ point if multiple
Main(# methods have $een defined in the current K.cs file set.
?nologo Suppresses compiler $anner information )hen compiling the file
?nostdli$ Prevents the automatic importing of the core .N.T li$rar+, mscorli$.dll
?noconfig Prevents the use of K.rsp files during the current compilation
?no)arn Suppress the compiler9s a$ilit+ to generate specified )arnings
?optimi8e .na$le or disa$le optimi8ation
?out Specifies the name of the output file
?recurse Searches su$directories for source files to compile
?reference Used to reference an e/ternal assem$l+
?resource Used to em$ed .N.T resources into the resulting assem$l+
?target Specifies the format of the output file.
?unsafe ompiles code that uses the & 3unsafe5 ke+)ord
?utfEoutput ,ispla+s compiler output using UT04E encoding
?)arn Used to sent )arning level for the compilation c+cle
?)arnaserror Used to automaticall+ promote )arnings to errors
?)in@=icon *nserts an .ico file into the output file
?)in@=res *nserts a %in@=.resource into the output file
@.E T2e Command8#ine 1ebugger 5cordbg.e;e6
The .N.T 0rame)ork S,: provides a command4line de$ugger named cordbg.exe. This tool provides
do8ens of options that allo) +ou to de$ug +our assem$l+. -ou ma+ vie) them $+ specif+ing the ?P flag6
cord$g ?P
R.V.COLLEGE OF ENGINEERING Page BG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
0ollo)ing ta$le lists some of the flags recogni8ed $+ cord$g.e/e ()ith the alternative shorthand notation#
once +ou have entered a de$ugging session.
Command #ine
*lag o" cordbg.e;e
Meaning
$VreakW Set or displa+ current $reakpoints.
delVeteW "emove one or more $reakpoints.
e/VitW ./it the de$ugger
gVoW ontinue de$ugging the current process until hitting ne/t $reakpoint.
oVutW Step out of the current function.
pVrintW Print all loaded varia$les (local, arguments, etc.#.
Si Step into the ne/t line.
So Step over the ne/t line.
Usuall+, )e )ill make use of the 2S.N.T integrated de$ugger. ;ence, the cordbg.e'e is rarel+ used in
realit+.
1ebugging at t2e Command #ine
Before +ou can de$ug +our application using cord$g.e/e, the first step is to generate de$ugging s+m$ols
for +our current application $+ specif+ing the ?de$ug flag of csc.e/e. 0or e/ample, to generate de$ugging
data for Test'pp.e/e, enter the follo)ing command set6
csc \testapp.rsp $debug
This generates a ne) file named testapp.pd$. *f +ou do not have an associated K.pd$ file, it is still possi$le
to make use of cord$g.e/eO ho)ever, +ou )ill not $e a$le to vie) +our & source code during the process
()hich is t+picall+ no fun )hatsoever, unless +ou )ish to complicate matters $+ reading *! code#. (nce
+ou have generated a K.pd$ file, open a session )ith cord$g.e/e $+ specif+ing +our .N.T assem$l+ as a
command4line argument (the K.pd$ file )ill $e loaded automaticall+#6
cord$g.e/e testapp.e/e
R.V.COLLEGE OF ENGINEERING Page B1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
't this point, +ou are in de$ugging mode and ma+ appl+ an+ num$er of cord$g.e/e flags at the (cord$g#
command prompt.
@.F Using t2e +isual Studio .NET 1E
Till no), )e have discussed ho) to compile & programs in command prompt. 2isual Studio .N.T
provides an *,. (*ntegrated ,evelopment .nvironment# to $uild applications using an+ num$er of .N.T4
a)are languages like &, 2B.N.T, I&, M0 etc. ;ere, )e )ill e/amine some of the core features of
2S.N.T *,..
T2e +S .NET Start Page
%hen )e launch 2S .N.T, )e can see start page as <
This )ill provide an option to open e/isting pro7ects or to create ne) pro7ects.
R.V.COLLEGE OF ENGINEERING Page B=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Creating a +S .NET Project Solution
(nce )e opt for creating ne) pro7ect, then, )e can see the follo)ing )indo)6
This )indo) )ill allo) us to choose the language (&, 2B.N.T etc#, then t+pe of the application
()indo)s, console etc#. Then )e can provide the name of the application and the location )here the
application to $e stored. 0ollo)ing is a list of pro7ect t+pes provided $+ &.
Project Ty!e Meaning
%indo)s 'pplication "epresents %indo)s 0orm application
lass !i$rar+ Used to $uild a single file assem$l+ (K.dll#
%indo)s ontrol !i$rar+ 'llo)s to $uild a single file assem$l+ (K.dll# that contains custom
%indo)s 0orms ontrols. ('ctive> controls#
'SP.N.T %e$ 'pplication Used to $uild a )e$ application
'SP.N.T %e$ Service Used to $uild a .N.T %e$ Service. %e$ Service is a $lock of code,
reacha$le using ;TTP reJuests.
%e$ ontrol !i$rar+ Used to $uild customi8ed %e$ controls. These 1U* )idgets are
R.V.COLLEGE OF ENGINEERING Page B@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
responsi$le for emitting ;TM! to a reJuesting $ro)ser.
onsole 'pplication Iust like command )indo).
%indo)s Services Used to $uild NT?=GGG services. Services are $ackground )orker
applications that are launched during (S $oot process.
@.1G C7 Pre!rocessor 1irectives
!ike and HH, & provides various s+m$ols to interact )ith the compilation process. But, the term
preprocessor doesn9t e/actl+ mean )hat it implies in or HH. There is no separate preprocessing step in
&. "ather, preprocessor directives are processed as a part of the le/ical anal+sis phase of the compiler.
;o)ever, the s+nta/ of & preprocessor is similar to that of and HH. 0ollo)ing is a list of
preprocessors supported $+ &.
C7 Pre!rocessor Symbol Meaning
&define, &undef Used to define and un4define conditional compilation s+m$ol.
&if, &elif, &else, &endif Used to conditionall+ skip sections of source code.
&line Used to control the line num$ers emitted for errors and )arnings
&error, &)arning Used to issue errors and )arnings for the current $uild
&region, &endregion Used to e/plicitl+ mark sections of source code. Under 2S.N.T,
regions ma+ $e e/panded and collapsed )ithin the code )indo). (ther
*,.s (including te/t editors# )ill ignore these s+m$ols.
S!eci"ying Code 4egions
Using &region and &endregion tags, )e can specif+ a $lock of code that ma+ $e hidden from vie) and
identified $+ a te/tual marker. The use of regions helps to keep length+ K.cs files more managea$le. 0or
e/ample, )e can create a region for defining a t+pe9s constructor (ma+ $e class, structure etc#, t+pe9s
properties and so on.
onsider the follo)ing code6
class Test
R.V.COLLEGE OF ENGINEERING Page BA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
]].
&region Un)anted
pu$lic class su$1
M
]].
N
pu$lic interface su$=
M
]]]]
N
&endregion
N
No), )hen )e put mouse curser on that region, it )ill $e sho)n as <
R.V.COLLEGE OF ENGINEERING Page BB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Conditional Code Com!ilation:
The preprocessor directives &if, &elif, &else and &endif allo)s to conditionall+ compile a $lock of code
$ased on predefined s+m$ols. onsider the follo)ing e/ample <
&define M'>
using S+stemO
class Test
M
R.V.COLLEGE OF ENGINEERING Page BC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic static void Main(#
M
&if(M'>#
onsole.%rite!ine(RM'> is definedR#O
&else
onsole.%rite!ine(RM'> is not definedR#O
&endif
N
N
The output )ill $e6 M'> is defined
ssuing %arnings and Errors:
The +warning and +error directives allo)s to instruct the & compiler to generate a )arning or error. 0or
e/ample, )e )ish to issue a )arning )hen a s+m$ol is defined in the current pro7ect. This is helpful )hen
a $ig pro7ect is handled $+ man+ people. onsider the follo)ing code6
&define M'>
using S+stemO
class Test
M
pu$lic static void Main(#
M
&if(M'>#
R.V.COLLEGE OF ENGINEERING Page BD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
&)arning M'> is defined $+ meLLL
]]]..
&endif
N
N
%hen )e compile, the program )ill give )arning message <
Test.cs(D,=1#6 )arning S1G@G6 &)arning6 ^M'> is defined $+ meLLL^
(ltering #ine Numbers:
The directive &line is rarel+ used in an+ pro7ect. This directive allo)s to alter the compiler9s recognition
of &line num$ers during its recording of compilation )arnings and errors. To reset the default line
num$ering, )e can specif+ default tag. onsider the follo)ing code6
&define M'>
using S+stemO
class Test
M
pu$lic static void Main(#
M
&line @GG ??ne/t line )ill take the num$er @GG
&)arning M'> is defined $+ meLLL
]]]..
&line default ?? default num$ering )ill continue
N
N
R.V.COLLEGE OF ENGINEERING Page BE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
%hen )e compile, the program )ill give )arning message <
Test.cs(@GG,=1#6 )arning S1G@G6 &)arning6 ^M'> is defined $+ meLLL^
Note that the line num$er appeared as @GG, though the actual line )as D.
@.11 (n nteresting (side: T2e System.Environment Class
The S+stem..nvironment class allo)s to o$tain a num$er of details regarding the conte/t of the operating
s+stem hosting .N.T application $+ using various static mem$ers. onsider the follo)ing e/ample <
using S+stemO
class Test
M
pu$lic static void Main(stringVW args#
M
onsole.%rite!ine(R(S6 MGNR, .nvironment.(S2ersion#O
onsole.%rite!ine(Rurrent ,irector+6 MGNR,
.nvironment.urrent,irector+#O
stringVW s Q .nvironment.1et!ogical,rives(#O
for(int iQGOiXs.!engthOiHH#
onsole.%rite!ine(R,rive MGN6 M1N R, i, sViW#O
R.V.COLLEGE OF ENGINEERING Page BF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsole.%rite!ine(R2ersion of .N.T6 MGNR, .nvironment.2ersion#O
N
N
The (utput )ill $e (depending on (S and version of .N.T, it ma+ var+# <
(S6 Microsoft %indo)s NT B.1.=CGG Service Pack @
urrent ,irector+6 6[Program 0iles[Microsoft 2isual Studio E[S,:[v=.G
,rive G6 '6[
,rive 16 6[
,rive =6 ,6[
,rive @6 .6[
,rive A6 06[
2ersion of .N.T6 =.G.BGD=D.@GE=
@.1= Summary
The point of this chapter )as to introduce +ou to the process of $uilding & applications. 's +ou have
seen, the ultimate recipient of +our K.cs files is the & compiler, csc.e/e. -ou have learnt ho) to use
csc.e/e in the ra) and during the process, +ou e/amined a num$er of compiler options including error
reporting?$ug report, response files etc. -ou have also e/plored the ke+ details of the 2S.N.T *,.. Trul+
speaking, 2S.N.T *,. is nothing more than an ela$orate )rapper around the ra) & compiler. That is,
an+thing that can $e done )ith 2S.N.T can $e done )ith the ra) & compiler too.
@.1@ :ey0ords
R.V.COLLEGE OF ENGINEERING Page CG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
csc.e/e
"esponse 0iles
1lo$al 'ssem$l+ ache (1'#
gacutil.e/e
Bug "eports
ommand !ine de$ugger or cord$g.e/e
Preprocessor ,irectives
&define, &undef
&line
&region, &endregion
&if, &elif, &endif, &else
&error, &)arning
S+stem..nvironment lass
@.1A E;ercises
1. ./plain the role of csc.e/e.
=. !ist and e/plain the $asic output options availa$le )ith & complier.
@. *llustrate )ith an e/ample, ho) do +ou compile multiple source filesP
A. %hat are response filesP ./plain )ith an e/ample.
B. ;o) do +ou generate $ug reportsP *llustrate )ith an e/ample.
C. %hat are & preprocessor directivesP ./plain.
D. ./plain the use of S+stem..nvironment class )ith a program.
Module 1
R.V.COLLEGE OF ENGINEERING Page C1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Unit 9
CONTENTS:
1.1E ($7ectives
A.= *ntroduction
A.@ The 'natom+ of a Basic & lass
A.A reating ($7ects6 onstructor Basics
A.B The omposition of a & 'pplication
A.C ,efault 'ssignment and 2aria$le scope
A.D The & Mem$er *nitiali8ation S+nta/
A.E Basic *nput and (utput )ith the onsole lass
A.F ,efining Program onstants
A.1G & *teration onstructs
A.11 & ontrols 0lo) onstructs
A.1= The omplete set of & (perators
A.1@ Summar+
A.1A :e+)ords
A.1B ./ercises
A.1 Objectives
't the end of this lesson, the students )ill understand6
The structure of & class
onstructors
R.V.COLLEGE OF ENGINEERING Page C=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
omposition of & 'pplication
2aria$les, *nput?(utput )ith onsole lass
onstants
*terative and "epetitive onstructs
(perators
A.= ntroduction
*n this unit, )e )ill discuss $asic concepts a$out & programming language. The s+nta/ of the &
program, ke+ )ords, varia$le initiali8ation, declaration of constants etc. are discussed here. The reading
of data from the ke+$oard, )riting the data onto the monitor have to $e revealed. The $asic programming
conditional constructs like if, if4else, s)itch statements, the looping constructs like for, )hile, do?)hile
etc are revealed. Then various operators like arithmetic, logical, relational operators supported $+ & are
discussed.
A.@ T2e (natomy o" a ,asic C7 Class
*n &, all program logic must $e contained )ithin a t+pe definition (t+pe ma+ $e a mem$er of the set
Mclass, interface, structure, enumeration, delegateN#. Unlike or HH, in & it is not possi$le to create
glo$al functions or glo$al points of data. *n its simplest form, a & program can $e )ritten as follo)s6
Program 9.1 Test.cs
using S+stemO
class Test
M
pu$lic static int Main(stringVW args#
R.V.COLLEGE OF ENGINEERING Page C@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
onsole.%rite!ine(R;ello %orldLR#O
return GO
N
N
.ver+ e/ecuta$le & application must contain a class defining a !ain,- method, )hich is used to signif+
the entr+ point of the application. !ain,- is used )ith the pu$lic and static ke+)ords. The pu$lic
mem$ers are accessi$le from other t+pes, )hile static mem$ers are scoped at the class level (rather than
the o$7ect level# and can thus $e invoked )ithout the need to first create a ne) class instance (or o$7ect#.
*n addition to the pu$lic and static ke+)ords, this Main(# method has a single parameter, )hich is an
arra+ of strings (stringVW args#. This parameter ma+ contain an+ num$er of incoming command4line
arguments.
The program Test.cs makes use of the onsole class, )hich is defined )ithin the S+stem namespace.
%rite!ine(# is a static mem$er of onsole class, )hich is used to pump a te/t string to the standard
output.
NOTE: %e can use onsole."ead!ine(# to ensure the command prompt launched $+ 2isual Studio =GGB
remains visi$le during a de$ugging session until )e press the .nter ke+.
+ariations on t2e Main56 Met2od
The !ain,- function can $e take an+ of the follo)ing forms $ased on our reJuirement6
$$ No return ty!e? array o" strings as argument.
pu$lic static void Main(stringFG args#
R.V.COLLEGE OF ENGINEERING Page CA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
??some code
N
$$ No return ty!e? no arguments.
pu$lic static void Main(#
M
??some code
N
$$ nteger return ty!e? no arguments.
pu$lic static int Main(#
M
??some code
??return a value to (S
N
NOTE: The Main(# method ma+ also $e defined as private. ,oing so ensures other assem$lies cannot
directl+ invoke an application9s entr+ point. 2isual Studio =GGB automaticall+ defines a program9s Main(#
method as private. ($viousl+, +our choice of ho) to construct Main(# )ill $e $ased on t)o Juestions.
0irst, do +ou need to process an+ user4supplied command4line parametersP *f so, the+ )ill $e stored in the
arra+ of strings. Second, do +ou )ant to return a value to the s+stem )hen Main(# has completedP *f so,
+ou need to return an integer data t+pe rather than void.
Processing Command8#ine (rguments
'ssume that )e need some arguments to $e passed as input to the Main(# funtion $efore starting the
program e/ecution. This is done through command4line parameters. onsider an e/ample <
R.V.COLLEGE OF ENGINEERING Page CB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Program 9.'
using S+stemO
class Test
M
pu$lic static int Main(stringVW args#
M
onsole.%rite!ine(RKKKKK ommand line args KKKKKR#O
for(int i Q GO i X args.!engthO iHH#
onsole.%rite!ine(R'rg6 MGN R, argsViW#O
N
N
;ere, )e are checking to )hether the arra+ of strings contains some num$er of items using the Lengt)
propert+ of System.Array. %e can provide command line arguments )hile running the program as <
Test.e/e 1ood Bad Ugl+
's an alternative to the standard for loop, )e ma+ iterate over incoming string arra+s using the &
foreac) ke+)ord. 0or e/ample <
$$ Notice you 2ave no need to c2ec3 t2e si<e o" t2e array $$02en using ="oreac2=.
pu$lic static int Main(stringVW args#
M
...
R.V.COLLEGE OF ENGINEERING Page CC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
"oreac25string s in args#
onsole.%rite!ine(R'rg6 MGN R, s#O
...
N
*t is also possi$le to access command4line arguments using the static .et#ommand-LineArgs,- method of
the System.Environment t+pe. The return value of this method is an arra+ of strings. The first inde/
identifies the current director+ containing the application itself, )hile the remaining elements in the arra+
contain the individual command4line arguments. *f )e are using this techniJue, )e need not define the
Main(# method )ith string arra+ parameter. onsider an e/ample <
pu$lic static int Main(# ??no arguments
M
$$ Eet arguments using System.Environment.
stringVW 'rgs Q .nvironment.1etommand!ine'rgs(#O
onsole.%rite!ine(RPath to this app is6 MGNR, 'rgsVGW#O
for(int iQ1O iX'rgs.!engthOiHH#
onsole.%rite!ine(R'rguments are6 MGNR, 'rgsViW#O
N
A.A Creating Objects: Constructor ,asics
'll o$7ect4oriented (((# languages make a clear distinction $et)een classes and o$7ects. ' class is a
definition (or, if +ou )ill, a blueprint# for a user4defined t+pe (U,T#. 'n ob/ect is simpl+ a term
descri$ing a given instance of a particular class in memor+. *n &, the new ke+)ord is used to create an
R.V.COLLEGE OF ENGINEERING Page CD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
o$7ect. Unlike other (( languages (such as HH#, it is not possi$le to allocate a class t+pe on the stackO
therefore, if +ou attempt to use a class varia$le that has not $een 3ne)4ed,5 +ou are issued a compile4time
error. Thus the follo)ing & code is illegal6
using S+stemO
class Test
M
pu$lic static int Main(stringVW args#
M
Test c1O
c1.SomeMethod(#O ??errorLL Must use 3ne)5
...
N
N
To illustrate the proper procedures for o$7ect creation, consider the follo)ing code6
using S+stemO
class Test
M
pu$lic static int Main(stringVW args#
M
$$ Aou can declare and create a ne0 object in a single line...
Test c1 Q ne0 Test(#O
R.V.COLLEGE OF ENGINEERING Page CE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
$$ ...or brea3 declaration and creation into t0o lines.
Test c=O
c= Q ne0 Test(#O
...
N
N
The new ke+)ord )ill calculate the correct num$er of $+tes for the specified o$7ect and acJuires
sufficient memor+ from the managed heap. ;ere, )e have allocated t)o o$7ects c1 and c=, each of )hich
points to a uniJue instance of Test t+pe. Note that & o$7ect varia$les are reall+ a reference to the o$7ect
in memor+, not the actual o$7ect itself. Thus, c1 and c= each reference a distinct Test o$7ect allocated on
the managed heap.
*n the previous program, the o$7ects have $een constructed using the default constructor, )hich $+
definition never takes arguments. .ver+ & class is automaticall+ provided )ith a free default
constructor, )hich +ou ma+ redefine if needed. The default constructor ensures that all mem$er data is set
to an appropriate default value. But in HH, un4initiali8ed data gets gar$age value.
Usuall+, classes provide additional constructors also. Using this, )e can initiali8e the o$7ect varia$les at
the time of o$7ect creation. !ike in Iava and HH, in & constructors are named identicall+ to the class
the+ are constructing, and the+ never provide a return value (not even void#.
onsider the follo)ing e/ample <
Program 9.&
using S+stemO
R.V.COLLEGE OF ENGINEERING Page CF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
class Test
M
pu$lic string userMessageO
$$ 1e"ault constructor.
pu$lic Test(#
M
onsole.%rite!ine(R,efault constructor calledLR#O
N
pu$lic Test (string msg#
M
onsole.%rite!ine(Rustom ctor calledLR#O
userMessage Q msgO
N
pu$lic static int Main(stringVW args#
M
$$ Call de"ault constructor.
Test c1 Q ne) Test (#O
onsole.%rite!ine(R2alue of userMessage6 MGN[nR, c1.userMessage#O
$$ Call !arameteri<ed constructor.
Test c=O
c= Q ne) Test (R;ello %orldR#O
onsole.%rite!ine(R2alue of userMessage6 MGNR, c=.userMessage#O
R.V.COLLEGE OF ENGINEERING Page DG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsole."ead!ine(#O
return GO
N
N
NOTE:
1. Technicall+ speaking, )hen a t+pe defines identicall+ named mem$ers (including constructors#
that differ onl+ in the num$er of_or t+pe of_parameters, the mem$er in Juestion is overloaded.
=. 's soon as )e define a custom constructor for a class t+pe, the free default constructor is
removed. *f )e )ant to create an o$7ect using the default constructor, )e need to e/plicitl+
redefine it as in the preceding e/ample.
s T2at a Memory #ea3H
Note that, in previous program, )e have not )ritten an+ code to e/plicitl+ destro+ the c1 and c=
references. *n HH, if )e do like this, it )ill lead to memor+ leak. But, the .N.T gar$age collector frees
the allocated memor+ automaticall+, and therefore & does not support a delete ke+)ord.
A.B T2e Com!osition o" a C7 (!!lication
%e have seen in the previous e/ample that the Main(# function creates instances of the ver+ o)n class in
)hich it is defined. ;o)ever, a more natural )a+ to )rite an application using distinct classes is as sho)n
in the follo)ing e/ample. *n (( terminolog+, this )a+ of )riting an application is kno)n as $eparation
o concerns.
Program 9.9 MyTest.cs
using S+stemO
class Test
R.V.COLLEGE OF ENGINEERING Page D1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
pu$lic Test(#
M
onsole.%rite!ine(R,efault constructor calledLR#O
N
pu$lic void disp(#
M
onsole.%rite!ine(R;iR#O
N
N
class M+Test
M
pu$lic static void Main(stringVW args#
M
Test c1 Q ne) Test (#O
c1.disp(#O
N
N
The t+pe (like class, structure etc# containing Main(# function (that is, entr+ point for the application# is
called as the application ob&ect. .ver+ & application )ill $e having one application o$7ect and numerous
other t+pes. (n the other hand, )e can create an application o$7ect that defines an+ num$er of mem$ers
called from the Main(# method.
A.C 1e"ault (ssignments and +ariable Sco!e
R.V.COLLEGE OF ENGINEERING Page D=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
'll intrinsic .N.T data t+pes have a default value. %hen )e create custom t+pes, all mem$er varia$les
are automaticall+ assigned to their respective default values. onsider an e/ample <
Program 9.I
using S+stemO
class Test
M
pu$lic int aO ??default value is G
pu$lic $+te $O ??default value is G
pu$lic char cO ??default value is null
pu$lic string sO ??default value is null
pu$lic static void Main(#
M
Test tQne) Test(#O
onsole.%rite!ine(3MGN, M1N, M=N, M@N5, a, $, c, s#O
N
N
'll the varia$les )ill $e initiali8ed to their default values )hen )e start de$ugging. ;o)ever, )e can not
e/pect the same )ithin method scope. 0or e/ample, the follo)ing program )ill generate an error.
using S+stemO
class Test
R.V.COLLEGE OF ENGINEERING Page D@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
pu$lic static void Main(#
M
int aO ??need to assign some value to `a9
onsole.%rite!ine(3MGN5, a#O ??.rror6Unassigned local varia$le `a9
N
N
NOTE: There is an e/ception for the mandator+ assignment of a local varia$le. *f the local varia$le is
used as an output parameter, then it need not $e initiali8ed $efore use. (utput parameters are discussed
later in detail. ;o)ever, note that, the+ are used to receive the value from a function.
A.D T2e C7 Member +ariable nitiali<ation Synta;
onsider a class (or an+ other t+pe# having more than one constructor )ith different set (ma+ $e different
in t+pe or num$er# of arguments. No), if an+ mem$er varia$le needs to $e initiali8ed )ith same value in
all the situations, )e need to )rite the code repeatedl+ in all the constructors. 0or e/ample,
class Test
M
private int aO
Test(#
M
aQBO
N
R.V.COLLEGE OF ENGINEERING Page DA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Test(int k#
M
aQBO
]].
N
Test(string s#
M
aQBO
]].
N
N
Though the a$ove code is valid, there is redundanc+ in code. %e can )rite a function for such
initiali8ation like <
class Test
M
private int aO
pu$lic void init(#
M
aQBO
N
Test(#
R.V.COLLEGE OF ENGINEERING Page DB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
init(#O
N
Test(int k#
M
init(#
]].
N
Test(string s#
M
init(#
]].
N
N
;ere )e have function call instead of assignment. Thus, redundanc+ still e/ists. To avoid such situation,
& provides the initiali8ation of mem$er varia$les directl+ )ithin a class as sho)n <
class Test
M
private int a QBO
private string sQ 3;ello5O
]]]]..
N
R.V.COLLEGE OF ENGINEERING Page DC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
This facilit+ )as not availa$le in HH. Note that, such an initiali8ation )ill happen $efore the constructor
gets called. ;ence, if )e provide an+ other value to a varia$le through constructor, the previous mem$er
assignment )ill $e over)ritten.
A.E ,asic n!ut and Out!ut 0it2 t2e Console Class
*n man+ of the programs )hat )e have seen till no), made use of S+stem.onsole class. 's the name
suggests, onsole class is defined in S+stem namespace and it encapsulates input, output and error stream
manipulations. This class is )idel+ used for console applications $ut not for %indo)s or %e$
applications.
There are four important static methods in onsole class6
"ead(# Used to capture a single character from the input stream.
"ead!ine(# Used to receive information from the input stream until the
enter ke+ is pressed.
%rite(# This method pumps te/t to the output stream )ithout
carriage return (enter ke+#
%rite!ine(# This pumps a te/t string including carriage return to the
output stream.
0ollo)ing ta$le gives some important mem$er of onsole class6
Member Meaning
Backgroundolor
0oregroundolor
These properties set the $ackground?foreground colors for the current output.
The+ ma+ $e assigned an+ mem$er of the onsoleolor enumeration.
R.V.COLLEGE OF ENGINEERING Page DD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Buffer;eight
Buffer%idth
These properties control the height?)idth of the console9s $uffer area.
lear(# This method clears the $uffer and console displa+ area.
Title This propert+ sets the title of the current console.
%indo);eight
%indo)%idth
%indo)Top
%indo)!eft
These properties control the dimensions of the console in relation to the
esta$lished $uffer.
T% illustrate the 2%r1ing %) C%ns%le class &eth%ds/ c%nsider the )%ll%2ing e0a&(le G
#rogram $.%
using S+stemO
class Basic*(
M
pu$lic static void Main(#
M
onsole.%rite(R.nter +our name6 R#O
string s Q onsole."ead!ine(#O
onsole.%rite!ine(R;ello, MGN R, s#O
onsole.%rite(R.nter +our age6 R#O
s Q onsole."ead!ine(#O
onsole.%rite!ine(R-ou are MGN +ears oldR, s#O
N
N
The output )ould $e <
.nter +our name6 "amu
;ello, "amu
R.V.COLLEGE OF ENGINEERING Page DE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
.nter +our age6 =B
-ou are =B +ears old
*ormatting Te;tual Out!ut
*n the previous e/amples, )e have seen numerous occurrences of the tokens MGN, M1N etc. em$edded
)ithin a string literal. .N.T introduces a ne) st+le of string formatting. ' simple e/ample follo)s <
static void Main(stringVW args#
M
...
int i Q FGO
dou$le d Q F.FFO
$ool $ Q trueO
onsole.%rite!ine(R*nt is6 J.K[n,ou$le is6 J1K[nBool is6 J'KR, i, d, $#O
N
The first parameter to %rite!ine(# represents a string literal that contains optional placeholders designated
$+ MGN, M1N, M=N, and so forth (curl+ $racket num$ering al)a+s $egins )ith 8ero#. The remaining
parameters to %rite!ine(# are simpl+ the values to $e inserted into the respective placeholders.
Note that %rite!ine(# has $een overloaded to allo) the programmer to specif+ placeholder values as an
arra+ of o$7ects. Thus, )e can represent an+ num$er of items to $e plugged into the format string as
follo)s6
$$ *ill !lace2olders using an array o" objects.
R.V.COLLEGE OF ENGINEERING Page DF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
o$7ectVW stuff Q MR;elloR, =G.F, 1, RThereR, RE@R, FF.FFF@@N O
onsole.%rite!ine(RThe Stuff6 MGN , M1N , M=N , M@N , MAN , MBN R, stu""#O
*t is also permissi$le for a given placeholder to repeat )ithin a given string. 0or e/ample, if )e )ant to
$uild the string RF, Num$er F, Num$er FR )e can )rite
onsole.%rite!ine(RMGN, Num$er MGN, Num$er MGNR, F#O
Note *f an+ mismatch occurs $et)een the num$er of uniJuel+ num$ered curl+4$racket placeholders and
fill arguments, an e/ception vi8. 0ormat./ception is popped up at runtime.
.NET String *ormatting *lags
*f )e reJuire more detailed formatting, each placeholder can optionall+ contain various format characters
(in either uppercase or lo)ercase#, as sho)n <
C7 *ormat
C2aracter
Meaning
or c Used to format currenc+. B+ default, the flag )ill prefi/ the local cultural s+m$ol (a
dollar sign VaW for U.S. .nglish#. ;o)ever, this can $e changed using a
S+stem.1lo$ali8ation.Num$er0ormat*nfo o$7ect
, or d Used to format decimal num$ers. This flag ma+ also specif+ the minimum num$er of
digits used to pad the value.
. or e Used for e/ponential notation.
0 or f Used for fi/ed4point formatting.
1 or g Stands for general. This character can $e used to format a num$er to fi/ed or
e/ponential format.
N or n Used for $asic numerical formatting ()ith commas#.
> or / Used for he/adecimal formatting. *f +ou use an uppercase >, +our he/ format )ill also
contain uppercase characters.
R.V.COLLEGE OF ENGINEERING Page EG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
These format characters are suffi/ed to a given placeholder value using the colon token (e.g., MG6N,
M16dN, M=6>N, and so on#. onsider an e/ample6
#rogram $.&
using S+stemO
class Test
M
pu$lic static void Main(stringVW args#
M
onsole.%rite!ine(R format6 J.:CKR, FFFEF.FED#O
onsole.%rite!ine(R,F format6 J.:1LKR, FFFFF#O
onsole.%rite!ine(R. format6 J.:EKR, FFFFF.DCBA@#O
onsole.%rite!ine(R0@ format6 J.:*&KR, FFFFF.FFFF#O
onsole.%rite!ine(RN format6 J.:NKR, FFFFF#O
onsole.%rite!ine(R> format6 J.:MKR, FFFFF#O
onsole.%rite!ine(R/ format6 J.:;KR, FFFFF#O
N
A
The %ut(ut 2%uld be G
format6 aFF,FEF.FF
,F format6 GGGGFFFFF
. format6 F.FFFFDD.HGGA
0@ format6 1GGGGG.GGG
N format6 FF,FFF.GG
> format6 1ECF0
R.V.COLLEGE OF ENGINEERING Page E1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
/ format6 1ECFf
Note that the use of .N.T formatting characters is not limited to console applications. These same flags
can $e used )ithin the conte/t of the static String.0ormat(# method. This can $e helpful )hen )e need to
create a string containing numerical values in memor+ for use in an+ application t+pe (%indo)s 0orms,
'SP.N.T, >M! )e$ services, and so on#6
#rogram $.'
using S+stemO
class Test
M
static void Main(stringVW args#
M
string StrO
Str Q String.0ormat(R-ou have J.:CK in +our accountR, FFFEF.FED#O
onsole.%rite!ine(Str#O
N
N
The %ut(ut 2%uld be G
-ou have aFF,FEF.FF in +our account
A.F 1e"ining Program Constants
R.V.COLLEGE OF ENGINEERING Page E=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
& provides a const ke+)ord to defined varia$les )ith a fi/ed, unaltera$le value. The value of a constant
data is computed at compile time and hence, a constant varia$le can not $e assigned to an o$7ect reference
()hose value is computed at runtime#. That is, $o/ing ()ill discuss this in ne/t module# is not possi$le
for constant varia$les. %e can define either class4level constants or local4level ()ithin a method#
constants. 0or e/ample,
Program 9.L
using S+stemO
a$stract class onstlass
M
pu$lic const int pQ1GO
pu$lic const string sQR* am a constantRO
N
class Test
M
pu$lic const int /QBO
pu$lic static void Main(#
M
const int +Q=GO
onsole.%rite!ine(RMGN,M1N,M=N,M@NR, onstlass.p, onstlass.s, /, +#O
N
R.V.COLLEGE OF ENGINEERING Page E@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
The output )ould $e <
1G, * am a constant, B, =G
A.1G C7 teration Constructs
Similar to an+ other programming language, & provides follo)ing iteration constructs6
for !oop
foreac)*in !oop
w)ile !oop
do*w)ile !oop
T2e or #oo!
The for loop in & is 7ust similar to that in , HH or Iava. This loop )ill allo) to repeat a set of
statements for fi/ed num$er of times. 0or e/ample <
for(int iQGO iX1GOiHH#
onsole.%rite!ine(3MGN5, i#O ??G to F )ill $e printed.
%e can use an+ t+pe of comple/ terminating conditions, incrementation? decrementation, continue,
brea0, goto etc. )hile using for loop.
R.V.COLLEGE OF ENGINEERING Page EA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
T2e oreach+in #oo!
This loop is used to iterate over all items )ithin an arra+. The follo)ing e/ample sho)s ho) each
element of an integer arra+ is considered )ithin a loop.
Program 9.1.
using S+stemO
class Test
M
pu$lic static void Main(#
M
intVW arrQne) intVWMB, @=, 1G, AB, C@NO
foreach(int i in arr#
onsole.%rite!ine(RMGNR,i#O
N
N
'part from iterating over simple arra+s, foreac) loop is used to iterate over s+stem supplied or user4
defined collections. This )ill $e discussed in later chapters.
T2e while and do+while #oo!
%hen )e don9t kno) the e/act num$er of times a set of statements to $e e/ecuted, )e )ill go for w)ile
loop. That is, a set of statements )ill $e e/ecuted till a condition remains true. 0or e/ample,
R.V.COLLEGE OF ENGINEERING Page EB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
string sO
)hile((sQonsole."ead!ine(##LQnull#
onsole.%rite!ine(3MGN5, s#O
Some times, )e need a set of statements to $e e/ecuted at least once, irrespective of the condition. Then
)e can go for do*w)ile loop. 0or e/ample,
string optO
do
M
onsole.%rite(3,o +ou )ant to continueP(-es?No#65#O
optQonsole."ead!ine(#O
N)hile(optLQ5-es5#O
A.11 C7 Control *lo0 Constructs
There are t)o control flo) constructs in & vi8. if*else and switc)*case. The if*else )orks onl+ on $oolean
e/pressions. So )e can not use the values G, 1 etc. )ithin if as )e do in ?HH. Thus, the if statement in
& t+picall+ involve the relational operators and?or conditional operators.
The follo)ing t)o ta$les lists out the relational and logical operators respectivel+.

4elational O!erator Meaning
QQ To check eJualit+ of t)o operands
LQ Not eJual to
X !ess than
Y 1reater than
R.V.COLLEGE OF ENGINEERING Page EC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
XQ !ess than or eJual to
YQ 1reater than or eJual to
Conditional$#ogical O!erator Meaning
UU !ogical 'N,
bb !ogical ("
L !ogical N(T
The general form of if can $e given as <
i"(condition#
M
??true $lock
N
else
M
??false $lock
N
The general from of switc) can $e given as <
s0itc2(varia$le?e/pression#
M
case val16 ??statementsO
brea3C
case val=6 ??statementsO
brea3C
44444444444444
44444444444444
R.V.COLLEGE OF ENGINEERING Page ED
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
case val=6 ??statementsO
brea3C
N
A.1= Com!lete set o" C7 O!erators
0ollo)ing is a set of operators provided $+ &.
O!erator Category O!erators
Unar+ H, 4, L, c, HH, 44
Multiplicative K, ?, d
'dditive H, 4
Shift XX, YY
"elational X, Y, XQ. YQ, is, as
.Jualit+ QQ, LQ
!ogical U ('N,#, T (>("#, b (("#
onditional UU, bb, P6 (ternar+ operator#
*ndirection?'ddress K, 4Y, U
'ssignment Q, KQ, 4Q, HQ, ?Q, dQ, XXQ, YYQ, UQ, TQ, bQ
The relational operator is is used to verif+ at runtime )hether an o$7ect is compati$le )ith a given t+pe or
not. The as operator is used to do)ncast $et)een t+pes. %e )ill discuss this later in detail. 's &
supports inter4language interaction, it supports the HH pointer manipulation operators like K, 4Y and U.
But if )e use an+ of these operators, )e are going $+pass the runtime memor+ management scheme and
)riting code in unsafe mode.
A.1@ Summary
R.V.COLLEGE OF ENGINEERING Page EE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
This unit has e/posed +ou to the numerous core aspects of the & programming !anguage. The focus )as
to e/amine the constructs that )ill $e commonplace in an+ application +ou ma+ $e interested in $uilding.
0irst, ever+ & program must have a class defining a static Main(# method, )hich serves as the entr+
point of the program. %ithin the scope of Main(#, +ou t+picall+ create an+ num$er of o$7ects )hich )ork
together to $reathe life into +our application. Then +ou have e/plored $asic reJuirements like *?(
operations, varia$le declaration and scope, control flo) etc. of the programming language.
A.1A :ey0ords
ommand !ine arguments
The ke+)ord new
"eference to an o$7ect
onstructor6 ,efault and Parameteri8ed
Separation of concerns
'pplication o$7ect
S+stem.onsole class
0ormatting outputs
The :e+)ord const
The loops for, foreac)*in, w)ile, do*w)ile
The conditional constructs if*else, switc)*case
The (perators is, as
A.1B E;ercises
1. ./plain variations in Main(# function.
=. %hat are $asic input and output functions )ith onsole classP ./plain.
@. %rite a & program to illustrate command line arguments.
A. %rite a note on formatting te/tual input.
B. !ist out string formatting flagsP ./plain )ith e/ample.
C. %rite a & program to illustrate foreach?in !oop.
D. %rite a & application )hich defines a class Shape, )ith four data mem$ers length, $readth, height
and radius, appropriate constructors and methods to calculate volume of cu$e, cone and sphere. 'lso
R.V.COLLEGE OF ENGINEERING Page EF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
)rite a class Shape'pp, )hich creates these @ o$7ects i.e. cu$e, cone and sphere using appropriate
constructors and calculates their volume )ith the help of a$ove class methods.
Module '
Unit 1
CONTENTS:
1.1F ($7ectives
1.=G *ntroduction
1.=1 Understanding 2alue T+pes and "eference T+pes
1.== The Master Node6 S+stem.($7ect
1.=@ The S+stem ,ata T+pes (and & 'liases#
1.=A onverting $et)een value t+pes reference t+pes6 Bo/ing and
Un$o/ing
1.=B Summar+
1.=C :e+)ords
1.=D ./ercises
1.1C Objectives
't the end of this lesson, the students )ill understand6
T)o t+pes in .N.T vi8. value t+pes and reference t+pes
The topmost $ase class S+stem.($7ect
2arious methods of S+stem.($7ect class, overriding these methods
2arious data t+pes availa$le in &
Bo/ing and Un$o/ing
R.V.COLLEGE OF ENGINEERING Page FG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1.1D ntroduction
%e have seen from the first module that .N.T provides common language runtime for all the
programming languages supported on its platform. 's a part of !", an+ t+pe in .N.T or more
specificall+ &, can $e either of value t+pe or of reference t+pe. These t)o t+pes have their o)n )a+ of
usage and properties. Moreover, in &, ever+thing that )e use in a program is derived from a topmost
$ase class called S+stem.($7ect. *n this unit, )e are going discuss all these factors in detail.
1.1E Understanding +alue Ty!es and 4e"erence Ty!es
!ike an+ programming language, & defines a num$er of ke+)ords that represent $asic data t+pes such as
)hole num$ers, character data, floating4point num$ers, and Boolean values. These intrinsic t+pes are
fi/ed constants. That is, all .N.T4a)are languages understand the fi/ed nature of these intrinsic t+pes,
and all agree on the range it is capa$le of handling.
' .N.T data t+pe ma+ $e ,alue-based or reerence-based. 2alue4$ased t+pes, )hich include all
numerical data t+pes (int, float, etc.# as )ell as enumerations and structures, are allocated on t)e stac0. So,
value t+pes can $e Juickl+ removed from memor+ once the+ are out of the defining scope6
pu$lic void SomeMethod(#
M
int i Q GO
onsole.%rite!ine(i#O
N $$ =i= is removed "rom t2e stac3 2ere
R.V.COLLEGE OF ENGINEERING Page F1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
%hen )e assign one value t+pe to another, a mem$er4$+4mem$er (or a $it4)ise# cop+ is achieved $+
default. *n terms of numerical or Boolean data t+pes, the onl+ 3mem$er5 to cop+ is the value of the
varia$le itself6
pu$lic void SomeMethod(#
M
int i Q FFO
int 7 Q iO
7 Q ED@=O $$ j 0ill be NO&' and i remains to be LL
N
This e/ample ma+ not seem special. But, no) )e )ill have a look at other value t+pes like structures and
enumerations. Structures provide a )a+ to achieve the $enefits of o$7ect orientation (i.e., encapsulation#
)hile having the efficienc+ of stack4allocated data. !ike a class, structures can take constructors (onl+
parameteri8ed constructors# and define an+ num$er of mem$ers. 'll structures are implicitl+ derived
from a class named System.+alueTy!e. The purpose of S+stem.2alueT+pe is to 3override5 the virtual
methods defined $+ S+stem.($7ect to support value4$ased v?s reference4$ased semantics. *n fact, the
instance methods defined $+ S+stem.2alueT+pe are identical to those of S+stem.($7ect.
onsider an e/ample to illustrate the )orking of value t+pes <
Program 1.1 *ile Name: MyClass.cs
struct M+Struct
M
pu$lic int /O
N
R.V.COLLEGE OF ENGINEERING Page F=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
class M+lass
M
pu$lic static void Main(#
M
?? the ke+)ord ne) is optional )hile creating structures.
M+Struct ms1 Qne) M+Struct(#O
ms1./ Q 1GGO
M+Struct ms= Q ms1O
onsole.%rite!ine(Rms1./ Q MGNR, ms1./#O ??1GG
onsole.%rite!ine(Rms=./ Q MGNR, ms=./#O ??1GG
ms=./ Q FGGO
onsole.%rite!ine(Rms1./ Q MGNR, ms1./#O ??1GG
onsole.%rite!ine(Rms=./ Q MGNR, ms=./#O ??FGG
N
N
The (utput )ill $e <
ms1./ Q 1GG
ms=./ Q 1GG
ms1./ Q 1GG
ms=./ Q FGG
R.V.COLLEGE OF ENGINEERING Page F@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Note that, to allocate a structure t+pe, )e can use the `ne)9 ke+)ord. This )ill create an impression that
memor+ is allocated in heap. But, this is not true. !" makes the programmer to feel ever+thing is an
o$7ect and ne) value t+pes. ;o)ever, )hen the runtime encounters a t+pe derived from
S+stem.2alueT+pe, stack allocation is achieved.
*n the a$ove program, )e have created a varia$le ms1 and then it is assigned to ms=. Since M+Struct is a
value t+pe, )e )ill have t)o copies of the M+Struct t+pe on the stack, each of )hich can $e
independentl+ manipulated. Therefore, )hen )e change the value of ms=./, the value of ms1./ is
unaffected.
(n the other hand, the reference t+pes (classes# are allocated on the managed heap. These o$7ects sta+ in
memor+ until the .N.T gar$age collector destro+s them. B+ default, assignment of reference t+pes results
in a ne) reference to the same o$7ect on the heap. To illustrate, let us change the a$ove e/ample6
Program 1.' *ile Name: MyClass1.cs
class M+lass ??struct has $een changed to class
M
pu$lic int /O
N
class M+lass1
M
pu$lic static void Main(#
M
R.V.COLLEGE OF ENGINEERING Page FA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M+lass mc1 Qne) M+lass (#O ?? new is compulsor+
mc1./ Q 1GGO
M+lass mc= Q mc1O
onsole.%rite!ine(Rmc1./ Q MGNR, mc1./#O ??1GG
onsole.%rite!ine(Rmc=./ Q MGNR, mc=./#O ??1GG
ms=./ Q FGGO
onsole.%rite!ine(Rmc1./ Q MGNR, mc1./#O ??FGG
onsole.%rite!ine(Rmc=./ Q MGNR, mc=./#O ??FGG
N
N
The (utput )ill $e <
mc1./ Q 1GG
mc=./ Q 1GG
mc1./ Q FGG
mc=./ Q FGG
*n this e/ample, )e have t)o references pointing to the same o$7ect on the managed heap. Therefore,
)hen )e change the value of / using the mc= reference, mc1./ reports the same value.
+alue Ty!es Containing 4e"erence Ty!es
R.V.COLLEGE OF ENGINEERING Page FB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
'ssume that )e have a reference (class# t+pe !y#lass containing a constructor to assign value to a
mem$er varia$le of t+pe string. 'ssume also that )e have included o$7ect of this class )ithin a structure
!yStruct. %e have included the Main(# function in another class and the total application is as given
$elo) <
Program 1.& Name o" "ile: Test.cs
using S+stemO
class M+lass
M
pu$lic string sO
pu$lic M+lass(string str# ??constructor for class
M
sQstrO
N
N
struct M+Struct
M
pu$lic M+lass mcO
pu$lic int aO
pu$lic M+Struct(string str# ??constructor for structure
M
mcQne) M+lass(str#O ??calling constructor of class
R.V.COLLEGE OF ENGINEERING Page FC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
aQ1GO
N
N
class Test
M
pu$lic static void Main(stringVW args#
M
M+Struct ms1Qne) M+Struct(R*nitial 2alueR#O
ms1.aQ1BO
M+Struct ms=Qms1O
ms=.mc.sQRNe) 2alueLLLRO
ms=.aQ=GO
onsole.%rite!ine(Rms1.mc.s is MGNR, ms1.mc.s#O
onsole.%rite!ine(Rms=.mc.s is MGNR, ms=.mc.s#O
onsole.%rite!ine(Rms1.a is MGNR, ms1.a#O
onsole.%rite!ine(Rms=.a is MGNR, ms=.a#O
N
N
The (utput )ould $e <
ms1.mc.s is Ne) 2alueLLL
ms=.mc.s is Ne) 2alueLLL
ms1.a is 1B
R.V.COLLEGE OF ENGINEERING Page FD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
ms=.a is =G
No) compare the programs 1.1? 1.' and 1.&.
*n Program 1.1? )e have used the structure, )hich is of value t+pe. So, )hen )e use the
statement
M+Struct ms1Q ms23
there )ill $e separate memor+ allocation for t)o o$7ects (Memor+ )ill $e allocated from stack#.
Thus, the assignment statement ms14ms2 )ill cop+ the contents of ms2 to the corresponding
varia$les of ms1. Since memor+ allocation is different for these t)o o$7ects, the change in one
o$7ect doesn9t affect the other o$7ect.
*n Program 1.'? )e have used the class, )hich is of reference t+pe. So, )hen )e use the
statement
M+lass mc1 Q mc2,
mc1 )ill $e 7ust reference to mc2 sharing the same memor+ location in the heap. 'lso, the
contents of mc2 )ill $e copied to the corresponding varia$les of mc1. Since memor+ location is
same for $oth the o$7ects, the change in one o$7ect )ill affect the other o$7ect.
*n Program 1.&, )e have a value t+pe !yStruct containing an o$7ect of reference t+pe !y#lass.
The o$7ect ms2 of !yStruct contains an o$7ect mc of !y#lass and an integer varia$le a. ;ere, a
)ill $e allocated memor+ from stack and mc )ill get memor+ from heap. No), )hen )e use the
statement
M+Struct ms=Qms1O
the o$7ect ms1 gets created. Note that, ms2.a and ms1.a )ill have different memor+ allocation as
a is mem$er of structure. But, ms2.mc.s and ms1.mc.s )ill point to same location in heap memor+
as s is $asicall+ a mem$er of class. This can $e diagrammaticall+ represented as<
R.V.COLLEGE OF ENGINEERING Page FE
ms2 ms1
a s a
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Thus, )hen a value t+pe contains other reference t+pes, assignment results in a cop+ of t)e references. *n
this )a+, )e have t)o independent structures ms2 and ms1 each of )hich contains a reference pointing to
the same o$7ect in memor+ (i.e., a 3shallo) cop+5#. %hen )e )ant to perform a 3deep cop+,5 )here the
state of internal references is full+ copied into a ne) o$7ect, )e need to implement the *lonea$le
interface, )hich )e )ill see later in detail.
+alue and 4e"erence Ty!es: *inal 1etails
0ollo)ing ta$le summari8es the core distinctions $et)een value t+pes and reference t+pes.
ntriguing Puestion +alue Ty!e 4e"erence Ty!e
%here is this t+pe allocatedP 'llocated on the stack 'llocated on the managed heap.
;o) is a varia$le representedP 2alue t+pe varia$les are local
copies.
"eference t+pe varia$les are pointing
to the memor+ occupied $+ the
allocated instance.
%hat is the $ase t+peP Must derive from
S+stem.2alueT+pe.
an derive from an+ other t+pe
(e/cept S+stem.2alueT+pe#, as long
as that t+pe is not 3sealed5
an this t+pe function as a $ase
to other t+pesP
No. 2alue t+pes are al)a+s sealed
and cannot $e e/tended.
-es. *f the t+pe is not sealed, it ma+
function as a $ase to other t+pes.
R.V.COLLEGE OF ENGINEERING Page FF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
%hat is the default parameter
passing $ehaviorP
2aria$les are passed $+ value
(i.e., a cop+ of the varia$le is
passed into the called function#.
2aria$les are passed $+ reference
(e.g., the address of the varia$le is
passed into the called function#.
an this t+pe override
S+stem.($7ect.0inali8e(#P
No. 2alue t+pes are never placed
onto the heap and therefore do not
need to $e finali8ed.
-es, indirectl+
an )e define constructorsP -es, $ut the default constructor is
reserved
-es
%hen do varia$les of this t+pe
dieP
%hen the+ fall out of the defining
scope.
%hen the managed heap is gar$age
collected.
,espite their differences, value t+pes and reference t+pes $oth have the a$ilit+ to implement interfaces
and ma+ support an+ num$er of fields, methods, overloaded operators, constants, properties, and events.
1.1F T2e Master Node: System.Object
*n .N.T, ever+ data t+pe is derived from a common $ase class6 S+stem.($7ect. The ($7ect class defines a
common set of mem$ers supported $+ ever+ t+pe in the .N.T frame)ork. %hen )e create a class, it is
implicitl+ derived from S+stem.($7ect. 0or e/ample, the follo)ing declaration is common )a+ to use.
class Test
M
...
N
But, internall+, it means that,
class Test 6 S+stem.($7ect
M
...
R.V.COLLEGE OF ENGINEERING Page 1GG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
S+stem.($7ect defines a set of instance4level (availa$le onl+ after creating o$7ects# and class4level (static#
mem$ers. Note that some of the instance4level mem$ers are declared using the virtual ke+)ord and can
therefore $e overridden $+ a derived class6
$$ T2e structure o" System.Object class
namespace System
M
pu$lic class Object
M
pu$lic ($7ect(#O
pu$lic virtual Boolean .Juals(($7ect o$7#O
pu$lic virtual *nt@= 1et;ashode(#O
pu$lic T+pe 1etT+pe(#O
pu$lic virtual String ToString(#O
protected virtual void 0inali8e(#O
protected ($7ect Mem$er)iselone(#O
pu$lic static $ool .Juals(o$7ect o$7', o$7ect o$7B#O
pu$lic static $ool "eference.Juals(o$7ect o$7', o$7ect o$7B#O
N
N
0ollo)ing ta$le sho)s some of the functionalit+ provided $+ each instance4level method.
nstance Met2od
o" ($7ect Class
Meaning
.Juals(# B+ default, this method returns true onl+ if the items $eing compared refer to
R.V.COLLEGE OF ENGINEERING Page 1G1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
the e/act same item in memor+. Thus, .Juals(# is used to compare o$7ect
references, not the state of the o$7ect. T+picall+, this method is overridden to
return true onl+ if the o$7ects $eing compared have the same internal state
values. Note that if +ou override .Juals(#, +ou should also override
1et;ashode(#.
1et;ashode(# This method returns an integer that identifies a specific o$7ect in memor+. *f
+ou intend +our custom t+pes to $e contained in a
S+stem.ollections.;ashta$le t+pe, +ou are )ell4advised to override the
default implementation of this mem$er.
1etT+pe(# This method returns a S+stem.T+pe o$7ect that full+ descri$es the details of
the current item. *n short, this is a "untime T+pe *dentification ("TT*# method
availa$le to all o$7ects.
ToString(# This method returns a string representation of a given o$7ect, using the
namespace.typename format (i.e., full+ Jualified name#. *f the t+pe has not
$een defined )ithin a namespace, typename alone is returned. This method
can $e overridden $+ a su$class to return a tokeni8ed string of name?value
pairs that represent the o$7ect9s internal state, rather than its full+ Jualified
name.
0inali8e(# This protected method ()hen overridden# is invoked $+ the .N.T runtime
)hen an o$7ect is to $e removed from the heap (during gar$age collection#.
Mem$er)iselone(# This protected method e/ists to return a ne) o$7ect that is a mem$er4$+4
mem$er cop+ of the current o$7ect. Thus, if the o$7ect contains references to
other o$7ects, the references to these t+pes are copied (i.e., it achieves a
shallo) cop+#. *f the o$7ect contains value t+pes, full copies of the values are
achieved. (./ample, Program 1.@#
T2e 1e"ault ,e2avior o" System.Object
To illustrate some of the default $ehavior provided $+ the S+stem.($7ect $ase class, consider the
follo)ing e/ample <
Program 1.9
using S+stemO
class Person
M
pu$lic string Name, SSNO
pu$lic $+te ageO
R.V.COLLEGE OF ENGINEERING Page 1G=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic Person(string n, string s, $+te a#
M
Name Q nO
SSN Q sO
age Q aO
N
pu$lic Person(#M N
static void Main(stringVW args#
M
onsole.%rite!ine(RKKKKK %orking )ith ($7ect KKKKK[nR#O
Person p1 Q ne) Person(R"amR, R11141141111R, =G#O
onsole.%rite!ine(Rp1.ToString6 MGNR, p1.ToString(##O
onsole.%rite!ine(Rp1.1et;ashode6 MGNR, p1.1et;ashode(##O
onsole.%rite!ine(Rp19s $ase class6 MGNR, p1.1etT+pe(#.BaseT+pe#O
Person p= Q p1O
o$7ect o Q p=O
if(o..Juals(p1# UU p=..Juals(o##
onsole.%rite!ine(Rp1, p= and o are same o$7ectsLR#O
N
N
The (utput )ould $e <
R.V.COLLEGE OF ENGINEERING Page 1G@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
KKKKK %orking )ith ($7ect KKKKK
p1.ToString6 Person
p1.1et;ashode6 BE==BAE=
p1^s $ase class6 S+stem.($7ect
p1, p= and o are same o$7ectsL
%e can notice from the a$ove program that the default implementation of ToString(# simpl+ returns the
full+ Jualified name of the t+pe. 1etT+pe(# retrieves a S+stem.T+pe o$7ect, )hich defines a propert+
named . ;ere, ne) Person o$7ect p1 is referencing memor+ in the heap. p= is also of t+pe Person,
ho)ever, )e are not creating a new instance of the Person class, $ut assigning p= to p1. Therefore, p1 and
p= are $oth pointing to the same o$7ect in memor+. Similarl+ the varia$le o (of t+pe o$7ect# also refers to
the same memor+. Thus, )hen )e compare p1, p= and o, it sa+s that all are same.
Overriding Some 1e"ault ,e2aviors o" System.Object
*n man+ of our applications, )e ma+ )ant to override some of the $ehaviors of S+stem.($7ect.
(verriding is the process of redefining the $ehavior of an inherited virtual mem$er in a derived class. %e
have seen that S+stem.($7ect class has some virtual methods like ToString(#, .Juals(# etc. These can $e
overridden $+ the programmer.
Overriding ToString56
onsider the follo)ing e/ample to override S+stem.($7ect.ToString(#.
Program 1.I
using S+stemO
using S+stem.Te/tO
R.V.COLLEGE OF ENGINEERING Page 1GA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
class Person
M
pu$lic string Name, SSNO
pu$lic $+te ageO
pu$lic Person(string n, string s, $+te a#
M
Name Q nO
SSN Q sO
age Q aO
N
pu$lic Person(#M N
$$ Overriding System.Object.ToString56
pu$lic override string ToString(#
M
StringBuilder s$ Q ne) StringBuilder(#O
s$.'ppend0ormat(RVNameQMGNR, this. Name#O
s$.'ppend0ormat(R SSNQMGNR, this.SSN#O
s$.'ppend0ormat(R 'geQMGNWR, this.age#O
return s$.ToString(#O
N
pu$lic static void Main(#
R.V.COLLEGE OF ENGINEERING Page 1GB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
Person p1 Q ne) Person(3"am5, 31141=5, =B#O
onsole.%rite!ine(3p1 is MGN5, p1.ToString(##O
N
N
The (utput )ould $e <
p1 is VNameQ"am SSNQ1141= 'geQ=BW
*n the a$ove e/ample, )e have overridden ToString(# method to displa+ the contents of the o$7ect in the
form of tuple. The S+stem.Te/t.StringBuilder is class )hich allo)s access to the $uffer of character data
and it is a more efficient alternative to & string concatenation (,iscussed later in detail#.
Overriding E@uals56
B+ default, S+stem.($7ect..Juals(# returns true onl+ if the t)o references $eing compared are referencing
same o$7ect in memor+. But in man+ situations, )e are more interested if the t)o o$7ects have the same
content. onsider an e/ample <
Program 1.-
using S+stemO
class Person
M
pu$lic string Name, SSNO
R.V.COLLEGE OF ENGINEERING Page 1GC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic $+te ageO
pu$lic Person(string n, string s, $+te a#
M
Name Q nO
SSN Q sO
age Q aO
N

pu$lic Person(#M N
pu$lic override $ool .Juals(o$7ect o$#
M
if (o$ LQ null UU o$ is Person#
M
Person p Q (Person#o$O

if (p.Name QQ this.Name UU p.SSN QQ this.SSN UU p.age QQ this.age#
return trueO
N
return falseO
N
pu$lic static void Main(#
M
Person p1 Q ne) Person(R"amR, R1141=R, =B#O
R.V.COLLEGE OF ENGINEERING Page 1GD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Person p= Q ne) Person(RSh+amR, R1141GR, =G#O
Person p@ Q ne) Person(R"amR, R1141=R, =B#O
Person pA Q p=O
if(p1..Juals(p=##
onsole.%rite!ine(Rp1 and p= are sameR#O
else
onsole.%rite!ine(Rp1 and p= are not sameR#O
if(p1..Juals(p@##
onsole.%rite!ine(Rp1 and p@ are sameR#O
else
onsole.%rite!ine(Rp1 and p@ are not sameR#O
if(p=..Juals(pA##$$com!ares based on content? not on re"erence
onsole.%rite!ine(RpA and p= are sameR#O
else
onsole.%rite!ine(RpA and p= are not sameR#O
N
N
The (utput )ould $e <
p1 and p= are not same
p1 and p@ are same
pA and p= are same
R.V.COLLEGE OF ENGINEERING Page 1GE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
%hile overriding the .Juals(# method, first )e are checking )hether the passed o$7ect is of class 5erson
or not. 'lso, )e need to check )hether the o$7ect has $een allocated memor+ or it is having null. Note
that .Juals(# method takes the parameter of t+pe ob/ect. Thus, )e need to t+pe4cast it to 5erson t+pe
$efore using it. %hen )e override .Juals(#, )e need to override 1et;ashode(# too.
Overriding System.Object.EetQas2Code56
The 1et;ashode(# method is suita$le for use in hashing algorithms and data structures
such as a hash ta$le.
The 1et;ashode(# method returns a numerical value used to identif+ an o$7ect in the
memor+.
The default implementation of the 1et;ashode(# method does not guarantee uniJue
return values for different o$7ects.
0urthermore, the .N.T 0rame)ork does not guarantee the default implementation of the
1et;ashode(# method, and the value it returns )ill $e the same $et)een different
versions of the .N.T 0rame)ork.
So, the default implementation of this method must not $e used as a uniJue o$7ect
identifier for hashing purposes.
*f )e place a custom (user4defined# o$7ect into a S+stem.ollections.;ashta$le t+pe, its
.Juals(# and 1et;ashode(# mem$ers )ill determine the correct t+pe to return from the
container.
So, user4defined t+pes should redefine the hashing algorithm used to identif+ itself )ithin
such a t+pe.
There are man+ algorithms that can $e used to create a hash code. *n the simplest case, an
o$7ect9s hash value )ill $e generated $+ taking its data into consideration and $uilding a uniJue
numerical identifier for the t+pe. 0or e/ample, SSN )ill $e uniJue for each individual. So, )e
can override 1et;ashode(# method as $elo) <
Program 1.O
R.V.COLLEGE OF ENGINEERING Page 1GF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
using S+stemO
class Person
M
pu$lic string Name, SSNO
pu$lic $+te ageO
pu$lic Person(string n, string s, $+te a#
M
Name Q nO
SSN Q sO
age Q aO
N

pu$lic Person(#M N

pu$lic override int 1et;ashode(#
M
return SSN.1et;ashode(#O
N
pu$lic static void Main(#
M
Person p1 Q ne) Person(R"amR, R1141=R, =B#O
Person p= Q ne) Person(RSh+amR, R1141GR, =G#O
Person p@ Q ne) Person(R"amR, R1141=R, =B#O
R.V.COLLEGE OF ENGINEERING Page 11G
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Person pA Q p=O
if(p1..Juals(p@## ??comparison $ased on reference
onsole.%rite!ine(Rp1 and p@ are sameR#O
else
onsole.%rite!ine(Rp1 and p@ are not sameR#O
if(p1.1et;ashode(#QQp@.1et;ashode(## ??comparison $ased on SSN
onsole.%rite!ine(Rp1 and p@ are sameR#O
else
onsole.%rite!ine(Rp1 and p@ are not sameR#O
N
N
The output )ould $e <
p1 and p@ are not same
p1 and p@ are same
1.=G T2e System 1ata Ty!es 5and C7 (liases6
.ver+ intrinsic & data t+pe is an alias to an e/isting t+pe defined in the S+stem namespace. Specificall+,
each & data t+pe aliases a )ell4defined structure t+pe in the S+stem namespace. 0ollo)ing ta$le lists
each s+stem data t+pe, its range, the corresponding & alias and the t+pe9s compliance )ith the !S.
C7 (lias C#S
Com!liantH
System Ty!e 4ange Meaning
s$+te No S+stem.SB+te 41=E to 1=D Signed E4$it num$er
$+te -es S+stem.B+te G to =BB Unsigned E4$it num$er
R.V.COLLEGE OF ENGINEERING Page 111
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
short -es S+stem.*nt1C 4=
1C
to =
1C
41 Signed 1C4$it num$er
ushort No S+stem.U*nt1C G to =
@=
41 Unsigned 1C4$it num$er
int -es S+stem.*nt@= 4=
@=
to =
@=
41 Signed @=4$it num$er
uint No S+stem.U*nt@= G to =
CA
41 Unsigned @=4$it num$er
long -es S+stem.*ntCA 4=
CA
to =
CA
41 Signed CA4$it num$er
ulong No S+stem.U*ntCA G to =
1=E
41 Unsigned CA4$it num$er
char -es S+stem.har U1GGGG to
U1ffff
' Single 1C4$it Unicode
character
float -es S+stem.Single 1.B / 1G
4AB
to
@.A / 1G
@E
@=4$it floating point num$er
dou$le -es S+stem.,ou$le B.G / 1G
4@=A
to
1.D / 1G
@GE
CA4$it floating point num$er
$ool -es S+stem.Boolean True or 0alse "epresents truth or falsit+
decimal -es S+stem.,ecimal 1 to 1G
=E
FC4$it signed num$er
string -es S+stem.String !imited $+
s+stem memor+
"epresents a set of Unicode
characters
o$7ect -es S+stem.($7ect 'n+thing(all
t+pes e/cluding
interfaces#
derive from
o$7ect
The $ase class of all t+pes in
the .N.T universe.
The relationship $et)een the core s+stem t+pes is sho)n in the figure 1.1. 0rom this diagram, )e can see
that all the t+pes are ultimatel+ derived from S+stem.($7ect. Since the data t+pes like int are simpl+
shorthand notations for the corresponding s+stem t+pe (like S+stem.*nt@=#, the follo)ing statements are
valid <
onsole.%rite!ine(=B.1et;ashode(##O
onsole.%rite!ine(@=.1etT+pe(#.BaseT+pe(##O etc.
%e can see that, though & defines a num$er of data t+pes, onl+ a su$set of the )hole set of data t+pes
are compliant )ith the rules of !S. So, )hile $uilding user4defined t+pes (like class, structures#, )e
should use onl+ !S4compliant t+pes. 'nd also, )e should avoid using unsigned t+pes as pu$lic mem$er
of user4defined t+pe. B+ doing this, our user4defined t+pe (class, enumeration, structure etc# can $e
understood $+ an+ language in .N.T frame)ork.
E;!erimenting 0it2 t2e System 1ata Ty!es
R.V.COLLEGE OF ENGINEERING Page 11=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
0rom the 0igure @.1, it is clear that & data t+pes are alias names for a related structure in the S+stem
namespace, and hence derived from S+stem.2alueT+pe. The purpose of S+stem.2alueT+pe is to override
the virtual methods defined $+ S+stem.($7ect to )ork )ith value4$ased v?s reference4$ased semantics.
Since data t+pes are value t+pes, the comparison of t)o varia$les )ill $e $ased on their internal value, $ut
not the reference6
S+stem.*nt@= aQ=GO
int $Q=GO
if(aQQ$# ??comparison $ased on value
onsole.%rite!ine(3SameLL5#O
R.V.COLLEGE OF ENGINEERING Page 11@
ObHect
Ty(e
String
Array
!0ce(ti%n
Delegate
MulticastDelegate
Byte
B%%lean
Char
Deci&al
D%uble
Int-9
Int96
Int53
UInt-9
UInt53
UInt96
D%id
DateTi&e
Guid
Ti&eS(an
SByte
Single
(alueType
Any ty(e that
deri8es )r%&
DalueTy(e is a
structure n%t a
class
!nu&erati%ns and Structures
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
R.V.COLLEGE OF ENGINEERING Page 11A
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
*ig. 1.1 T2e 2ierarc2y o" System Ty!es
,asic Numerical Members
To understand the numerical t+pes in &, consider the follo)ing e/ample <
Program 1.N

using S+stemO
class Test
M
pu$lic static void Main(#
M
S+stem.U*nt1C aQ@GGGGO
onsole.%rite!ine(RMa/ value for U*nt1C6 MGNR, U*nt1C.Ma/2alue#O $$-II&I
onsole.%rite!ine(RMin value for U*nt1C6 MGNR, U*nt1C.Min2alue#O $$.
onsole.%rite!ine(Rvalue of U*nt1C6 MGNR, a#O $$&....
onsole.%rite!ine(RThe t+pe is6 MGNR, a.1etT+pe(#.ToString(##O $$System.Unt1-
R.V.COLLEGE OF ENGINEERING Page 11B
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
ushort $Q1=GGGO
onsole.%rite!ine(RMa/ value for ushort6 MGNR, ushort.Ma/2alue#O $$-II&I
onsole.%rite!ine(RMin value for ushort6 MGNR, ushort.Min2alue#O $$.
onsole.%rite!ine(Rvalue of ushort6 MGNR, $#O $$1'...
onsole.%rite!ine(RThe t+pe is6 MGNR, $.1etT+pe(#.ToString(##O $$System.Unt1-
onsole.%rite!ine(Rdou$le..psilon6 MGNR, dou$le..psilon#O
$$9.L9.-I-9IN91'9OE8&'9
onsole.%rite!ine(Rdou$le.Positive*nfinit+6 MGNR, dou$le.Positive*nfinit+#O
$$n"inity
onsole.%rite!ine(Rdou$le.Negative*nfinit+6 MGNR, dou$le.Negative*nfinit+#O
$$8n"inity
onsole.%rite!ine(Rdou$le.Ma/2alue6 MGNR, dou$le.Ma/2alue#O
$$ 1.OLO-L&1&9N-'&'E)&.N
onsole.%rite!ine(Rdou$le.Min2alue6 MGNR, dou$le.Min2alue#O
$$81.OLO-L&1&9N-'&'E)&.N
N
N
Members o" System.,oolean
*n &, for Boolean data, )e have to assign an+ one value true or false. %e can not use the num$ers like
41, G, 1 etc. as )e do in HH. The usage of $ool data is sho)n in Program 1.F.
Members o" System.C2ar
R.V.COLLEGE OF ENGINEERING Page 11C
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
'll the .N.T4a)are languages map te/tual data into the same underl+ing t+pes vi8 S+stem.String and
S+stem.har, $oth are Unicode. The S+stem.har t+pe provides several methods as sho)n in the
follo)ing e/ample <
Program 1.L
using S+stemO
class Test
M
pu$lic static void Main(#
M
$ool $1QtrueO
$ool $=QfalseO
onsole.%rite!ine(RMGNR, $ool.0alseString#O $$*alse
onsole.%rite!ine(RMGNR, $ool.TrueString#O $$True
onsole.%rite!ine(RMGN, M1NR, $1, $=#O $$True? *alse
onsole.%rite!ine(RMGNR, char.*s,igit(^P^##O $$*alse
onsole.%rite!ine(RMGNR, char.*s,igit(^F^##O $$True
onsole.%rite!ine(RMGNR, char.*s!etter(R1GR, 1##O $$*alse
onsole.%rite!ine(RMGNR, char.*s!etter(R1aR, 1##O $$True
onsole.%rite!ine(RMGNR, char.*s!etter(^p^##O $$True
onsole.%rite!ine(RMGNR, char.*s%hiteSpace(R;ello %orldR, B##O $$True
onsole.%rite!ine(RMGNR, char.*s%hiteSpace(R;ello %orldR, C##O $$*alse
onsole.%rite!ine(RMGNR, char.*s!etter(r,igit(^P^##O $$*alse
R.V.COLLEGE OF ENGINEERING Page 11D
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsole.%rite!ine(RMGNR, char.*sPunctuation(^L^##O $$True
onsole.%rite!ine(RMGNR, char.*sPunctuation(^X^##O $$*alse
onsole.%rite!ine(RMGNR, char.*sPunctuation(^,^##O $$True
N
N
Parsing +alues "rom String 1ata
.N.T data t+pes provide the a$ilit+ to generate a varia$le of their underl+ing t+pe given a te/tual
eJuivalent. This techniJue is called as parsing. This is helpful )hen )e need to convert user input data
into a numerical value. onsider the follo)ing program <
Program 1.1.
using S+stemO
class Test
M
pu$lic static void Main(#
M
$ool $Q$ool.Parse(RTrueR#O
onsole.%rite!ine(R2alue of $ool is6MGNR, $#O ??True
dou$le dQdou$le.Parse(RFF.ABDR#O
onsole.%rite!ine(R2alue of dou$le is6MGNR, d#O ??FF.ABD
R.V.COLLEGE OF ENGINEERING Page 11E
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
int iQint.Parse(RER#O
onsole.%rite!ine(R2alue of int is6MGNR, i#O ??E
char cQchar.Parse(R)R#O
onsole.%rite!ine(R2alue of char is6MGNR, c#O ??)
N
N
1.=1 ,o;ing and Un8bo;ing
%e kno) that .N.T defines t)o $road categories of t+pes vi8. value t+pes and reference t+pes.
Sometimes, )e ma+ need to convert varia$les of one categor+ to the varia$les of other categor+. 0or
doing so, .N.T provides a mechanism called boxing.
Bo/ing can $e defined as the process of e/plicitl+ converting a value t+pe into a reference t+pe.
%hen )e bo' a varia$le, a ne) o$7ect is allocated in the heap and the value of varia$le is copied
into the o$7ect.
0or e/ample,
int pQ=GO
o$7ect o$QpO ??$o/ the value t+pe p into an o$7ect reference
The operation 7ust opposite to $o/ing is called as unboxing.
Un$o/ing is the process of converting the value held in the o$7ect reference $ack into a
corresponding value t+pe.
%hen )e tr+ to un$o/ an o$7ect, the compiler first checks )hether is the receiving data t+pe is
eJuivalent to the $o/ed t+pe or not.
R.V.COLLEGE OF ENGINEERING Page 11F
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
*f +es, the value stored in the o$7ect is copied into a varia$le in the stack.
*f )e tr+ to un$o/ an o$7ect to a data t+pe other than the original t+pe, an e/ception called
*nvalidast./ception is generated.
0or e/ample,
int pQ=GO
o$7ect o$QpO
44444444
4444444
int $Q(int#o$O ?? un$o/ing successful
string sQ(string#o$O ?? *nvalidast./ception
1enerall+, there )ill fe) situations in )hich )e need $o/ing and?or un$o/ing. *n most of the situations,
& compiler )ill automaticall+ $o/es the varia$les. 0or e/ample, if )e pass a value t+pe data to a
function having reference t+pe o$7ect as a parameter, then automatic $o/ing takes place. onsider the
follo)ing program <
Program 1.11
using S+stemO
class Test
M
pu$lic static void M+0unc(o$7ect o$#
M
onsole.%rite!ine(o$.1etT+pe(##O
onsole.%rite!ine(o$.ToString(##O
onsole.%rite!ine(((int#o$#.1etT+peode(##O
R.V.COLLEGE OF ENGINEERING Page 1=G
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
pu$lic static void Main(#
M
int /Q=GO
M+0unc(/#O
N
N
The output )ould $e <
S+stem.*nt@=
=G
*nt@=
NOTE:
1. Bo/ing and un$o/ing takes some processing time. So, it must $e used onl+ )hen needed.
=. %hen )e pass custom (user defined# structures?enumerations into a method taking generic
S+stem.($e7ct parameter, )e need to un$o/ the parameter to interact )ith the specific mem$ers
of the structure?enumeration. %e )ill stud+ this later in4detail.
1.== Summary
This section revealed the value t+pes and reference t+pes in .N.T frame)ork. %e have seen ho) value
t+pes and reference t+pes $ehave in various situations. %e have also discussed the $asic methods of
S+stem.($7ect class and ho) to override them according to our need in the program. The $o/ing and un4
$o/ing techniJues allo) the programmer to s)itch $et)een value t+pes and reference t+pes in the
program.
R.V.COLLEGE OF ENGINEERING Page 1=1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1.=@ :ey0ords
2alue T+pe and "eference T+pe
Stack area and ;eap area
Shallo) op+ and ,eep op+
Mem$ers of S+stem.Boolean, S+stem.har and numeric mem$ers
Parsing values from Sting t+pe
Bo/ing and un$o/ing
1.=A E;ercises
-# .rite a (r%gra& t% illustrate the di))erence bet2een (assing re)erence ty(es by re)erence
and by 8alue#
3# Bring %ut the di))erence bet2een 8alue ty(es and re)erence ty(es#
5# I%2 d% y%u %8erride T%String"$ &eth%d %) Syste&#ObHect class4 !0(lain 2ith a (r%gra&#
6# !0(lain the c%nce(t %) GetIashC%de"$ &eth%d#
7# Dra2 a diagra& t% de(ict the hierarchy %) Syste& ty(es and e0(lain#
9# .hat is b%0ing and unb%0ing4 !0(lain 2ith an e0a&(le )%r each#
:# .hat is the %ut(ut (rinted by the )%ll%2ing c%de seg&ent and 2hy4
struct Point
M
pu$lic int /, +O
pu$lic Point(int /, int +#
R.V.COLLEGE OF ENGINEERING Page 1==
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
this./Q/ O
this.+Q+ O
N
N
Point pQne) Point(1G,1G# O
o$7ect o$7Qp O
p./Q=GO
onsole.%rite!ine(3p./QMGN5, p./#O
onsole.%rite!ine(Ro$7./QMGNR, ((Point#o$7#./# O
Module '
Unit '
CONTENTS:
=.1@ ($7ectives
=.1A *ntroduction
=.1B ,efining ustom lass Methods
=.1C Understanding Static Methods
=.1D Methods Parameter Modifiers
=.1E 'rra+ Manipulation in &
=.1F String Manipulation in &
=.=G & .numerations
=.=1 ,efining Structures in &
=.== ,efining ustom Namespaces
=.=@ Summar+
=.=A :e+)ords
=.=B ./ercises
R.V.COLLEGE OF ENGINEERING Page 1=@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
=.1 Objectives
't the end of this lesson, students )ill understand the follo)ing tasks in detail6
,efining User4defined?ustom methods for a class
Static Mem$ers (,ata and Method# of a class
The parameter modifiers like out, params, ref
Mem$ers of 'rra+ and String class
Manipulation of 'rra+s and Strings
& enumeration and structures
oncept of user4defined?custom namespaces
=.1@ ntroduction
*n all the previous units, )e have discussed $asic concepts of & programming language. ;ere, )e )ill
continue )ith understanding ho) to define o)n methods for a class, the concept of static mem$ers of a
class, ho) to define our o)n namespace $ased on the reJuirements and so on. 'lso, )e )ill ela$orate the
value t+pes of & vi8. structure and enumeration t+pes.
=.1A 1e"ining Custom Class Met2ods
*n &, ever+ data and a method must $e a mem$er of a class or structure. That is, )e can not have glo$al
data or method. The methods in & ma+ or ma+ not take parameters and the+ ma+ or ma+ not return a
value. 'lso, custom methods (user defined methods# ma+ $e declared non4static (instance level# or static
(class level#.
Met2od (ccess Modi"iers
.ver+ method in & specifies its level of accessi$ilit+ using follo)ing access modifiers6
R.V.COLLEGE OF ENGINEERING Page 1=A
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
(ccess Modi"iers Meaning
pu$lic Method is accessi$le from an o$7ect or an+ su$class.
private Method is accessi$le onl+ $+ the class in )hich it is defined.
private is a default modifier in &.
protected Method is accessi$le $+ the defining class and all its su$4
classes.
internal Method is pu$licl+ accessi$le $+ all t+pes in an assem$l+, $ut
not outside the assem$l+.
protected internal Method9s access is limited to the current assem$l+ or t+pes
derived from the defining class in the current assem$l+.
=.1B Understanding Static Met2ods
' method can $e declared as static. %hen a method is static, it can $e invoked directl+ from the class
level, )ithout creating an o$7ect. This is the reason for making !ain,- function to $e static. The another
e/ample is (riteLine,- method. %e )ill directl+ use the statement #onsole.(riteLine,- )ithout creating
an o$7ect of #onsole class. onsider the follo)ing program6
Program '.1
using S+stemO
class Test
M
pu$lic static void disp(#
M
onsole.%rite!ine(3hello5#O
N
pu$lic static void Main(#
M
R.V.COLLEGE OF ENGINEERING Page 1=B
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Test.disp(#O ??calling method using class name itself
N
N
1e"ining static 1ata
Normall+, )e )ill define a set of data mem$ers for a class. Then ever+ o$7ect of that class )ill have
separate cop+ of each of those data mem$ers. 0or e/ample,
class Test
M
pu$lic int pO
N
4444444
444444
Test t1Qne) Test(#O
t1.pQ1GO
Test t=Q ne) Test(#O
t=.pQ1BO
;ere, the o$7ects t2 and t1 )ill $e having separate cop+ of the varia$le p.
(n the other hand, static data is shared among all the o$7ects of that class. That is, for all the o$7ects of a
class, there )ill $e onl+ one cop+ of static data. 0or e/ample,
Program '.'
R.V.COLLEGE OF ENGINEERING Page 1=C
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
using S+stemO
class Test
M
pu$lic static int pQGO
pu$lic int incr(#
M
return HHpO
N
pu$lic static void Main(#
M
Test t1Qne) Test(#O
Test t=Qne) Test(#O
onsole.%rite!ine(RpQ MGNR, t1.incr(##O ??1
onsole.%rite!ine(RpQ MGNR, t=.incr(##O ??=
onsole.%rite!ine(RpQ MGNR, t1.incr(##O ??@
N
N

=.1C Met2od Parameter Modi"iers
Normall+ methods )ill take parameter. %hile calling a method, parameters can $e passed in different
)a+s. & provides some parameter modifiers as sho)n <
R.V.COLLEGE OF ENGINEERING Page 1=D
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Parameter Modi"ier Meaning
(none# *f a parameter is not attached )ith an+ modifier, then
parameter9s value is passed to the method. This is the default
)a+ of passing parameter. (call4$+4value#
out The output parameters are assigned $+ the called method.
ref "eference to a parameter is passed to a method. (call4$+4
reference#
params This modifier )ill allo) to send man+ num$er of parameters as
a single parameter. 'n+ method can have onl+ one params
modifier and it should $e the last parameter for the method.
T2e 1e"ault Parameter Passing ,e2avior
B+ default, the parameters are passed to a method by value. So, the changes made for parameters )ithin a
method )ill not affect the actual parameters of the calling method. onsider the follo)ing e/ample <

Program '.&
using S+stemO
class Test
M
pu$lic static void s)ap(int /, int +#
M
int tempQ/O
/Q+O
+QtempO
N
pu$lic static void Main(#
M
int /QB,+Q=GO
R.V.COLLEGE OF ENGINEERING Page 1=E
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsole.%rite!ine(RBefore6 /QMGN, +QM1NR, /, +#O
s)ap(/,+#O
onsole.%rite!ine(R'fter6 /QMGN, +QM1NR, /, +#O
N
N
The output )ould $e <
Before6 /QB, +Q=G
'fter 6 /QB, +Q=G
T2e out :ey0ord
*n some of the methods, )e need to return a value to a calling method. *nstead of using return statement,
& provides a modifier for a parameter as out. The usage of out can $e $etter understood $+ the follo)ing
e/ample <
Program '.9
using S+stemO
class Test
M
pu$lic static void add(int /, int +, out int 8#
M
8Q/H+O
N
R.V.COLLEGE OF ENGINEERING Page 1=F
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic static void Main(#
M
int /QB,+Q=G, 8O
add(/, +, out 8#O
onsole.%rite!ine(R8QMGNR, 8#O ??8Q=B
N
N
The out parameter is certainl+ useful )hen )e need more values to $e returned from a method. onsider
the follo)ing e/ample <
Program '.I
using S+stemO
class Test
M
pu$lic static void M+0un(out int /, out string s#
M
/QBO
sQR;ello, ho) are +ouPRO
N
pu$lic static void Main(#
M
R.V.COLLEGE OF ENGINEERING Page 1@G
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
int aO
string strO
M+0un(out a, out str#O
onsole.%rite!ine(RaQMGN, strQM1NR, a, str#O
N
N
The output )ould $e <
aQB, strQ5;ello, ho) are +ouP
T2e C7 re :ey0ord
%henever )e )ant the changes made in method to get affected in the calling method, then )e )ill go for
call $+ ref. 0ollo)ing are the differences $et)een output and reference parameters6
The output parameters do not need to $e initiali8ed $efore sending to called method. Because it is
assumed that the called method )ill fill the value for such parameter.
The reference parameters must $e initiali8ed $efore sending to called method. Because, )e are
passing a reference to an e/isting t+pe and if )e don9t assign an initial value, it )ould $e
eJuivalent to )orking on NU!! pointer.
Program '.-
using S+stemO
class Test
M
R.V.COLLEGE OF ENGINEERING Page 1@1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic static void Main(#
M
string sQRhelloRO
onsole.%rite!ine(RBefore6MGNR,s#O
M+0un(ref s#O
onsole.%rite!ine(R'fter6MGNR,s#O
N
pu$lic static void M+0un(ref string s#
M
sQs.ToUpper(#O
N
N
The output )ould $e <
Before6 hello
'fter6 ;.!!(
T2e C7 params :ey0ord
The params ke+)ord of & allo)s us to send man+ num$ers of arguments as a single parameter. To
illustrate the use of params, consider the follo)ing e/ample <
R.V.COLLEGE OF ENGINEERING Page 1@=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Program '.O
using S+stemO
class Test
M
pu$lic static void M+0un(!arams intVW arr#
M
for(int iQGO iXarr.!engthO iHH#
onsole.%rite!ine(arrViW#O
N
pu$lic static void Main(#
M
intVW aQne) intV@WMB, 1G, 1BNO
int pQ=B, JQ1G=O
M+0un(a#O
M+0un(p, J#O
N
N
The output )ould $e <
B 1G 1B =B 1G=
R.V.COLLEGE OF ENGINEERING Page 1@@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
0rom the a$ove e/ample, )e can o$serve that for params parameter, )e can pass an arra+ or individual
elements.
%e can use params even )hen the parameters to $e passed are of different t+pes, as sho)n in the
follo)ing program <
Program '.N
using S+stemO
class Test
M
pu$lic static void M+0un(params o$7ectVW arr#
M
for(int iQGO iXarr.!engthO iHH#
M
if(arrViW is *nt@=#
onsole.%rite!ine(RMGN is an integerR, arrViW#O
else if(arrViW is string#
onsole.%rite!ine(RMGN is a stringR, arrViW#O
else if(arrViW is $ool#
onsole.%rite!ine(RMGN is a $ooleanR, arrViW#O
N
N
pu$lic static void Main(#
M
int /QBO
R.V.COLLEGE OF ENGINEERING Page 1@A
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
string sQRhelloRO
$ool $QtrueO
M+0un($, /, s#O
N
N
The output )ould $e <
True is a Boolean
B is an integer
hello is a string
Passing 4e"erence Ty!es by +alue and 4e"erence
Till no), )e have seen ho) to pass a parameter to methods $+ value and $+ using ref. *n the previous
e/amples, )e have passed value type varia$les as parameters to methods (Iust recollect that there are t)o
t+pes of varia$les value type like int, char, string, structure etc. and reference type like class, delegates#.
No) )e )ill see )hat happens )hen reference type varia$les (i.e. o$7ects of class# are passed as
parameters. onsider the program <
Program '.L
using S+stemO
class Person
M
string nameO
R.V.COLLEGE OF ENGINEERING Page 1@B
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
int ageO
pu$lic Person(string n, int a#
M
nameQnO
ageQaO
N
pu$lic static void allB+2al(Person p#
M
p.ageQCCO
pQne) Person(RSh+amuR, =B#O
N
pu$lic static void allB+"ef(ref Person p#
M
p.ageQBBO
pQne) Person(RSh+amuR, =G#O
N
pu$lic void disp(#
M
onsole.%rite!ine(RMGN M1NR, name, age#O
N
pu$lic static void Main(#
R.V.COLLEGE OF ENGINEERING Page 1@C
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
Person p1Qne) Person(R"amuR, @G#O
p1.disp(#O
allB+2al(p1#O
p1.disp(#O
allB+"ef(ref p1#O
p1.disp(#O
N
N
The output )ould $e <
"amu @G
"amu CC
Sh+amu =G
*n the Main(# function, )e have created an o$7ect p2 of 5erson class. Memor+ )ill $e allocated to p2
from heap as p2 is of reference t+pe (o$7ect of a class#. No), the displa+ )ill $e <
"amu @G
No) )e are passing p2 to the function using call4$+4value method. But, $+ nature, p2 is of reference t+pe.
So, in the receiving end, the o$7ect p takes the reference of p2. That means, the memor+ location for $oth
p2 and p )ill $e same. Thus, the statement
p.age Q CCO
)ill affect the original o$7ect p2. 'nd hence the output )ill $e <
R.V.COLLEGE OF ENGINEERING Page 1@D
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
"amu CC
But, )hen )e tr+ to allocate ne) memor+ for p, the compiler )ill treat p as different o$7ect and ne)
memor+ is allocated from heap. No) on)ards, p and p2 are different.
Ne/t, )e are passing p2 using the modifier ref. This is nothing $ut call4$+4reference. ;ere also, the
receiving o$7ect p )ill $e a reference to p2. Since the parameter passing techniJue used is call4$+4
reference, as per the definition, an+ changes in method should affect the calling method. Thus, the
statement
pQ ne) Person(3Sh+amu5, =G#O
)ill affect the original o$7ect p2 and hence the output is <
Sh+amu =G
NOTE: The important rule to $e remem$ered is6 R" a class ty!e 5re"erence ty!e6 is !assed by
re"erence? t2e called met2od 0ill c2ange t2e values o" t2e objectSs data and also t2e object it is
re"erencingT.
=.1D (rray Mani!ulation in C7
& arra+s look like that of ?HH. But, $asicall+, the+ are derived from the $ase class vi8. S+stem.'rra+.
'rra+ is a collection of data elements of same t+pe, )hich are accessed using numerical inde/. Normall+,
in &, the arra+ inde/ starts )ith G. But it is possi$le to have an arra+ )ith ar$itrar+ lo)er $ound using
the static method reate*nstance(# of S+stem.'rra+. 'rra+s can $e single or multi4dimensional. The
declaration of arra+ )ould look like <
R.V.COLLEGE OF ENGINEERING Page 1@E
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
intV W aQ ne) intV1GWO
aVGWQ BO
aV1WQ 1AO
]]].
stringV W sQ ne) stringV=WM3"amu5, 3Sh+mu5NO
intV W $QM1B, =B, @1, DENO ??ne) is missing. Still valid
*n .N.T, the mem$ers of arra+ are automaticall+ set to their respective default value. 0or e/ample, in the
statement,
intV W aQ ne) intV1GWO
all the elements of a are set to G. Similarl+, string arra+ elements are set to null and so on.
(rray as Parameters and 4eturn +alues
'rra+ can $e passed as parameter to a method and also can $e returned from a method. onsider the
follo)ing e/ample <
Program '.1.
using S+stemO
class Test
M
pu$lic static void disp(intV W arr# ??taking arra+ as parameter
M
for(int iQGOiXarr.!engthOiHH#
onsole.%rite!ine(RMGN R, arrViW#O
R.V.COLLEGE OF ENGINEERING Page 1@F
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
pu$lic static stringV W M+0un(# ??returning an arra+
M
stringV W strQMR;elloR, R%orldRNO
return strO
N
pu$lic static void Main(#
M
intV W pQne) intV WM=G, BA, 1=, 4BCNO
disp(p#O
stringV W strsQM+0un(#O
foreach(string s in strs#
onsole.%rite!ine(s#O
N
N
The output )ould $e <
=G BA 1= 4BC ;ello %orld
%or3ing 0it2 Multidimensional (rrays
There are t)o t+pes of multi4dimensional arra+s in & vi8. rectangular array and /agged array. The
rectangular arra+ is an arra+ of multiple dimensions and each ro) is of same length. 0or e/ample <
R.V.COLLEGE OF ENGINEERING Page 1AG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Program '.11
using S+stemO
class Test
M
pu$lic static void Main(#
M
intV,W arrQne) intV=,@WMMB, D, GN, M@, 1, ENNO
int sumQGO
for(int iQGOiX=O iHH#
for(int 7QGO7X@O7HH#
sumQsumHarrVi,7WO
onsole.%rite!ine(RSum is MGNR, sum#O
N
N
The output )ould $e <
Sum is =A
Iagged arra+ contain some num$er of inner arra+s, each of )hich ma+ have uniJue si8e. 0or e/ample <
R.V.COLLEGE OF ENGINEERING Page 1A1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Program '.1'
using S+stemO
class Iagged'rra+
M
pu$lic static intVWVW I'rrQne) intV@WVWO
pu$lic static void Main(#
M
int m, n, p, sumQGO
onsole.%rite!ine(R.nter the si8es for @ inner arra+s6R#O
mQint.Parse((onsole."ead!ine(##.ToString(##O
nQint.Parse((onsole."ead!ine(##.ToString(##O
pQint.Parse((onsole."ead!ine(##.ToString(##O
I'rrVGWQne) intVmWO
I'rrV1WQne) intVnWO
I'rrV=WQne) intVpWO
onsole.%rite!ine(R.nter the elements for arra+6R#O
for(int iQGOiX@OiHH#
for(int 7QGO7XI'rrViW.!engthO7HH#
M
I'rrViWV7WQint.Parse((onsole."ead!ine(##.ToString(##O
sumQsumHI'rrViWV7WO
R.V.COLLEGE OF ENGINEERING Page 1A=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
onsole.%rite!ine(R[nThe Sum is6 MGNR,sum#O
N
N
The output )ould $e <
.nter the si8es for @ inner arra+s6
= @ =
.nter the elements for arra+6
1 = @ A B C D
The Sum is6 =E
T2e System.(rray ,ase Class
.ver+ arra+ in & is derived from the class S+stem.'rra+. This class defines num$er of methods to )ork
)ith arra+s. 0e) of the methods are given $elo) <
Member Meaning
Binar+Search(# This static method searches a (previousl+ sorted# arra+ for a given item. *f the arra+
is composed of user4defined data t+pes, the t+pe in Juestion must implement the
*omparer interface to engage in a $inar+ search.
lear(# This static method sets a range of elements in the arra+ to empt+ values (G for value
t+pesO null for reference t+pes#.
op+To(# This method is used to cop+ elements from the source arra+ into the destination
arra+.
!ength This read4onl+ propert+ is used to determine the num$er of elements in an arra+.
"ank This propert+ returns the num$er of dimensions of the current arra+.
"everse(# This static method reverses the contents of a one4dimensional arra+.
R.V.COLLEGE OF ENGINEERING Page 1A@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Sort(# This method sorts a one4dimensional arra+ of intrinsic t+pes. *f the elements in the
arra+ implement the *omparer interface, )e can also sort an arra+ of user4defined
data t+pe .

onsider the follo)ing e/ample to illustrate some methods and?or properties of S+stem.'rra+ class <
Program '.1&
using S+stemO
class Test
M
pu$lic static void Main(#
M
intVW arrQne) intVBWM1=, G, AB, @=, CDNO
onsole.%rite!ine(R'rra+ elements are 6R#O
for(int iQGOiXarr.!engthOiHH#
onsole.%rite!ine(RMGN[tR, arrViW#O
'rra+."everse(arr#O
onsole.%rite!ine(R"eversed 'rra+ elements are 6R#O
for(int iQGOiXarr.!engthOiHH#
onsole.%rite!ine(RMGN[tR, arrViW#O
R.V.COLLEGE OF ENGINEERING Page 1AA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
'rra+.lear(arr, 1, @#O
onsole.%rite!ine(Rleared some elements 6R#O
for(int iQGOiXarr.!engthOiHH#
onsole.%rite!ine(RMGN[tR, arrViW#O
N
N
The (utput )ould $e <
'rra+ elements are6
1= G AB @= CD
"eversed 'rra+ elements are6
CD @= AB G 1=
leared some elements6
CD G G G 1=
=.1E String Mani!ulation in C7
Till no), )e have used string ke+ )ord as a data t+pe. But trul+ speaking, string is an alias t+pe for
System.String class. This class provides a set of methods to )ork on strings. 0ollo)ing is a list of fe)
such methods <
Member Meaning
!ength This propert+ returns the length of the current string.
ontains(# This method is used to determine if the current string o$7ect contains a specified string.
oncat(# This static method of the String class returns a ne) string that is composed of t)o discrete
strings.
ompareTo(# ompares t)o strings.
R.V.COLLEGE OF ENGINEERING Page 1AB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
op+(# "eturns a fresh ne) cop+ of an e/isting string.
0ormat(# This static method is used to format a string literal using other primitives (i.e., numerical data
and other strings# and the MGN notation e/amined earlier in this chapter.
*nsert(# This method is used to receive a cop+ of the current string that contains ne)l+ inserted string
data.
Pad!eft(#
Pad"ight(#
These methods return copies of the current string that has $een padded )ith specific data.
"emove(#
"eplace(#
Use these methods to receive a cop+ of a string, )ith modifications (characters removed or
replaced#.
Su$string(# This method returns a string that represents a su$string of the current string.
Tohar'rra+(# This method returns a character arra+ representing the current string.
ToUpper(#
To!o)er(#
These methods create a cop+ of a given string in uppercase or lo)ercase.
onsider the follo)ing e/ample <
Program '.19
using S+stemO
class Test
M
pu$lic static void Main(#
M
S+stem.String s1QRThis is a stringRO
string s=QRThis is another stringRO
if(s1QQs=#
onsole.%rite!ine(RSame stringsR#O
R.V.COLLEGE OF ENGINEERING Page 1AC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
else
onsole.%rite!ine(R,ifferent stringsR#O
string s@Qs1Hs=O
onsole.%rite!ine(Rs@QMGNR,s@#O
for(int iQGOiXs1.!engthOiHH#
onsole.%rite!ine(Rhar MGN is M1N[nR,i, s1ViW#O
onsole.%rite!ine(Rotains ^is^P6 MGNR, s1.ontains(RisR##O
onsole.%rite!ine(s1."eplace(^a^,^ ^##O
N
N
The output )ould $e <
,ifferent strings
s@QThis is a stringThis is another string
har G is T har 1 is h har = is i har @ is s
har A is har B is * har C is s har D is
har E is a har F is har 1G is s har 11 is t
har 1= is r har 1@ is * har 1A is n har 1B is g
otains ^is^P6 True
This is string
R.V.COLLEGE OF ENGINEERING Page 1AD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Esca!e C2aracters and -)erbatim $trings.
Iust like , HH and Iava, & also provides some set of escape characters as sho)n <
C2aracter Meaning
[9 *nserts a single Juote into a string literal.
[R *nserts a dou$le Juote into a string literal.
[[ *nserts a $ackslash into a string literal. This can $e Juite helpful )hen defining file paths.
[a Triggers a s+stem alert ($eep#. 0or console applications, this can $e an audio clue to the user.
[$ Triggers a $ackspace.
[f Triggers a form feed.
[n *nserts a ne) line (on %in@= platforms#.
[r *nserts a carriage return.
[t *nserts a hori8ontal ta$ into the string literal
[u *nserts a Unicode character into the string literal.
[v *nserts a vertical ta$ into the string literal
[G "epresents NU!! character.
*n addition to escape characters, & provides the \4Juoted string literal notation named as ,erbatim
string. Using this, )e can $+pass the use of escape characters and define our literals. onsider the
follo)ing e/ample <
Program '.1I
using S+stemO
class Test
M
pu$lic static void Main(#
M
string s1QR* said, [R;i[RRO
onsole.%rite!ine(RMGNR,s1#O
R.V.COLLEGE OF ENGINEERING Page 1AE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
s1QR6[[Notes[[,otNet[[hapter@.docRO
onsole.%rite!ine(RMGNR,s1#O
string s=Q\R6[Notes[,otNet[hapter@.docRO
onsole.%rite!ine(RMGNR,s=#O
N
N
The output )ould $e <
* said, R;iR
6[Notes[,otNet[hapter@.doc
6[Notes[,otNet[hapter@.doc
Using $ystem.Text.$tring/uilder
*n the previous e/amples, )e tried to change the content of strings using various methods like 6eplace,-,
To7pper,- etc. But, the value of a string cannot $e modified once it is esta$lished. The methods like
6eplace,- ma+ seems to change the content of the string, $ut actuall+, those methods 7ust output a cop+ of
the string and the original string remains the same. 0or e/ample <
string s1Q5;ello5O
onsole.%rite!ine(3s1QMGN5, s1#O ??;ello
string s=Qs1.ToUpper(#O
onsole.%rite!ine(3s=QMGN5, s=#O ??;.!!(
onsole.%rite!ine(3s1QMGN5, s1#O ??;ello
R.V.COLLEGE OF ENGINEERING Page 1AF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Thus, )henever )e )ant to modif+ a string, )e should have a ne) string to store the modified version.
That is, ever+ time )e have to )ork on a cop+ of the string, $ut not the original. To avoid this in4
efficienc+, & provides a class called $tring/uilder contained in the namespace $ystem.Text. 'n+
modification on an instance of $tring/uilder )ill affect the underl+ing $uffer itself. onsider the
follo)ing e/ample <
Program '.1-
using S+stemO
using S+stem.Te/tO
class Test
M
pu$lic static void Main(#
M
StringBuilder s1Q ne) StringBuilder(R;elloR#O
s1.'ppend(R %orldR#O
onsole.%rite!ine(RMGNR,s1#O
string s=Qs1.ToString(#.ToUpper(#O
onsole.%rite!ine(RMGNR,s=#O
N
N
The output )ould $e <
R.V.COLLEGE OF ENGINEERING Page 1BG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
;ello %orld
;.!!( %("!,
=.1F C7 Enumerations

%hen num$er of values taken $+ a t+pe is limited, it is $etter to go for s+m$olic names rather than
numeric values. 0or e/ample, the marital status of a person can $e an+ one of !arried, (idowed,
7nmarried, %ivorced. To have such s+m$olic names, & provides enumerations <
enum MSStatus
M
Married, ??G
%ido)ed, ??1
Unmarried, ??=
,ivorced ??@
N
*n enumeration, the value for first s+m$olic name is automaticall+ initiali8ed to G and second to 1 etc. *f
)e )ant to give an+ specific value, )e can use <
enum MSStatus
M
Married Q1=B,
%ido)ed, ??1=C
Unmarried, ??1=D
,ivorced ??1=E
N
R.V.COLLEGE OF ENGINEERING Page 1B1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
(r
enum MSStatus
M
Married Q1=B,
%ido)edQG,
UnmarriedQ=@,
,ivorcedQ1=
N
B+ default, the storage t+pe used for each item of enumeration is S+stem.*nt@=. %e can change it, if )e
)ish <
enum MSStatus6 byte
M
Married Q1=B,
%ido)edQG,
UnmarriedQ=@,
,ivorcedQ1=
N
.numerations can $e used as sho)n $elo) <
Program '.1O
using S+stemO
R.V.COLLEGE OF ENGINEERING Page 1B=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
class Test
M
enum MSStatus6 $+te
M
Married Q1=B,
%ido)edQG,
UnmarriedQ=@,
,ivorcedQ1=
N
pu$lic static void Main(#
M
MSStatus p1, p=O
p1QMSStatus.MarriedO
p=QMSStatus.,ivorcedO
if(p1QQMSStatus.Married#
onsole.%rite!ine(Rp1 is marriedR#O $$ !1 is married
if(p=QQMSStatus.,ivorced#
onsole.%rite!ine(Rp= is MGNR, MSStatus.,ivorced#O $$!' is 1ivorced
N
N
T2e System.Enum ,ase Class
R.V.COLLEGE OF ENGINEERING Page 1B@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
The & enumerations are derived from S+stem..num class. This $ase class defines some methods for
)orking )ith enumerations.
Member Meaning
0ormat(# onverts a value of a specified enumerated t+pe to its eJuivalent string
representation according to the specified format
1etName(#
1etNames(#
"etrieves a name (or an arra+ containing all names# for the constant in the
specified enumeration that has the specified value
1etUnderl+ingT+pe(# "eturns the underl+ing data t+pe used to hold the values for a given
enumeration
1et2alues(# "etrieves an arra+ of the values of the constants in a specified
.numeration
*s,efined(# "eturns an indication of )hether a constant )ith a specified value
e/ists in a specified enumeration
Parse(# onverts the string representation of the name or numeric value of one or
more enumerated constants to an eJuivalent enumerated o$7ect
onsider the follo)ing e/ample to illustrate some of the methods of .num class.
Program '.1N
using S+stemO
class Test
M
enum MSStatus
M
Married ,
%ido)ed,
Unmarried,
,ivorced
R.V.COLLEGE OF ENGINEERING Page 1BA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
pu$lic static void Main(#
M
onsole.%rite!ine(.num.1etUnderl+ingT+pe(t+peof(MSStatus###O
'rra+ o$7 Q.num.1et2alues(t+peof(MSStatus##O
onsole.%rite!ine(RThis enum has MGN mem$ersR, o$7.!ength#O
foreach(MSStatus p in o$7#
M
onsole.%rite!ine(RString name6 MGNR, p.ToString(##O
onsole.%rite!ine(Rint6 (MGN#,R, .num.0ormat(t+peof(MSStatus#, p, R,R##O
onsole.%rite!ine(Rhe/6 (MGN#,R, .num.0ormat(t+peof(MSStatus#, p, R>R##O
N
if(.num.*s,efined(t+peof(MSStatus#, R%ido)edR##
onsole.%rite!ine(R%ido)ed is definedR#O
MSStatus p1 Q (MSStatus#.num.Parse(t+peof(MSStatus#, R,ivorcedR#O
onsole.%rite!ine(Rp1 is MGNR, p=.ToString(##O
MSStatus p=QMSStatus.MarriedO
if(p1Xp=#
onsole.%rite!ine(3p1 has less value than p=5#O
R.V.COLLEGE OF ENGINEERING Page 1BB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
else
onsole.%rite!ine(3p1 has more value than p=5#O
N
N
The output )ould $e <
S+stem.*nt@=
This enum has A mem$ers
String name6 Married int6 (G# he/6 (GGGGGGGG#
String name6 %ido)ed int6 (1# he/6 (GGGGGGG1#
String name6 Unmarried int6 (=# he/6 (GGGGGGG=#
String name6 ,ivorced int6 (@# he/6 (GGGGGGG@#
%ido)ed is defined
p1 is ,ivorced
p1 has more value than p=
=.=G 1e"ining Structures in C7
*n &, structures $ehave similar to class, e/cept that memor+ structures )ill $e allocated in stack area,
)hereas for class memor+ )ill $e allocated from heap area. Structures can have mem$er data, mem$er
methods, constructors (onl+ parameteri8ed# and the+ can implement interfaces. Structure in & is directl+
derived from S+stem.2alueT+pe. %e can implement $o/ing and un$o/ing on structures 7ust like as )e do
for an+ intrinsic data t+pes.
R.V.COLLEGE OF ENGINEERING Page 1BC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsider the follo)ing e/ample <
Program '.1L
using S+stemO
struct .MP
M
pu$lic int ageO
pu$lic string nameO
pu$lic .MP(int a, string n#
M
ageQaO
nameQnO
N
pu$lic void disp(#
M
onsole.%rite!ine(RName QMGN, 'ge QM1NR, name, age#O
N
N
class Test
M
pu$lic static void Main(#
R.V.COLLEGE OF ENGINEERING Page 1BD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
.MP eQne) .MP(=B, R"amuR#O
e.disp(#O
o$7ect o$QeO ??$o/ing
M+0un(o$#O
N
pu$lic static void M+0un(o$7ect o$7#
M
.MP tQ(.MP#o$7O ??un$o/ing
onsole.%rite!ine(R'fter $o/ing and un4$o/ing6R#O
t.disp(#O
N
N
The output )ould $e <
Name Q"amu, 'ge Q=B
'fter $o/ing and un4$o/ing6
Name Q"amu, 'ge Q=B
=.=1 1e"ining Custom Names!aces
*n the programs )e discussed till no), )e have used namespaces like System, System.Te't etc. These are
e/isting namespaces in the .N.T frame)ork. %e can define our o)n namespace i.e. user4defined
R.V.COLLEGE OF ENGINEERING Page 1BE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
namespace (or custom namespace#. %henever )e )ant to group similar classes into a single entit+, )e
can define a namespace.
'ssume )e need to develop a program to sho) the features of several vehicles like car, $us and $ike.
Then, the classes for all these vehicles can $e put under a namespace like <
namespace 2ehicle
M
pu$lic class ar
M
??mem$ers of ar class
N
pu$lic class Bus
M
??mem$ers of Bus class
N
pu$lic class Bike
M
??mem$ers of Bike class
N
N
No), the namespace 2ehicle acts as a container for all these classes. *f )e )ant to create an o$7ect of an+
of these classes in an+ other application, )e can simpl+ )rite <
R.V.COLLEGE OF ENGINEERING Page 1BF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
using S+stemO
using 2ehicleO ??note this
class Test
M
pu$lic static void Main(#
M
ar cQne) ar(#O
4444444
4444444
N
N
4esolving Name Clas2es (cross Names!aces
There ma+ $e situation )here more than one namespace contains the class )ith same name. 0or e/ample,
)e ma+ have one more namespace like <
namespace M+2ehicle
M
pu$lic class ar
M
??mem$ers of ar class
N
44444444
R.V.COLLEGE OF ENGINEERING Page 1CG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
%hen )e include the namespaces M+2ehicle and 2ehicle, and tr+ to create an o$7ect of ar class, )e
)ill get an error. To avoid this, )e )ill use dot operator for com$ining namespace name and class name.
0or e/ample <
using S+stemO
using 2ehicleO
using M+2ehicleO
class Test
M
pu$lic static void Main(#
M
?? ar cQne) ar(#O .rrorLLL name conflict
2ehicle.ar c1Qne) 2ehicle.ar(#O
M+2ehicle.ar c=Qne) M+2ehicle.ar(#O
444444444
N
N
1e"ining Names!ace (liases
The am$iguit+ in the namespaces can also $e resolved using alias names as sho)n <
using S+stemO
using 2ehicleO
R.V.COLLEGE OF ENGINEERING Page 1C1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
using M+2ehicleO
using M+arQM+2ehicle.arO
class Test
M
pu$lic static void Main(#
M
ar c1Qne) ar(#O
M+ar c=Qne) M+ar(#O
444444444
N
N
Nested Names!aces
%e can nest one namespace )ithin the other also. 0or e/ample <
namespace 2ehicle
M
namespace M+2ehicle
M
44444
44444
N
N
R.V.COLLEGE OF ENGINEERING Page 1C=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
(r
namespace 2ehicle.M+2ehicle
M
4444444
N
=.== Summary
This section $rought out the salient features of & value t+pes like structures and enumerations. %e have
discussed the concept of static methods, the access4specifiers?modifiers for the methods of a class, the
different ke+)ords used for passing parameters to methods etc. 'lso, )e understood ho) to define our
o)n namespace rather than using the in4$uild namespaces.
=.=@ :ey0ords
'ccess Modifiers6 pu$lic, private, protected, internal, protected internal
Static ,ata and Static Method
Parameter modifiers6 out, ref, params
Passing reference t+pes $+ value and $+ reference
S+stem.'rra+ class and its mem$ers
Multidimensional 'rra+6 "ectangular and Iagged arra+s
S+stem.String class and its mem$ers
.scape characters and 2er$atim Strings
S+stem.Te/t.StringBuilder class and its mem$ers
S+stem..num $ase class and its mem$ers
Structures (struct#
Namespaces6 'liases and nested
R.V.COLLEGE OF ENGINEERING Page 1C@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
=.=A E;ercises
E. %hat do +ou understand $+ `params9 method of parameter passingP 1ive an e/ample.
F. ./plain the & static methods and static data )ith suita$le e/amples.
1G. Using the methods in S+stem.String class, design a & method )hich replaces all occurrences of the
)ord 3computer5 )ith 3(MPUT."5.
11. %hat is the difference $et)een S+stem.String and S+stem.Te/t.StringBuilderP ./plain )ith relevant
code some of the features of StringBuilder class.
1=. %rite a & program to design a structure StudentXUSN, Name, Marks, BranchY. ;ere, Branch is of
t+pe .num )ith mem$ers M', MB', MTech. 'dd appropriate constructor and also a method to
hike the marks $+ 1Gd to onl+ M' students. Sho) creation of some Student o$7ects and the )a+ to
call these methods.
1@. ./plain various method parameter modifiers used in &.
1A. ,esign a & class called Matri/ containing an integer matri/ as a mem$er and methods to
(i# read the elements of the matri/ from the ke+$oard.
(ii# 0ind the addition of t)o matrices.
(iii# 0ind the product of t)o matrices.
(iv# 0ind the su$traction of t)o matrices.
(v# To print the elements in the matri/ form.
%rite a Main(# method to call all these methods and to print all the three matrices.
1B. %rite a program to count the num$er of o$7ects created for a class.
1C. %hat are 7agged arra+sP %rite a program to find sum of elements in a 7agged arra+ of @ inner arra+s.
Module '
Unit &
R.V.COLLEGE OF ENGINEERING Page 1CA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
CONTENTS:
1.=E ($7ectives
@.= *ntroduction
@.@ 0ormal ,efinition of the & lass
@.A ,efinition the 3,efault Pu$lic *nterface5 of a T+pe
@.B "ecapping the Pillars of ((P
@.C The 0irst Pillars6 &9s .ncapsulation Services
@.D Pseudo .ncapsulation6 reating "ead4(nl+ 0ields
@.E Summar+
@.F :e+)ords
@.1G ./ercises
@.1 Objectives
't the end of this lesson, the students )ill understand the follo)ing tasks in detail6
The $asic concepts of oops
The method overloading, calling $ase class constructor through derived class constructor
The t)o )a+s of encapsulation6 traditional accessors and mutators and class properties
The read4onl+?)rite4onl+?static properties
"ead onl+ fields
@.1B ntroduction
The previous units revealed the programming fundamentals of &. Since & is an o$7ect oriented
programming (((P# language, )e need to e/plore the ((Ps properties (that is encapsulation, inheritance
R.V.COLLEGE OF ENGINEERING Page 1CB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
and pol+morphism# )ith respect to &. *n this unit, )e )ill discuss the $asic concepts of ((Ps in $rief,
and the encapsulation in detail. The other t)o concepts vi8. inheritance and pol+morphism )ill $e
e/plored in ne/t unit.
@.1C *ormal 1e"inition o" C7 class
lass is a $asis of ((Ps. ' class can $e defined as a user4defined data t+pe (U,T# that is composed of
data (or attri$utes# and functions (or methods# that act on this data. *n ((Ps, )e can group data and
functionalit+ into a single U,T to model a real4)orld entit+.
' & class can define an+ num$er of constructors. onstructor is a special t+pe of method called
automaticall+ )hen o$7ect gets created. The+ are used to provide initial values for some attri$utes. The
programmer can define default constructor to initiali8e all the o$7ects )ith some common state. ustom
or parameteri8ed constructors can $e used to provide different states to the o$7ects )hen the+ get created.
The general form of a & class ma+ look like <
class classSname
M
??data mem$ers
??constructors
??methods
N
Understanding Met2od Overloading
' class can have more than one method )ith a same name onl+ if num$er and?or t+pe of parameters are
different. Such methods are kno)n as o,erloaded methods. 0or e/ample <
$$ E;am!le "or overloaded constructors
R.V.COLLEGE OF ENGINEERING Page 1CC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
class .mplo+ee
M
pu$lic .mplo+ee(# ??default constructor
M N
pu$lic .mplo+ee(string name, int .mp*,, float BasicSal#
M
??some code
N
N
$$ overloaded member8met2ods: number o" arguments are di""erent
class Triangle
M
pu$lic float ,ra)(float height, float $ase# ??t)o arguments
M
??some code
N
pu$lic float ,ra)(float side', float sideB, float side# ??@ args
M
??some code
N
N
$$ overloaded member8met2ods: ty!e o" arguments are di""erent
class Shape
R.V.COLLEGE OF ENGINEERING Page 1CD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
pu$lic float 'rea(float height, float $ase#
M
??some code
N
pu$lic int 'rea(int a, int $#
M
??some code
N
N
$$ overloading can not be done only based on return8ty!e
class Shape
M
$$error>>>
pu$lic float 'rea(float height# ??one parameter of t+pe float
M
??some code
N
pu$lic int 'rea(float a # ??one parameter of t+pe float
M
??some code
N
N
R.V.COLLEGE OF ENGINEERING Page 1CE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Sel"84e"erence in C7
The ke+4)ord this is used to make reference to the current ob&ect i.e. the o$7ect )hich invokes the
function4call. 0or e/ample <
class .mplo+ee
M
string nameO
int e*dO
pu$lic .mplo+ee(string name, int .mp*,#
M
this.nameQnameO
this.e*dQ.mp*,O
N
N
Note that the static mem$er functions of a class can not use t)is ke+)ord as static methods are invoked
using class name $ut not the o$7ect.
*or0arding Constructor Calls using Rthis.
Using t)is ke+)ord, )e can force one constructor to call another constructor during constructor call. This
)ill help us to avoid redundanc+ in mem$er initiali8ation logic.
onsider that there is a class called I%.enerator containing a static method to generate employee id
$ased on some pre4defined criteria like department and designation of emplo+ee. The application ma+ $e
R.V.COLLEGE OF ENGINEERING Page 1CF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
having t)o situations6 (a# provide an emplo+ee id at the time of o$7ect creation, and ($# the emplo+ee id
must $e generated from I%.enerator class. But the parameter like name of the emplo+ee is provided
during o$7ect creation itself. *n such a situation, to avoid code4redundanc+, )e ma+ use t)is ke+)ord to
for)ard one constructor call to other as sho)n $elo) <
class *,1enerator
M
static int idO
pu$lic static int 1et.mp*,(#
M
??code for generating an emplo+ee id vi8 id
return idO
N
N
class .mplo+ee
M
string nameO
int e*,O
float BasicSalO
pu$lic .mplo+ee(string n, int .mp*,, float $#
M
this.nameQnO ??either use t)is
this.e*,Q.mp*,O
R.V.COLLEGE OF ENGINEERING Page 1DG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
BasicSalQ$O ??or not use t)is
N
? K 1et.mp*,(# method is called first to generate emplo+ee4id and then the construct call is
for)arded to the a$ove constructor K?
pu$lic .mplo+ee(string n#6 t2is(n, *,1enerator.1et.mp*,(#, G.GG#
M N
pu$lic static void Main(#
M
??direct call for constructor )ith three arguments
.mplo+ee e1Qne) .mplo+ee(3"amu5, 111, 1=GGG.GG#O
?K call for constructor )ith single arguments )hich in4turn calls constructor )ith three
arguments later K?
.mplo+ee e=Qne) .mplo+ee(3Sh+amu5#O
4444444444444444444
N
N
*n the a$ove e/ample, if )e )ould have not for)arded the constructor call, then )e )ould need to )rite
redundant code in the second constructor like <
pu$lic .mplo+ee(string n#
R.V.COLLEGE OF ENGINEERING Page 1D1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
this.nameQnO
this.e*,Q*,1enerator.1et.mp*,(#O
this.BasicSalQG.GGO
N
Thus, using t)is ke+)ord to for)ard constructor call, )e are avoiding code redundanc+.
@.1D 1e"ining t2e R1e"ault Public nter"aceT o" a Ty!e
The term default public interface refers to the set of pu$lic mem$ers (data or method# that are directl+
accessi$le from an o$7ect. That means, the default pu$lic interface is an+ item declared in the class )ith
the ke+)ord public. *n &, the default pu$lic interface of a class ma+ $e an+ of the follo)ing6
!et)ods 8 Named units that model some $ehavior of a class
5roperties 8 'ccessor and mutator functions
5ublic data 8 ' data mem$er )hich is pu$lic (though it is not good
to use, & provides if programmer needs#
'part from a$ove items, default pu$lic interface ma+ include user defined event, delegates and nested
t+pes.
S!eci"ying Ty!e +isibility: Public and nternal Ty!es
%e kno) that an+ mem$er of a class can $e declared for its level of visi$ilit+ (access specifier# using the
ke+)ord public, private, protected, internal and protected internal. Iust like mem$ers, the t+pe (class,
structure, interface, delegate, enumeration# itself can $e specified for its level of visi$ilit+.
R.V.COLLEGE OF ENGINEERING Page 1D=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
The method+member ,isibility is used to kno) )hich mem$ers can $e accessed from an o$7ect of the
t+pe, )here as, the type ,isibility is used to kno) )hich parts of the s+stem can create the o$7ect of that
t+pe.
' non4nested & t+pe can $e marked $+ either public or internal and nested t+pes can $e specified )ith
an+ of public, private and internal. The pu$lic t+pes can $e created $+ an+ other o$7ects )ithin the same
assem$l+ or $+ other e/ternal assem$lies. But, the internal t+pes can $e created $+ the t+pes )ithin the
same assem$l+ and are not accessi$le outside the assem$l+. B+ default, the visi$ilit+ level of a class is
internal. 0or e/ample,
??this class can $e used outside this assem$l+ also
pu$lic class Test
M
??$od+ of the class
N
??this class can $e accessed onl+ )ithin its assem$l+
internal class Test
M
??$od+ of the class
N
(r
class Test ??$+ default, it is internal
M
R.V.COLLEGE OF ENGINEERING Page 1D@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
??$od+ of the class
N
@.1E 4eca!!ing t2e Pillars o" OOP
'll the o$7ect oriented languages possess three principals (considered to $e pillars of ((P# vi8.
.ncapsulation 6 ;o) the languages hide an o$7ect9s internal
implementationP
*nheritance 6 ;o) the languages promote code reuseP
Pol+morphism 6 ;o) the languages let the programmer to treat
related o$7ects in a similar )a+P
;ere, )e )ill discuss the $asic role of each of these pillars and then move for)ard for detailed stud+.
Enca!sulation Services
.ncapsulation is the a$ilit+ to hide unnecessar+ implementation details from the o$7ect user. 0or e/ample,
assume )e have created a class named ,B"eader having methods open,- and close,-6
,B"eader dQne) ,B"eader(#O
d.open(36[M+,ata$ase.mdf5#O
]]..
d.close(#O
R.V.COLLEGE OF ENGINEERING Page 1DA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
The class ,B"eader has encapsulated the inner details of locating, loading, manipulating and closing data
file. But, the o$7ect user need not )orr+ a$out all these.
losel+ related to the notion of encapsulation is data hiding. %e do this $+ making data mem$ers as
private. The private data can $e modified onl+ through the pu$lic mem$er functions of that class.
n2eritance: T2e is-a and has-a 4elations2i!s
*nheritance is the a$ilit+ to create ne) class definitions $ased on e/isting class definitions. *n other )ords,
inheritance allo)s us to e/tend the $ehavior of $ase class $+ inheriting core functionalit+ into a derived
class.
0or e/ample, )e kno) that S+stem.($7ect is the topmost class in .N.T. %e can create a class called
Shape )hich defines some properties, fields, methods and events that are common to all the shapes. The
;e/agon class e/tends Shape and inherits properties of Shape and ($7ect. *t contains properties of its
o)n. No), )e can sa+ ;e/agon is a Shape, )hich is an o$7ect. Such kind of relationship is called as is-a
relationship and such inheritance is termed as Classical inheritance.

There is another t+pe of code reuse in ((P vi8. the containment+delegation model or has-a relationship.
This t+pe of reuse is not used for $ase class?child class relationships. "ather, a given class can define a
mem$er varia$le of other class and make use of that either full+ or partl+.
R.V.COLLEGE OF ENGINEERING Page 1DB
ObHect
Sha(e
Ie0ag%n
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
0or e/ample, a ar can contain "adio. The containing t+pe (ar# is responsi$le for creating the inner
o$7ect ("adio#. *f the ar )ishes to make the "adio9s $ehavior accessi$le from a ar instance, it must
provide some set of pu$lic functions that operate on the inner t+pe.

Polymor!2ism: Classical and (d Qoc
Pol+morphism can $e of t)o t+pes vi8. classical and Ad 0oc. ' Classical polymorphism takes place in
the languages that support classical inheritance. The $ase class can define a set of mem$ers that can $e
overridden $+ a su$class. %hen su$class overrides the $ehavior defined $+ a $ase class, the+ are
essentiall+ redefining ho) the+ respond to the same message. 0or e/ample, assume Shape class has
defined a function named ,ra)(# )ithout an+ parameter and returning nothing. 's ever+ shape has to $e
dra)n in its o)n manner, each su$class like ;e/agon, ircle etc. can redefine the method Shape(# as
sho)n <
R.V.COLLEGE OF ENGINEERING Page 1DC
Car
'adi%
//Meth%d %) Car
8%id TurnOn'adi%"b%%l %n$
=
//Delegate t% inner 'adi%
radi%ObH#P%2er"%n$J
A
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)

lassical pol+morphism allo)s a $ase class to enforce a given $ehavior on all su$classes.
Ad hoc polymorphism allo)s o$7ects that are not related $+ classical inheritance to $e treated in a similar
manner, provided that ever+ o$7ect has a method of the e/act signature. !anguages that support ad hoc
pol+morphism possess a techniJue called late binding to find the underl+ing t+pe of given o$7ect at
runtime.
onsider the follo)ing situation6

R.V.COLLEGE OF ENGINEERING Page 1DD
ObHect
Sha(e
Ie0ag%n
8%id Dra2"$
Circle
Dra2"$
Dra2"$
Circle Ie0ag%n 'ectangle
Dra2"$
Dra2"$
Dra2"$
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Note that the three classes ircle, ;e/agon and "ectangle are not from same $ase. Still each class
supports an identical ,ra)(# method. This is possi$le $+ implementing ,ra)(# method on generic t+pes.
%hen a particular t+pe is used for calling ,ra)(#, it )ill act accordingl+.
@.1F T2e *irst Pillar: C7Ss Enca!sulation Services
The concept of encapsulation sa+s that the o$7ect9s data should not $e directl+ accessi$le from a method.
*f the data is to $e manipulated, it has to $e done indirectl+ using accessor (get# and mutator(set# method.
& provides follo)ing t)o techniJues to manipulate private data mem$ers <
,efine a pair of traditional accessor and mutator methods
,efined a named propert+.
*t is good programming practice to make all the data mem$ers or fields of a class as private. This kind of
programming is kno)n as $lack $o/ programming.
En"orcing Enca!sulation Using Traditional (ccessors and Mutators
*f )e )ant to access an+ private data, )e can )rite a traditional accessor (get method# and )hen )e )ant
to provide value to data, )e can )rite a mutator (set method#. 0or e/ample,
class .mp
M
string NameO
pu$lic string 1etName(# ??accessor
M
R.V.COLLEGE OF ENGINEERING Page 1DE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
return NameO
N
pu$lic void SetName(string n# ??mutator
M
NameQnO
N
N
class Test
M
pu$lic static void Main(#
M
.mp pQne) .mp(#O
p.SetName(3"amu5#O
onsole.%rite!ine(3MGN5,p.1etName(##O
N
N
*n this e/ample, using the pu$lic methods, )e could a$le access private data.
(not2er *orm o" Enca!sulation: Class Pro!erties
'part from traditional accessors and mutators, )e can make use of properties provided $+ .N.T class
(and structures, interfaces#. Properties resolve to a pair of hidden internal methods. The user need not call
R.V.COLLEGE OF ENGINEERING Page 1DF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
t)o separate methods to get and set the data. *nstead, user is a$le to call )hat appears to $e a single
named field. 0or illustration, consider the follo)ing e/ample <
using S+stemO
class .mp
M
string NameO
pu$lic string .mpName ?? EmpName is name of propert+
M
get
M
return NameO ?? Name is field4name
N
set
M
NameQvalueO ?? value is a ke+)ord
N
N
N
class Test
M
pu$lic static void Main(#
M
.mp pQne) .mp(#O
p..mpNameQR"amuRO ??use name of the propert+
R.V.COLLEGE OF ENGINEERING Page 1EG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsole.%rite!ine(RMGNR,p..mpName#O
N
N
' & propert+ is composed using a get $lock (accessor# and set $lock (mutator#. The value ke+)ord
represents the right4hand side of the assignment. Though, value is an o$7ect, the underl+ing t+pe of the
o$7ect depends on )hich kind of data it represents. 0or e/ample, in the previous program, the propert+
EmpName is operating on a private string, )hich maps to S+stem.String. Unlike traditional accessors and
mutators, the properties make our t+pes easier to manipulate.
Properties are a$le to respond to the intrinsic operators in &. 0or e/ample,
using S+stemO
class .mp
M
int SalO
pu$lic int Salar+
M
get
M
return SalO
N
set
M
SalQvalueO
R.V.COLLEGE OF ENGINEERING Page 1E1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
N
N
class Test
M
pu$lic static void Main(#
M
.mp pQne) .mp(#O
p.Salar+Q1=GGGO
p.Salar+HHO
onsole.%rite!ine(RMGNR,p.Salar+#O ??1=GG1
p.Salar+ 4QAGGO
onsole.%rite!ine(RMGNR,p.Salar+#O ??11CG1
N
N
4ead8only and %rite8only Pro!erties
*n some of the situations, )e 7ust )ant to set a value to a data mem$er and don9t )ant to return it. *n such
a situation, )e can omit get $lock. ' propert+ )ith onl+ a set $lock is kno)n as write-only propert+. *n
the same manner, )e can 7ust have a get $lock and omit set $lock. ' propert+ )ith onl+ a get $lock is
kno)n as read-only propert+. 0or e/ample,
class .mp
M
string SSN, nameO
R.V.COLLEGE OF ENGINEERING Page 1E=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
int .mp*,O
pu$lic .mp(string n, int id#
M
nameQnO
.mp*,QidO
N
pu$lic string .mpSSN ??read4onl+ propert+
M
getM return SSNON
N
N
Understanding static !ro!erties
& supports static properties. Note that, static mem$ers of a class are $ound to class $ut not for o$7ects.
That is, to access static mem$ers, )e need not create an o$7ect of the class. The same rule )ill appl+ to
static properties too. 0or e/ample,
class .mp
M
static string ompan+NameO
pu$lic static string ompan+
M
getM return ompan+NameO N
setM ompan+NameQvalueO N
N
R.V.COLLEGE OF ENGINEERING Page 1E@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic static void Main(#
M
.mp.ompan+Q3"NS*T5O ??use class name
onsole.%rite!ine(3%e are at MGN5, .mp.ompan+#O
N
N
Understanding static Constructors
's )e have seen, static properties can $e used to set and get values for static mem$ers. 'ssume a
situation, )here )e need to 7ust set a value commonl+ for all the o$7ects. %riting a static )rite4onl+
propert+ )ith a set4$lock and then assigning value is Juite time4consuming. 0or this purpose, & provides
another method for doing so, through static constructors. 0or e/ample,
class .mp
M
static string ompan+NameO
static .mp(#
M
ompan+NameQ3"NS*T5O
N
pu$lic static void Main(#
M
onsole.%rite!ine(3%e are at MGN5, .mp.ompan+#O
N
N
R.V.COLLEGE OF ENGINEERING Page 1EA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
No), all the o$7ects of Emp class )ill $e set the value 96NSIT9 for the mem$er #ompanyName
automaticall+ as soon as the o$7ects gets created.
@.=G Pseudo8Enca!sulation: Creating 4ead8Only *ields
Iust like read4onl+ properties, )e have a notion of read4onl+ fields. "ead4onl+ fields offer data
preservation via the ke+)ord readonly. The readonl+ field can $e given a value through assignment onl+
at the time of declaration or as a part of constructor.
class Student
M
pu$lic readonly int SemQBO ??assignment during declaration
pu$lic readonly string USNO
string nameO
pu$lic Student(string n, string usn#
M
nameQnO
USNQusnO ??assignment through constructor
N
pu$lic static void Main(#
M
Student s1Qne) Student(3'$hishek5, 31"NGDM'G15#O
R.V.COLLEGE OF ENGINEERING Page 1EB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
s1.SemQ @O ??error
s1.USNQ31"NGDM'G=5O ??error
]]]
N
N
NOTE:
e The ke+)ord readonly is different from const.
e The const fields can $e assigned a value at the time of declaration onl+ and assignment is not
possi$le there4after.
e So, const fields )ill have same value through out the program, as it is compile-time constant.
e (n the other hand, readonly fields can $e assigned a value through constructor also.
e So, the+ can have different values $ased on constructor call.
e 0or e/ample <
class Student
M
pu$lic readonl+ int SemQBO ??make Sem as B for all o$7ects
pu$lic readonl+ string USNO
string nameO
pu$lic Student(string n, string usn#
M
nameQnO
USNQusnO
N
R.V.COLLEGE OF ENGINEERING Page 1EC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic Student(string n, string u, int s# ??change sem for one student
M
nameQnO
USNQuO
SemQsO
N
pu$lic static void Main(#
M
Student s1Qne) Student(3"amu5, 3M'G15#O ??sem is B $+ default
Student s=Qne) Student(3Sh+am5, 3SG=5, @#O ??sem is set to @
44444444444444
N
N
*n the a$ove e/ample, if the field Sem )ould have $een specified )ith const modifier, then tr+ing to
change the value through constructor )ill generate error. But, readonly ke+)ord )ill allo) the
programmer to keep some fields as constant unless and other)ise specified through constructor.
@.=1 Summary
.ncapsulation is one of the $asic $uilding $locks of o$7ect oriented programming language. *n &, )e can
achieve encapsulation either $+ )riting accessor and mutator methods or $+ )riting properties. 'gain,
$ased on our need in a program, )e can )rite read4onl+?)rite4onl+ properties. (ne can make use of static
constructors and read4onl+ fields too.
R.V.COLLEGE OF ENGINEERING Page 1ED
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
@.== :ey0ords
Method (verloading
The ke+)ord t)is and 0or)arding constructor calls
Method?Mem$er visi$ilit+ and T+pe visi$ilit+
.ncapsulation, *nheritance, Pol+morphism, ,ata hiding
*s4a and ;as4a relationship (lassical inheritance and ontainment?,elegation model#
lassical and 'd4hoc Pol+morphism
!ate Binding
'ccessor and Mutators
Properties (get and set#6 "ead4onl+, %rite4onl+, static
Static onstructors and "ead4onl+ fields
@.=@ E;ercises
1. %hat are the $asic components of ($7ect oriented programming and ho) the+ are implementedP
1ive e/amples.
=. ;o) do +ou overload a methodP ./plain )ith an e/ample.
@. %hat do +ou mean $+ for)arding constructor callsP ./plain.
A. %hat are mem$er visi$ilit+ and t+pe visi$ilit+P
B. ./plain 3is4a5 and 3has4a5 relationship )ith respect to inheritance.
C. %hat is encapsulationP %hat are t)o )a+s of enforcing encapsulationP 1ive e/amples for $oth the
methods.
D. ./plain the concept of static properties )ith e/ample.
E. %hat do +ou mean $+ static constructorsP %rite a program to illustrate the same.
F. ./plain the concept of readonl+ fields )ith an e/ample.
Module '
R.V.COLLEGE OF ENGINEERING Page 1EE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Unit 9
CONTENTS:
1.=F ($7ectives
A.= *ntroduction
A.@ The Second Pillar6 &9s *nheritance Supports
A.A :eeping famil+ secrets6 The 3Protected5 :e+)ord
A.B Nested T+pe ,efinitions
A.C The Third Pillar6 &9s Pol+morphic Support
A.D asting Bet)een
A.E Summar+
A.F :e+)ords
A.1G ./ercises
B.1 Objectives
't the end of this lesson, the students )ill understand6
The concept of *nheritance
The protected mem$ers of a class
Sealed classes
Pol+morphism
2irtual Methods
'$stract lasses
'$stract Methods
R.V.COLLEGE OF ENGINEERING Page 1EF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
2ersioning lass Mem$ers
*mplicit and ./plicit asting
A.1C ntroduction
The previous unit ela$orated a$out one of the ((P concepts vi8. .ncapsulation. ;ere, )e )ill stud+ the
other t)o vi8. *nheritance and Pol+morphism. *nheritance allo)s the code re4usa$ilit+. The $ase class
properties can $e made use of in the derived class. But & does not support multiple inheritance. To get
the properties of more than one class, )e need to design interfaces )hich )ill $e discussed in ne/t
module. Pol+morphism means :ne interface, multiple forms. Under this, )e are going to stud+ the
concept of a$stract classes, a$stract methods, virtual methods and so on.
A.1D T2e Second Pillar: C7Ss n2eritance Su!!orts
*nheritance facilitates code reuse. The inheritance can $e either classical in2eritance (is-a relationship#
or containment$delegation model (has-a relationship#.
%hen )e esta$lish is8a relationship $et)een classes, )e are $uilding a dependenc+ $et)een t+pes. The
$asic idea of classical inheritance is that ne) classes ma+ influence and e/tend the functionalit+ of other
classes. The hierarch+ ma+ look something like <
R.V.COLLEGE OF ENGINEERING Page 1FG
!&(l%yee
Manager
SalesMan
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
No) )e can sa+ that, Manager is4a .mplo+ee and SalesMan is4a .mplo+ee.
*n classical inheritance, the $ase classes are used to define general characteristics that are common to all
derived classes. The derived classes e/tend this general functionalit+ )hile adding more specific
$ehaviors to the class.
onsider an e/ample <
pu$lic class .mp
M
protected string NameO
protected int .mp*,O
]]]]..
N
pu$lic class SalesMan6.mp ??SalesMan is inherited from .mp
M
int num$erSofSsalesO ?? also includes mem$ers Name, .mp*,
]]]..
N
class Test
M
pu$lic static void Main(#
R.V.COLLEGE OF ENGINEERING Page 1F1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
.mp eQne) .mp(#O
SalesMan sQne) SalesMan(#O
444444444444
N
N
Controlling ,ase8Class Creation
Usuall+, the $ase class constructors are used to initiali8e the mem$ers of $ase class. %hen derived class
has fe) more mem$ers and if )e need to initiali8e, then )e )ill )rite constructor for derived class. *n
such a situation, there is a repetition of code. 0or e/ample <
pu$lic class .mp
M
protected string NameO
protected int .mp*,O
pu$lic .mp(string n, int eid, float s#
M
NameQnO
.mp*dQeidO
N
N
pu$lic class SalesMan6.mp
M
R.V.COLLEGE OF ENGINEERING Page 1F=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
int num$erSofSsalesO
pu$lic SalesMan(string n, int eid, int s#
M
NameQnO $$code re!eated
.mp*dQeidO $$code re!eated
num$erSofSsalesQsO
N
N
*f there is more num$er of data fields in the $ase class, then in each of the derived class constructors, )e
need to repeat such assignment statements. To avoid this, & provides an option to explicitly call $ase
class constructors as sho)n $elo) <
pu$lic class .mp
M
protected string NameO
protected int .mp*,O
pu$lic .mp(string n, int eid#
M
NameQnO
.mp*dQeidO
N
N
R.V.COLLEGE OF ENGINEERING Page 1F@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic class SalesMan6.mp
M
int $onusO
pu$lic SalesMan(string n, int eid, int $#6 base(n, eid#
M
$onusQ$O ??other mem$ers are passed to $ase class to initiali8e
N
N
class Test
M
pu$lic static void Main(#
M
.mp e1Qne) .mp(3"am5, =B#O
SalesMan s1Q ne) SalesMan(3Sham5, 1=, 1G#O
444444444444
N
N
Multi!le ,ase Classes
,eriving a class from more than one $ase class is not possi$le in &. That is, multiple inheritance is not
supported $+ &. %hen )e need to use the properties of more than one class in a derived class, )e need
to )rite interaces rather than classes. Then )e can implement an+ num$er of interfaces to achieve code4
reusa$ilit+.
R.V.COLLEGE OF ENGINEERING Page 1FA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
A.1E :ee!ing *amily Secrets: T2e protected :ey0ord
The private mem$ers of a class can not $e availa$le to derived classes. So, )e )ill go for protected
keeping the privac+ of the data. The protected mem$ers of a class can not $e accessed from outside, $ut
still $e availa$le to derived classes.
Preventing n2eritance: $ealed Classes
*n some of the situations, )e ma+ don9t )ant our class to $e inherited $+ an+ other class. 0or e/ample <
;ere, a class called 5art-time Sales!an is derived from Sales!an class )hich in4turn is derived from
Employee class as sho)n in the diagram. No), )e don9t )ant an+ more classes to $e derived from 5art-
time Sales!an class. To prevent such inheritance, & provides a ke+)ord sealed. The usage is depicted
here4under6
pu$lic sealed class PartSTimeSalesMan6 SalesMan
M
??$od+ of 5art;TimeSales!an class
N
No) an+ attempt made to derive a class from 5art;TimeSales!an class )ill generate an error6
R.V.COLLEGE OF ENGINEERING Page 1FB
!&(l%yee
SalesMan
PartBti&e SalesMan
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic class Test6 5art;TimeSales!an ++compile-time error111
M
]]]]..
N
Man+ of the in$uilt classes of & are sealed classes. (ne such e/ample is S+stem.String.
Programming "or Containment$1elegation
Till no) )e have discussed is-a relationship. No) )e )ill see, ho) to )rite program for )as-a
relationship. onsider a class 6adio <
class "adio
M
pu$lic void Turn(n($ool on#
M
if(on#
onsole.%rite!ine(3"adio is on5#O
else
onsole.%rite!ine(3"adio is off5#O
N
N
No), consider a class #ar <
R.V.COLLEGE OF ENGINEERING Page 1FC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
class ar
M
int urrSpeed, Ma/SpeedO
string nameO
$ool car*s,eadQfalseO
pu$lic ar(# M Ma/SpeedQ1GGN
pu$lic ar(string n, int m, int c#
M
nameQnO
Ma/SpeedQmO
urrSpeedQcO
N
pu$lic void SpeedUp(int a#
M
if(car*s,ead#
onsole.%rite!ine(3(ut of order5#O
else
M
urrSpeedHQaO
N
N
N
R.V.COLLEGE OF ENGINEERING Page 1FD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
No), )e have t)o classes vi8. 6adio and #ar. But, )e can not sa+, <#ar is a 6adio9 or <6adio is a
#ar9. "ather, )e can sa+, <#ar )as a 6adio9. No), the #ar is called containing lass and 6adio is
called contained class.
To make the contained class to )ork, )e need to re4define #ar class as <
class ar
M ]]]..
private "adio rdQne) "adio(#O
N
To e/pose the functionalit+ of the inner class to the outside )orld reJuires delegation. %elegation is the
act of adding mem$ers to the containing class that make use of the functionalit+ of contained class.
class ar
M ]]].
pu$lic void Tune($ool s#
M
rd.Turn(n(s#O ??delegate reJuest to inner o$7ect
N
N
To make this function )ork, in the Main(# function )e can )rite <
ar cQne) ar(#O
c.Tune(false#O
R.V.COLLEGE OF ENGINEERING Page 1FE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Thus $+ making one class to $e a mem$er of other class, )e can esta$lish )as-a relationship. But it is
al)a+s the 7o$ of outer class to define a mem$er function )hich activates the inner class o$7ects.
A.1F Nested Ty!e 1e"initions
*n &, it is possi$le to define a t+pe (enum, class, interface, struct, delegate# directl+ )ithin the scope of a
class. %hen a t+pe is nested )ithin a class, it is considered as a normal mem$er of that class. 0or
e/ample,
class 1
M
]]].. ??mem$ers of outer class
class =
M
]]].??mem$ers of inner class
N
N
Nested t+pe seems like )as-a relationship, $ut it is not. *n containment?delegation, the o$7ect of contained
class is created )ithin containing class. But, it is possi$le to create the o$7ects )herever )e )ish. But in
nested t+pes, the inner class definition is )ithin the $od+ of out class and hence, inner class o$7ects can
not $e created outside the outer class.
A.=G T2e T2ird Pillar: C7Ss Polymor!2ic Su!!ort
R.V.COLLEGE OF ENGINEERING Page 1FF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Pol+morphism ans)ers the Juestion 3ho) to make related o$7ects respond differentl+ to the same
reJuestP5 onsider the follo)ing e/ample to illustrate the need of pol+morphism.
'ssume )e have a $ase class Employee and t)o derived classes !anager and Sales!an.
class .mplo+ee
M
]].
pu$lic void Bonus(float $#
M
$asicSalHQ$O
N
N
class Manager6.mplo+ee
M
]]]..
N
class SalesMan6 .mplo+ee
M
]]]]
N
No), the classes !anager and Sales!an $oth contains the method =onus,float-. Thus in the Main(#
function, )e can call =onus,- through the o$7ects of !anger and Sales!an <
R.V.COLLEGE OF ENGINEERING Page =GG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Manager mQne) Manager(#O
m.Bonus(BGG#O
SalesMan sQne) SalesMan(#
s.Bonus(@GG#O
($viousl+, the =onus,- method )orks same for $oth the o$7ects. But in realit+, the $onus for a SalesMan
should $e calculated $ased on num$er of sales. Manager can $e given $onus $ased on his other
performance like successful completion and deliver+ of a pro7ect etc. This means, )e need a =onus,-
method )hich )orks differentl+ in t)o derived classes.
The pol+morphic techniJue of & provides solution for this pro$lem. %ith the help of ,irtual and
o,erride ke+)ords, )e can make same function to $ehave differentl+ in $ase4class and all the derived
classes. 0or e/ample,
class .mplo+ee
M
444444444444444444
pu$lic virtual void Bonus(float $#
M
$asicSalHQ$O
N
N
class SalesMan6.mplo+ee
M
444444444444444444
R.V.COLLEGE OF ENGINEERING Page =G1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic override void Bonus(float $#
M
int salesBonusQGO
if(num(fSalesXQ1GG#
salesBonusQ1GO
elseif (num(fSalesXQ=GG#
salesBonusQ=GO
base.Bonus($KsalesBonus#O ??use of $ase class method
N
N
class Test
M
pu$lic static void Main(#
M
.mplo+ee eQne) .mplo+ee(#O
e.Bonus(1GG#O ??$ase class =onus,- is called
SalesMan sQne) SalesMan(#
s.Bonus(@GG#O ??derived class =onus,- is called
N
N
%e can see that )hen the =onus,- method is invoked through $ase class o$7ect, the corresponding method
)ill $e called. %hereas, )hen =onus,- is invoked )ith the o$7ect s of derived class, the o,erridden
method =onus,- )ill $e called.
R.V.COLLEGE OF ENGINEERING Page =G=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
NOTE that an+ overridden method is free to call its corresponding $ase class method using the ke+)ord
base. Thus, the overridden method can have its o)n statements and also can make use of the $ehaviors of
$ase class virtual method also.
1e"ining (bstract Classes
Sometimes, the creation of $ase class o$7ects )ill not $e of an+ use. 0or e/ample, an .mplo+ee is al)a+s
identified )ith a designation. Thus, an emplo+ee must $e either a Manager or a SalesMan or )orking at
some such other designation. So, creation of the o$7ect of class Employee is useless. *n such situations, )e
can prevent $ase class instantiation $+ making it as abstract.
pu$lic abstract class .mplo+ee
M
]]]
N
.mplo+ee eQne) .mplo+ee ??error >>
Thus, a$stract class is a class )hich 7ust declares mem$ers (data and method# and no o$7ect can $e
created for this class. The mem$er methods of a$stract class ma+ $e used $+ the o$7ects of derived class
either directl+ or $+ overriding them in the derived class.
En"orcing Polymor!2ic (ctivity: Abstract Methods
'n a$stract class ma+ contain the definition for methods it is defining. The derived classes are free to use
such methods directl+ or the+ can override and then use. But in some situations, the definitions of a$stract
$ase4class methods ma+ not $e useful. The derived classes onl+ should define the reJuired $ehavior. *n
R.V.COLLEGE OF ENGINEERING Page =G@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
this case, )e need to "orce the derived classes to override the $ase class methods. This is achieved using
abstract methods.
'n a$stract class can define an+ num$er of a$stract methods, )hich )ill not suppl+ an+ default
implementation. '$stract method is eJuivalent to pure ,irtual unctions of HH. The a$stract methods
can $e used )henever )e )ish to define a method that does not suppl+ a default implementation. To
understand the need for a$stract methods, consider the follo)ing situation6
;ere, each derived class like >e'agon and #ircle of S)ape has to override %raw,- method to indicate the
methodolog+ of dra)ing itself. *f an+ derived class forgets to override %raw,- method, the code ma+ look
like <
a$stract class Shape
M
pu$lic virtual void ,ra)(#
M
onsole.%rite!ine(3Shape.,ra)(#5#O
N
R.V.COLLEGE OF ENGINEERING Page =GA
ObHect
Sha(e
Ie0ag%n
Circle
8irtual 8%id Dra2"$
Dra2"$
Dra2"$
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
pu$lic class ircle6Shape(#
M
pu$lic ircle(#O
44444444444444
N
pu$lic class ;e/agon6Shape(#
M
]]]]..
pu$lic override void ,ra)(#
M
onsole.%rite!ine(3;e/agon.,ra)(#5#O
N
N
pu$lic class Test
M
pu$lic static void Main(#
M
ircle cQ ne) ircle(#O
c.,ra)(#O ??,ra)(# method of S)ape class is called
;e/agon hQne) ;e/agon(#O
h.,ra)(#O ??,ra)(# method of >e'agon class is called
R.V.COLLEGE OF ENGINEERING Page =GB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
N
*n this e/ample, the #ircle class is not overriding the %raw,- method. So, )hen the %raw,- method is
invoked through the o$7ect of #ircle class, the %raw,- method of S)ape class itself )ill $e called.
($viousl+, the %raw,- method of S)ape class )ill not $e having an+ information a$out ho) to dra) a
circle and hence it )ill $e meaningless. This sho)s that ,irtual methods o base class need not be
o,erridden by deri,ed classes.
%hen programmer must $e forced to override %raw,- method, the method of $ase class must $e made
abstract <
a$stract class Shape
M
?? completel+ a$stract method. Note the semicolon at the end
pu$lic abstract void ,ra)(#C
4444444444
N
pu$lic class ircle6Shape(#
M 44444444444444444
pu$lic override void ,ra)(# ??has to override
M
onsole.%rite!ine(3ircle.,ra)(#5#O
N
N
R.V.COLLEGE OF ENGINEERING Page =GC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic class ;e/agon6Shape(#
M ]]]]..
pu$lic override void ,ra)(# ??has to override
M
onsole.%rite!ine(3;e/agon.,ra)(#5#O
N
N
pu$lic class Test
M
pu$lic static void Main(#
M
ircle cQ ne) ircle(#O
c.,ra)(#O ??,ra)(# method of #ircle class is called
;e/agon hQne) ;e/agon(#O
h.,ra)(#O ??,ra)(# method of >e'agon class is called
N
N
Thus, $+ making a $ase class method as abstract, )e are making use of run-time polymorphism or late
binding. That is, the $inding $et)een the o$7ect and the method to $e invoked is decided onl+ at runtime.
This concept is more clear )hen )e re4design our Main(# function in the follo)ing format6
pu$lic static void Main(#
R.V.COLLEGE OF ENGINEERING Page =GD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
ShapeV W sQMne) ircle(#, ne) ;e/agon(#NO
for(int iQGOiXs.!engthOiHH#
sViW.,ra)(#O
N
This ma+ seems to $e Juite interesting. Till no), )e have heard that )e can not create o$7ects for a$stract
classes. But in the a$ove code snippet, )e are creating arra+ of o$7ects of $ase4classes. ;o)P This is ver+
o$vious as arra+ of o$7ects stores references to varia$les $ut not the o$7ects directl+. Thus, in the a$ove
e/ample, s?@A stores reference to the o$7ect of t+pe #ircle and s?2A stores reference to the o$7ect of t+pe
>e'agon.
*n the for loop, )hen )e use the statement <
sViW.,ra)(#O
t2e content 5i.e. 02et2er re"erence to Circle or re"erence to 0exagon6 o" s2i3 is considered to decide
02ic2 4raw%5 met2od to be invo3ed and t2e type 5i.e. 2ere ty!e is $hape6 o" s2i3 is ignored. T2is is
not2ing but run8time !olymor!2ism or late binding.
NOTE 5+ery im!ortant6:
'fter dealing )ith entire stor+ a$out a$stract classes and a$stract methods, some$od+ ma+ feel )hat
e/actl+ is the difference $et)een a$stract classes and interfacesP Because 7ust4like a$stract classes,
interfaces also provide 7ust a protot+pe of the methods and the implementing classes have to define those
methods. (more a$out interfaces in Module @#
R.V.COLLEGE OF ENGINEERING Page =GE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
The ma7or difference comes in case of multiple inheritance. %e kno) that )e can not derive a class from
more than one $ase4class in &. That is multiple inheritance is not possi$le. But, )e ma+ have a situation
)here there is more than one $ase class and )e need to derive a class from all those $ase classes and then
override the virtual methods present in all the $ase classes. *n such a situation, instead of )riting a$stract
$ase classes, )e should )rite interfaces. Because, a class can $e derived from one $ase class and it can
implement man+ num$er of interfaces.
+ersioning class members
& provides facilit+ of method hiding, )hich is logical opposite of method overriding. 'ssume the
follo)ing situation6

The class #ircle is derived from S)ape. The S)ape class has an a$stract method %raw,- )hich is
overridden )ithin #ircle class to indicate ho) to dra) a circle. The class :val $ehaves similar to #ircle.
But, methodolog+ for dra)ing an oval is different from that of circle. So, )e need to !revent t2e O,al
class "rom in2eriting 4raw%5 met2od. This techniJue is kno)n as ,ersioning a class. This is achieved
$+ using the ke+ )ord new as sho)n $elo) <
R.V.COLLEGE OF ENGINEERING Page =GF
ObHect
Sha(e
Ie0ag%n
Circle
O8al
Abstract Dra2"$ &eth%d de)ined
Dra2"$ &eth%d i&(le&ented
C%&(letely ne2 Dra2"$ &eth%d
hiding Circle#Dra2"$
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic class (val6 ircle
M
pu$lic (val(#
M
444444
N
pu$lic ne0 void ,ra)(#
M
??(val specific dra)ing algorithm
N
N
No), )hen )e create an o$7ect of :val class and invoke %raw,- method, the most recentl+ used
definition of ,ra)(# is called. That is,
(val o$Qne) (val(#O
o$.,ra)(#O ??calls the ,ra)(# method of (val class
Thus, the ke+)ord new $reaks the relationship $et)een the a$stract ,ra)(# method defined $+ the $ase
class and the ,ra)(# method in the derived class.
(n the other hand, if )e )ish, )e can make use of the $ase class method itself $+ using e'plicit casting6
(val o$7Qne) (val(#O
((ircle#o$7#.,ra)(#O ??calls ,ra)(# method of ircle class
R.V.COLLEGE OF ENGINEERING Page =1G
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
NOTE:
The method hiding is useful )hen )e are making use of the t+pes defined in another .N.T assem$l+ and
)e are not sure )hether that t+pe contains an+ method )ith the same name as )e are using. That is, in
our application )e ma+ $e using in$uilt classes ()ith the help of ke+)ord using#. %e are going to create
a method %raw,- in our application, $ut )e are not sure )hether an+ of the in$uilt class contains a
method )ith same name. *n such a situation, )e can 7ust put a ke+)ord new )hile declaring our method.
This )ill prevent the possi$le call to $uilt4in class method.
A.=1 Casting ,et0een
Till no), )e have discussed num$er of class hierarchies. No) )e should kno) the la)s of casting
$et)een class t+pes. onsider the follo)ing situation, )here )e have is-a relationship <

:eeping the a$ove class hierarch+ in mind, the follo)ing declarations are purel+ valid.
o$7ect o$Qne) Manager(#O
.mplo+ee eQne) Manager(#O
R.V.COLLEGE OF ENGINEERING Page =11
ObHect
!&(l%yee
Manager
SalesMan
PartKti&e
SalesMan
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
SalesMan sQ ne) PartStimeSalesMan(#O
*n all these situations, the implicit casting from derived class to $ase class is done $+ the & !". (n the
other hand, )hen )e need to convert $ase class reference to $e stored in derived class o$7ect, )e should
make explicit casting as <
o$7ect o$O
Manager mQ(Manager#o$O
;ere, the e/plicit cast from $ase class to derived class is done.
1etermining t2e Type-o Objects
& provides three )a+s to determine if a $ase class reference is actuall+ referring to derived t+pes6
e ./plicit casting
e is ke+)ord
e as ke+)ord
%e have seen e/plicit casting 7ust no). The usage of other t)o methodolog+ is depicted )ith the help of
e/amples6
($7ect o$Qne) Manager(#O
if(o$ is Manager# ??checking )hether ob is !anager
??do something
.mplo+ee eO
SalesMan sQ e as SalesManO ??converting Employee t+pe to Sales!an t+pe
??do something )ith s
R.V.COLLEGE OF ENGINEERING Page =1=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Numerical Casts
*n addition to casting $et)een o$7ects, the numerical conversions also follo) similar rules. %hen )e are
tr+ing to cast larger (in si8e of t+pe# t+pe to smaller t+pe, )e need to make e/plicit casting6
int /Q=BGGGO
$+te $Q($+te#/O ??loss of information
%hile converting from larger t+pe to smaller t+pe, there is a chance of data4loss.
%hen )e need to cast smaller t+pe to larger t+pe, the implicit casting is done automaticall+6
$+te $Q=@O
int /Q$O ??implicit casting
There )ill not $e an+ loss of data during such casting.
A.== Summary
Till no), )e have discussed some of ver+ important features of & programming language. %hile
developing huge pro7ect or a product, the concepts inheritance and pol+morphism makes sense. The
developer should understand )hen and )here to use the concept of a$stract classes virtual functions etc.
A.=@ :ey0ords
R.V.COLLEGE OF ENGINEERING Page =1@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
lassical *nheritance (is4a relationship#
ontainment? ,elegation Model (has4a relationship#
The ke+)ords protected and sealed
The ke+)ords abstract, virtual, base and override
'$stract methods or Pure 2irtual functions
"un4time Pol+morphism or !ate Binding
*mplicit and ./plicit t+pe casting
The ke+)ords is and as
A.=A E;ercises
B. ;o) do +ou e/plicitl+ call $ase class constructor from derived class constructorP ./plain )ith an
e/ample.
C. %hat do +ou mean $+ nested classesP %hat is the difference $et)een nested classes and
ontainment?delegationP
D. ;o) do +ou prevent inheritance using sealed classesP ./plain )ith an e/ample.
E. %ith an e/ample, e/plain the concept of a$stract classes.
F. %rite a program to demonstrate the concept of virtual and override ke+)ords.
1G. ./plain the concept of late $inding )ith an e/ample.
11. %rite a note on asting.
1=. ./plain a$stract methods )ith e/ample.
1@. %hat do +ou mean $+ versioning mem$ersP ./plain.
Module &
Unit 1
CONTENTS:
R.V.COLLEGE OF ENGINEERING Page =1A
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1.@G ($7ectives
1.@1 *ntroduction
1.@= Meaning of .rrors and ./ceptions
1.@@ The "ole of .N.T ./ception ;andling
1.@A The S+stem. ./ception Base lass
1.@B Thro)ing a 1eneric ./ception
1.@C atching ./ception
1.@D !" S+stem < !evel ./ception (S+stem.S+stem./ception#
1.@E ustom 'pplication4!evel ./ception
(S+stem.'pplication./ception#
1.@F ;andling Multiple ./ceptions
1.AG The 0inall+ Block
1.A1 ,+namicall+ *dentif+ing 'pplication and S+stem !evel
./ceptions
1.A= Summar+
1.A@ :e+)ords
1.AA ./ercises
1.=B Objectives
't the end of this lesson, the students )ill understand6
The meaning of e/ceptions
T+pes of e/ceptions6 S+stem and 'pplication
Usage of ke+)ords like try, catc), t)row, finally
Building user4defined?custom e/ceptions
1.=C ntroduction
The point of this unit is to understand ho) to handle runtime anomalies in +our code $ase through the use
of structured e/ception handling. Not onl+ )ill +ou learn a$out the & ke+)ords that allo) +ou to handle
such pro$lems, $ut +ou )ill also come to understand the distinction $et)een application4level and
R.V.COLLEGE OF ENGINEERING Page =1B
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
s+stem4level e/ceptions. This discussion )ill also provide a lead4in to the topic of $uilding custom
e/ceptions t+pes as )ell as ho) to leverage the $uilt4in e/ception handling functionalit+ of 2S.N.T.
1.=D Meaning o" Errors? ,ugs and E;ce!tions
Mistakes are $ound to happen during programming. Pro$lems ma+ occur due to $ad code like overflo)
of arra+ inde/, invalid input etc. So, the programmer needs to handle all possi$le t+pes of pro$lems.
There are three terminologies to define mistakes that ma+ occur.
e /ugs!
< .rrors done $+ the programmer.
< ./ample6 making use of NU!! pointer, referring arra+ inde/ out of $ound, not deleting
allocated memor+ etc.
e Errors!
< aused $+ user of the application.
< 0or e/ample6 entering un4e/pected value in a te/t$o/, sa+ USN.
e Exceptions!
< "untime anomalies those are difficult to prevent.
< ./ample6 tr+ing to open a corrupted file, tr+ing to connect non4e/isting data$ase etc.
1.=E T2e 4ole o" .NET E;ce!tion Qandling
The .N.T platform provides a standard techniJue to send and trap runtime errors6 structured e/ception
handling (S.;#. The $eaut+ of this approach is that developers no) have a unified approach to error
handling, )hich is common to all languages targeting the .N.T universe. 'nother $onus of .N.T
e/ceptions is the fact that rather than receiving a cr+ptic numerical value that identifies the pro$lem at
hand, e/ceptions are o$7ects that contain a human4reada$le description of the pro$lem, as )ell as a
detailed snapshot of the call stack that triggered the e/ception in the first place. 0urthermore, +ou are
R.V.COLLEGE OF ENGINEERING Page =1C
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
a$le to provide the end user )ith help link information that points the user to a U"! that provides detailed
information regarding the error at hand as )ell as custom user4defined data.
T2e (toms o" .NET E;ce!tion Qandling
Programming )ith structured e/ception handling involves the use of four interrelated entities6
' class t+pe that represents the details of the e/ception that occurred
' mem$er that t)rows an instance of the e/ception class to the caller
' $lock of code on the caller9s side that invokes the e/ception4prone mem$er
' $lock of code on the caller9s side that )ill process (or catc)# the e/ception should it occur
The & programming language offers four ke+)ords (tr+, catch, thro), and finall+# that allo) +ou to
thro) and handle e/ceptions. The t+pe that represents the pro$lem at hand is a class derived from
S+stem../ception
1.=F T2e System.E;ce!tion ,ase Class
'll user4 and s+stem4defined e/ceptions ultimatel+ derive from the S+stem../ception $ase class ()hich
in turn derives from S+stem.($7ect#. ore Mem$ers of the S+stem../ception T+pe are sho)n $elo)6
S+stem../ception
Pro!erty
Meaning
;elp!ink This propert+ returns a U"! to a help file descri$ing the error in full
detail.
*nner./ception Used to o$tain information a$out the previous e/ceptions that caused
the current e/ception to occur. The previous e/ceptions are recorded
$+ passing them into the constructor of the most current e/ception.
This is a read4onl+ propert+.
R.V.COLLEGE OF ENGINEERING Page =1D
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Message "eturns the te/tual description of a given error. The error message
itself is set as a constructor parameter. This is a read4onl+ propert+.
Source "eturns the name of the assem$l+ that thre) the e/ception.
StackTrace ontains a string that identifies the seJuence of calls that triggered the
e/ception. This is a read4onl+ propert+.
TargetSite "eturns a Method4Base t+pe, )hich descri$es numerous details a$out
the method that thre) the e/ception (ToString(# )ill identif+ the
method $+ name#. This is a read4onl+ propert+.
1.@G T2ro0ing a Eeneric E;ce!tion
,uring the program, if an+ e/ception occurs, )e can thro) it to either a specific e/ception like
ileNotoundE'ception, ArrayInde':ut:f=oundE'ception, %ivide=yBeroE'ception etc. or )e can
through a generic e/ception directl+ using E'ception class. The o$7ect of E'ception class can handle an+
t+pe of e/ception, as it is a $ase class for all t+pe of e/ceptions. ;ere is an e/ample to sho) ho) to
thro) an e/ception6
using S+stemO
class Test
M
int Ma/Q1GGO
pu$lic void 0un(int d#
M
if(dYMa/#
thro) ne) ./ception(Rcrossed limitLLLR#O
R.V.COLLEGE OF ENGINEERING Page =1E
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
else
onsole.%rite!ine(RdQMGNR, d#O
N
pu$lic static void Main(#
M
Test o$Qne) Test(#O
onsole.%rite!ine(R.nter a num$er6R#O
int dQint.Parse(onsole."ead!ine(##O
o$.0un(d#O
N
N
Out!ut:
.nter a num$er6 1=
dQ1=
.nter a num$er6 BCD
Unhandled ./ception6 S+stem../ception6 crossed limitLLL
at Test.0un(*nt@= d#
at Test.Main(#
*n the a$ove e/ample, if the entered value d is greater than 1GG, then )e are thro)ing an e/ception. %e
are passing message 3crossed limit9 to a !essage property of E'ception class.
R.V.COLLEGE OF ENGINEERING Page =1F
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
,eciding e/actl+ )hat constitutes thro)ing an e/ception and )hen to thro) an e/ception is up to the
programmer.
1.@1 Catc2ing E;ce!tions
%hen a $lock of code is $ound to thro) an e/ception, it needs to $e caught using catc) statement. (nce
)e catch an e/ception, )e can invoke the mem$ers of S+stem../ception class. Using these mem$ers in
the catc) $lock, )e ma+ displa+ a message a$out the e/ception, store the information a$out the error in a
file, send a mail to administrator etc. 0or e/ample,
using S+stemO
class Test
M
int Ma/Q1GGO
pu$lic void 0un(int d#
M
tr+
M
if(dYMa/#
thro) ne) ./ception(Rcrossed limitLLLR#O
N
catch(./ception e#
M
onsole.%rite!ine(RMGNR, e.Message#O
N
onsole.%rite!ine(RdQMGNR, d#O
R.V.COLLEGE OF ENGINEERING Page ==G
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
pu$lic static void Main(#
M
Test o$Qne) Test(#O
onsole.%rite!ine(R.nter a num$er6R#O
int dQint.Parse(onsole."ead!ine(##O
o$.0un(d#O
N
N
Out!ut:
.nter a num$er6 1=
dQ1=
.nter a num$er6 1=@
crossed limitLLL
dQ1=@
*n the a$ove e/ample, )e are thro)ing an e/ception if dC2@@ and is caught. Thro)ing an e/ception using
the statement <
t)row new E'ception ,<#rossed Limit9-O
means, creating an o$7ect of E'ception class and passing that o$7ect to catc) $lock. %hile passing an
o$7ect, )e are passing the message also, )hich )ill $e an input for the !essage propert+ of E'ception
class.
R.V.COLLEGE OF ENGINEERING Page ==1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
' tr+ $lock is a section of code used to check for an+ e/ception that ma+ $e encountered during its scope.
*f an e/ception is detected, the program control is sent to the appropriate catch $lock. *f the code )ithin
tr+ $lock does not trigger an+ e/ception, then the catch $lock is skipped full+ and program )ill continue
to e/ecute further.
(nce an e/ception has $een handled, the application )ill continue its e/ecution from ver+ ne/t point after
catch $lock. *n some situations, a given e/ception ma+ $e critical and it ma+ )arrant the termination of
the application. ;o)ever, in most of the cases, the logic )ithin the e/ception handler )ill ensure the
application to $e continued in ver+ normal )a+.
T2e Target$ite Pro!erty
The S+stem../ception.TargetSite propert+ allo)s to determine various details a$out the method
that thre) a given e/ception.
Printing the value of TargetSite )ill displa+ the return t+pe, name, and parameters of the method
that thre) the e/ception.
;o)ever, TargetSite does not simpl+ return a string, $ut a strongl+ t+ped
S+stem."eflection.MethodBase o$7ect.
This t+pe can $e used to gather numerous details regarding the offending method as )ell as the
class that defines the offending method.
T2e $tac6Trace Pro!erty
e The S+stem../ception.StackTrace propert+ allo)s +ou to identif+ the series of calls that resulted
in the e/ception.
e Be a)are that +ou never set the value of StackTrace as it is esta$lished automaticall+ at the time
the e/ception is created.
e The string returned from StackTrace documents the seJuence of calls that resulted in the
thro)ing of this e/ception.
R.V.COLLEGE OF ENGINEERING Page ===
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
using S+stemO
class Test
M
int Ma/Q1GGO
pu$lic void 0un(int d#
M
tr+
M
if(dYMa/#
thro) ne) ./ception(string.0ormat(Rcrossed limitLLLR##O
N
catch(./ception e#
M
onsole.%rite!ine(RMGNR,e.Message#O ?? crossed limitLLL
onsole.%rite!ine(RMGNR, e.TargetSite#O ??2oid 0un(*nt@=#
onsole.%rite!ine(RMGNR,e.TargetSite.,eclaringT+pe#O ??Test
onsole.%rite!ine(RMGNR, e.TargetSite.Mem$erT+pe#O ??Method
onsole.%rite!ine(RStack6MGNR, e.StackTrace#O
??at Test.0un(*nt@= d#
N
onsole.%rite!ine(RdQMGNR, d#O
N
pu$lic static void Main(#
M
R.V.COLLEGE OF ENGINEERING Page ==@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Test o$Qne) Test(#O
onsole.%rite!ine(R.nter a num$er6R#O
int dQint.Parse(onsole."ead!ine(##O ??assume d is 1=@
o$.0un(d#O
N
N
NOTE: The comment lines for the statements )ithin the function un,- are the outputs for the input d
greater than 1GG.
T2e 0elplin6 Pro!erty
e The ;elp!ink propert+ can $e set to point the user to a specific U"! or standard %indo)s help
file that contains more detailed information.
e B+ default, the value managed $+ the ;elp!ink propert+ is an empt+ string.
e *f +ou )ish to fill this propert+ )ith an interesting value, +ou )ill need to do so $efore thro)ing
the S+stem../ception t+pe.
using S+stemO
class Test
M
int Ma/Q1GGO
pu$lic void 0un(int d#
M
tr+
M
if(dYMa/#
R.V.COLLEGE OF ENGINEERING Page ==A
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
./ception e/Q ne) ./ception(Rcrossed limitLLLR#O
e/.;elp!inkQRg6[[;elp.docRO
thro) e/O
N
N

catch(./ception e#
M
onsole.%rite!ine(RMGNR, e.;elp!ink#O ?? 16[;elp.doc
N
onsole.%rite!ine(RdQMGNR, d#O
N
pu$lic static void Main(#
M
Test o$Qne) Test(#O
onsole.%rite!ine(R.nter a num$er6R#O
int dQint.Parse(onsole."ead!ine(##O ??sa+ dQ@AB
o$.0un(d#O
N
N
1.@= C#4 System #evel E;ce!tions
R.V.COLLEGE OF ENGINEERING Page ==B
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
The .N.T $ase class li$raries define man+ classes derived from S+stem../ception. 0or e/ample, the
S+stem namespace defines core error o$7ects such as 'rgument(ut(f"ange./ception,
*nde/(ut(f"ange4./ception, Stack(verflo)./ception etc. (ther namespaces define e/ceptions that
reflect the $ehavior of that namespace. 0or e/. S+stem.,ra)ing.Printing defines printing e/ceptions,
S+stem.*( defines *(4$ased e/ceptions, S+stem.,ata defines data$ase4centric e/ceptions, and so on.
./ceptions that are thro)n $+ the methods in the B! are called system e'ceptions. These e/ceptions are
regarded as non4recovera$le, fatal errors. S+stem e/ceptions derive directl+ from a $ase class named
S+stem.S+stem./ception, )hich in turn derives from S+stem../ception ()hich derives from
S+stem.($7ect#6
pu$lic class S+stem./ception 6 ./ception
M
$$ +arious constructors.
N
The S+stem.S+stem./ception t+pe does not add an+ additional functionalit+ $e+ond a set of constructors.
1.@@ Custom (!!lication #evel E;ce!tions
'll .N.T e/ceptions are class t+pes and hence )e can create our o)n application4specific e/ceptions.
Since the S+stem.S+stem./ception $ase class represents e/ceptions thro)n from the !", )e ma+
naturall+ assume that )e should derive +our custom e/ceptions from the S+stem../ception t+pe. But, the
$est practice is to derive from the S+stem.'pplication./ception t+pe6
R.V.COLLEGE OF ENGINEERING Page ==C
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic class 'pplication./ception 6 ./ception
M
$$ +arious constructors.
N
The purpose of S+stem.'pplication./ception is to identif+ the source of the (nonfatal# error. %hen )e
handle an e/ception deriving from S+stem.'pplication./ception, )e can assume that e/ception )as
raised $+ the code4$ase of the e/ecuting application rather than $+ the .N.T B!. The relationship
$et)een e/ception4centric $ase classes are sho)n <

Trul+ speaking, it is not necessar+ to derive a custom e/ception from S+stem.'pplication./ception class,
rather it can directl+ $e derived from more generic S+stem../ception class. To understand various
possi$ilities, no) )e )ill $uild custom e/ceptions.
R.V.COLLEGE OF ENGINEERING Page ==D
Syste&#A((licati%n!0ce(ti%n
Syste&#ObHect
Syste&#!0ce(ti%n
L%ur A((licati%nMs
Cust%& !0ce(ti%ns
Syste&#Syste&!0ce(ti%
n
!0ce(ti%ns )r%&
#+!T BCL
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)

,uilding Custom E;ce!tions: Ta3e One
%e can al)a+s thro) instances of S+stem../ception to indicate runtime error. But, it is $etter to $uild a
strongly typed e'ception that represents the uniJue details of our current pro$lem. The first approach is
defining a ne) class derived directl+ from S+stem../ception. !ike an+ class, the e/ception class also ma+
include fields, methods and properties that can $e used )ithin the catch $lock. %e can also override an+
virtual mem$er in the parent class. 0or e/ample, assume )e )ish to $uild a custom e/ception (named
ar*s,ead./ception# to represent that the car has crossed the ma/imum speed limit.
pu$lic class ar*s,ead./ception 6 S+stem../ception
M
private string message,etailsO
pu$lic ar*s,ead./ception(#M N
pu$lic ar*s,ead./ception(string message#
M
message,etails Q messageO
N
$$ Override t2e E;ce!tion.Message !ro!erty.
pu$lic override string Message
M
get
M
return string.0ormat(Rar .rror Message6 MGNR, message,etails#O
N
R.V.COLLEGE OF ENGINEERING Page ==E
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
N
pu$lic class ar
M
]]]]]]]]
pu$lic void SpeedUp(int delta#
M
tr+
M
speedQcurrentSspeed H deltaO
if(speedYma/Sspeed#
thro) ne) ar*s,ead./ception(30ord *kon5#O
N
catch(ar*s,ead./ception e#
M
onsole.%rite!ine(3Method6MGN5, e.TargetSite#O
onsole.%rite!ine(3Message6MGN5, e. Message#O
N
N
]]]]]]]]..
N
Note that, the custom e/ceptions are needed onl+ )hen the error is tightl+ $ound to the user4defined class
issuing the error. 0or e/ample, a 0ile class ma+ thro) num$er of file4related errorsO Student class ma+
R.V.COLLEGE OF ENGINEERING Page ==F
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
thro) errors related to student information and so on. B+ )riting the custom e/ception, )e provide the
facilit+ of handling numerous e/ceptions on a name4$+4name $asis.
,uilding Custom E;ce!tions: Ta3e T0o
%e can )rite the constructors, methods and overridden properties as )e )ish in our e/ception class. But
it is al)a+s recommended approach to $uild a relativel+ simple t+pe that supplied three named
constructors matching the follo)ing signature <
pu$lic class ar*s,ead./ception 6 S+stem../ception
M
pu$lic ar*s,ead./ception(#M N
pu$lic ar*s,ead./ception(string message#6$ase(message#
M
N
pu$lic ar*s,ead./ception(string message, ./ception
inner./#6$ase(message, inner./#
M
N
N
Most of the user defined e/ceptions follo) this pattern. Because, man+ times, the role of a custom
e/ception is not to provide additional functionalit+ $e+ond )hat is provided $+ its $ase class. "ather, to
provide a strongly named type that clearl+ identifies the nature of the error.
R.V.COLLEGE OF ENGINEERING Page =@G
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
,uilding Custom E;ce!tions: Ta3e T2ree
%e have discussed thatO e/ceptions can $e s+stem4level or application4level. *f )e )ant to clearl+ mark
our e/ception to $e thro)n $+ the application itself and not $+ an+ chance $+ B!, )e can redefine as <
pu$lic class ar*s,ead./ception6 'pplication./ception
M
??$od+
N
1.@A Qandling Multi!le E;ce!tions
%e have seen a situation )here a tr+ $lock )ill have corresponding catch $lock. But in realit+, )e ma+
face a situation )here the code )ithin tr+ $lock ma+ trigger multiple possi$le e/ceptions. 0or e/ample,
pu$lic void SpeedUp(int delta#
M
tr+
M
if(deltaXG#
thro) ne) 'rgument(ut(f"ange./ception(30ord *kon5#O
speedQcurrentSspeed H deltaO
if(speedYma/Sspeed#
thro) ne) ar*s,ead./ception(30ord *kon5#O
N
R.V.COLLEGE OF ENGINEERING Page =@1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
catch(ar*s,ead./ception e#
M
onsole.%rite!ine(3Method6MGN5, e.TargetSite#O
onsole.%rite!ine(3Message6MGN5, e. Message#O
N
catch('rgument(ut(f"ange./ception e#
M
onsole.%rite!ine(3Method6MGN5, e.TargetSite#O
onsole.%rite!ine(3Message6MGN5, e. Message#O
N
N
*n the a$ove e/ample, if delta is less than 8ero, then Argument:ut:f6angeE'ception is triggered. *f the
speed e/ceeds !a'Speed, then #arIs%eadE'ception is thro)n. %hile constructing multiple catch $locks
for a single tr+ $lock, )e must $e a)are that it )ill $e processed $+ the nearest available catch $lock. 0or
e/ample, the follo)ing code snippet generates compile4time errorLL
tr+
M
4444444444
N
catch(./ception e#
M
44444444444444
R.V.COLLEGE OF ENGINEERING Page =@=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
catch(ar*s,ead./ception e#
M
44444444444444
N
catch(Argument:ut:f6angeE'ception e-
M
44444444444444
N
;ere, the class E'ception is a $ase class for all user4defined and $uilt4in e/ceptions. ;ence, it can handle
an+ t+pe of e/ceptions. Thus, if E'ception is the first catch4$lock, the control )ill 7ump to that $lock
itself and the other t)o e/ceptions are unreac)able. Thus, during multiple e/ceptions, )e have to design
ver+ structured format. The ver+ first catch $lock should contain ver+ specific e/ception or the most
derived t+pe in inheritance hierarch+. %hereas the last catch $lock should $e the most general or the top
most $ase class in inheritance hierarch+.
Eeneric Catc2 Statements
& supports a generic catch $lock that does not e/plicitl+ define the t+pe of e/ception. That is, )e can
)rite <
catch
M
onsole.%rite!ine(3Some error has occurred5#O
N
R.V.COLLEGE OF ENGINEERING Page =@@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
But, using this t+pe of catch $locks indicates that the programmer is un4a)are of the t+pe of e/ception
that is going to occur, )hich is not accepta$le. ;ence it is al)a+s advised to use specific t+pe of
e/ceptions.
4e8t2ro0ing E;ce!tions
*t is possi$le to re4thro) an error to the previous caller. 0or e/ample<
tr+
M
4444444444444444
N
catch(ar*s,ead./ception e#
M
??handle ar*s,ead./ception partiall+ or do something
thro) eO
N
*n the a$ove code, the statement t)row e )ill thro) the e/ception again to #arIs%eadE'ception.
1.@B T2e inally ,loc3
The tr+?catch $lock ma+ $e added )ith an optional inally $lock. The finally $lock contains a code that
al)a+s e/ecutes irrespective of an+ num$er of e/ceptions that ma+ interfere )ith the normal flo) of
e/ecution. 0or e/ample, )e ma+ )ant to turn4off radio )ithin a car $efore stopping the car due to an+
reason. Programmaticall+ speaking, $efore e/iting from Main(# function, )e ma+ need to turn4off radio of
a car. Then )e can )rite <
R.V.COLLEGE OF ENGINEERING Page =@A
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic static void Main(#
M
tr+
M
??increase speed
N
catch(ar*s,ead./ception e#
M
44444444444
N
catch(Argument:ut:f6angeE'ception e-
M
44444444444444
N
"inally
M
arName.Turn(ff"adio(#O
N
N
NOTE:
The finall+ $lock is useful in follo)ing situations <
%hen )e )ant to
< clean4up an+ allocated memor+
R.V.COLLEGE OF ENGINEERING Page =@B
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
< lose a file )hich is in use
< lose a data$ase connection to a data source
The finall+ $lock )ill $e e/ecuted even if our tr+ $lock does not trigger an+ e/ception.
This is especiall+ helpful if a given e/ception reJuires the termination of the current application.
1.@C 1ynamically denti"ying (!!lication and System #evel
E;ce!tions
*n the previous e/amples, )e have handled each e/ception $+ its specific class name. 'lternativel+, if )e
)ant to generali8e our catch $locks in such a )a+ that all application level e/ceptions are handled apart
from possi$le s+stem4level e/ceptions6
tr+
M
??do something
N
catch('pplication./ception e#
M
444444444444444
N
catch(S+stem./ception e#
M
444444444444444
N
R.V.COLLEGE OF ENGINEERING Page =@C
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Though & has the a$ilit+ to discover at runtime the underl+ing source of an e/ception, )e are gaining
nothing $+ doing so. Because some B! methods that should ideall+ thro) a t+pe derived from
S+stem.S+stem./ception are actuall+ derived from S+stem.'pplication./ception or even more generic
S+stem../ception.
1.@D Summary
This unit e/amined one of the ((P4centric topic vi8. e/ceptions. -ou )ere sho)n ho) the .N.T runtime
makes use of structured e/ception handling to contend )ith runtime pro$lems. Using a small set of
ke+)ords (tr+, catch, thro) and finall+#, & programmers are a$le to raise and handle s+stem4level and
application4level e/ceptions.
1.@E :ey0ords
Bugs, .rrors, ./ceptions
S+stem../ception Base lass and its properties
1eneric e/ception
The ke+)ords try, catc), t)row and finally
S+stem level and 'pplication !evel e/ceptions
Building ustom?User4defined e/ceptions
Multiple e/ceptions
"e4thro)ing ./ceptions
1.@F E;ercises
R.V.COLLEGE OF ENGINEERING Page =@D
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1. %hat do +ou understand $+ e/ception in &P *llustrate the use of S+stem../ception $ase class in
thro)ing generic e/ceptions.
=. ,ifferentiate $et)een $ugs, errors and e/ceptions. ./plain the concepts of .N.T e/ception handling
)ith valid e/ample code.
@. ./plain the follo)ing properties6 TargetSite, StackTrace, ;elp!ink.
A. ./plain the concept of re4thro)ing the e/ception.
B. %hat do +ou mean $+ custom e/ceptionP %rite a program to $uild a custom e/ception )hich raises
an e/ception )hen the argument passed is a negative num$er.
C. Briefl+ e/plain the usage of finally $lock.
Module &
Unit '
CONTENTS:
1.AB ($7ectives
=.=C *ntroduction
=.=D Understanding ($7ect !ifetime
=.=E The *! of new
=.=F The Basics of 1ar$age ollection
=.@G 0inali8ation a t+pe
=.@1 The 0inali8ation Process
=.@= Building an ', ;oc ,estruction Method
=.@@ 1ar$age ollection (ptimi8ations
=.@A The S+stem. 1 T+pe
=.@B Summar+
=.@C :e+)ords
=.@D ./ercises
=.1 Objectives
R.V.COLLEGE OF ENGINEERING Page =@E
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
't the end of this lesson, the students )ill understand the follo)ing tasks in detail6
The concept of 1ar$age ollection and need for it
*dea a$out heap memor+, meaning of new during o$7ect creation
Meaning of finali8ation and the method inali$e,-
Usage of *,isposa$le *nterface
The S+stem.1 class
=.=B ntroduction
This unit e/amines the process of o$7ect lifetime management as handled $+ the !". 's +ou )ill see,
the .N.T runtime destro+s o$7ects in a rather nondeterministic nature. Thus, +ou t+picall+ do not kno)
)hen a given o$7ect )ill $e de4allocated from the managed heap, onl+ that it )ill come to pass. (n this
note, +ou )ill come to understand ho) the S+stem.($7ect.0inali8e(# method and *,isposa$le interface
can $e used to interact )ith an o$7ect9s lifetime management. 0inall+, )e )rap up )ith an e/amination of
the S+stem.1 t+pe, and illustrate a num$er of )a+s +ou are a$le to get involved )ith the gar$age
collection process.
=.=C Understanding Object #i"etime
B+ the e/ample programs )e have seen in previous four chapters, )e can note that )e have never directl+
de4allocated an o$7ect from memor+. That is there is no delete ke+)ord in &. "ather, .N.T o$7ects are
allocated onto a region of memor+ termed as managed heap, )here the+ )ill $e automaticall+ de4
allocated $+ the !" at some time later.
Thus, the golden rule of .N.T memor+ management is <
Allocate an ob&ect onto the managed heap using the new 6eyword and orget about it.
R.V.COLLEGE OF ENGINEERING Page =@F
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
(nce an o$7ect is created using new, the !" removes it )hen it is no longer needed. That is, the !"
removes an o$7ect from the heap )hen it is unreacha$le $+ the current application. 0or e/ample,
pu$lic static void Main(#
M
ar cQne) ar(30ord *kon5#O
]]]]]]
N
;ere, c is created )ithin the scope of Main(#. Thus, once the application shuts do)n, this reference is no
longer valid and therefore it is a candidate for gar$age collection. But, )e can not surel+ sa+ that the
o$7ect c is destro+ed immediatel+ after Main(# function. 'll )e can sa+ is )hen !" performs the ne/t
gar$age collection, c is read+ to $e destro+ed.
=.=D T2e C# o" new
;ere )e )ill discuss )hat actuall+ happens )hen new ke+)ord is used.
%hen & encounters the new ke+)ord, it )ill produce a *! newob& instruction to the code module.
Note that, the managed heap is not 7ust a ra) portion of memor+ accessed $+ the !".
The .N.T gar$age collector )ill compact empt+ $locks of memor+, )hen needed, for the purpose of
optimi8ation.
To help this process, the managed heap maintains a pointer, referred as new ob&ect pointer that
identifies e/actl+ )here the next ob&ect )ill $e placed on the heap.
'fter these tasks, the newob& instruction informs the !" to perform the follo)ing seJuence of
events6
R.V.COLLEGE OF ENGINEERING Page =AG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
alculate the total amount of memor+ reJuired for the o$7ect to $e allocated. *f this o$7ect
contains other internal o$7ects (i.e. )as-a relationship and?or nested t+pe mem$er#, the+ are
also added4up. 'nd the memor+ reJuired for each $ase class is also considered (i.e is-a
relationship#.
The !" then e/amines the managed heap to ensure that there is enough space for the o$7ect
to $e allocated. *f so, the o$7ect9s constructor is called and a reference to the o$7ect in the
memor+ is returned.
0inall+, $efore returning the reference, the !" )ill move the ne) o$7ect pointer to point to
the ne/t availa$le slot on the managed heap.
The entire process is depicted here4under6

=.=E T2e ,asics o" Earbage Collection
'fter creating so man+ o$7ects, the managed heap ma+ $ecome full.
%hen the newob& instruction is $eing processed, if the !" determins that the managed heap does
not have sufficient memor+ to allocate the reJuested t+pe, it )ill perform a gar$age collection in an
attempt to free4up the memor+.
Thus, the ne/t rule of gar$age collection is6
R.V.COLLEGE OF ENGINEERING Page =A1
c- c3 c5
Unused Iea(
S(ace
Car c-?ne2 Car"N%rdO$J
Car c3?ne2 Car"NS2i)tO$J
Car c5?ne2 Car"NPenO$J
+e2 %bHect (%inter
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
o ( the managed heap does not ha,e suicient memory to allocate a new ob&ect7 a garbage
collection will occur.
No) the Juestion arise6 ho) !" is a$le to determine an o$7ect on the heap that it is no longer
needed and destro+ itP
To ans)er this Juestion, )e should kno) application roots.
' root is a storage location containing a reference to an o$7ect on the heap.
*n other )ords, a root is a varia$le in our application that points to some area of memor+ on the
managed heap.
The root can fall into an+ of the follo)ing categories6
< "eference to glo$al o$7ects (Though glo$al o$7ects are not allo)ed in &, ra) *! does
permit allocation of glo$al o$7ects#
< "eference to static o$7ects
< "eferences to local o$7ects )ithin a given method
< "eferences to o$7ect parameters passed into a method
< 'n+ PU register that references a local o$7ect
%hen a gar$age collection occurs, the runtime (!"# )ill check all o$7ects on the managed heap to
determine if it is still in use (or rooted# in the application.
To do so, the !" )ill $uild an ob&ect graph, )hich represents each o$7ect on the heap that is still
reacha$le.
The o$7ect graph documents all co4dependencies for the current o$7ect.
The !" )ill ensure that all related o$7ects are considered $efore a possi$le gar$age collection
through the construction of an o$7ect graph.
The !" )ill never graph the same o$7ect t)ice, and thus avoids the circular reference count.
To illustrate this concept, assume that the managed heap contains a set of o$7ects named ', B, , ,, ., 0,
and 1. ,uring a gar$age collection, these o$7ects (as )ell as an+ internal o$7ect references the+ ma+
contain# are e/amined for active roots. (nce the graph has $een constructed, unreacha$le o$7ects, sa+, the
o$7ects and 0 are marked as gar$age as sho)n in the follo)ing diagram6
R.V.COLLEGE OF ENGINEERING Page =A=
Managed Iea(
+e2 ObHect (%inter
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
No), a possi$le o$7ect graph ma+ look like <
;ere, the arro)s indicate depends on or re&uires. 0or e/ample, . depends on 1, B depends on . and also
1, ' is not depending on an+thing etc. (nce an o$7ect has $een marked for collection (here, and 0#,
the+ are not considered for o$7ect graph creation and are s)ept from the memor+. 't this point, the
remaining space on the heap is compacted, )hich in turn )ill cause the !" to modif+ the set of active
application roots to refer to the correct memor+ location (this is done automaticall+ and transparentl+#.
Then, the ne) o$7ect pointer is read7usted to point to the ne/t availa$le slot. 0ollo)ing diagram depicts it
<
R.V.COLLEGE OF ENGINEERING Page =A@
' B , . 0 1
' B , . 1
A
G
E D
B
Managed Iea(
+e2 ObHect (%inter
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
=.=F *inali<ing a Ty!e
0rom the previous discussion, )e can easil+ make out that the .N.T gar$age collection scheme is non-
deterministic in nature. *n other )ords, )e can not determine e/actl+ )hen an o$7ect )ill $e de4allocated
from the memor+. This approach seems to $e Juite good $ecause, )e, the programmers need not )orr+
once the o$7ect has $een created. But, there is a possi$ilit+ that the o$7ects are holding unmanaged
resources (%in@= files etc# longer than necessar+.
%hen )e $uild .Net t+pes that interact )ith unmanaged resources, )e like to ensure that this resource is
released in4time rather than )aiting for .N.T gar$age collector. To facilitate this, the & provides an
option for overriding the virtual S+stem.($7ect.0inali8e(# method. The default implementation of
0inali8e(# method does nothingLL Note that )e need to override it onl+ if )e are making use of
unmanaged resources. (ther)ise, the & gar$age collector )ill do the 7o$.
& )ill not allo) the programmer to directl+ override the 0inali8e(# method.
pu$lic class Test
M
protected override void 0inali8e(# ??error111
M ]]]. N
N
"ather, )e need to use a HH 4t+pe destructor s+nta/6
pu$lic class Test
M
cTest(#
R.V.COLLEGE OF ENGINEERING Page =AA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
]]]
N
N
ndirectly nvo3ing System.Object.*inali<e56
%e have discussed till no) that the .N.T runtime )ill trigger gar$age collector )hen it reJuires more
memor+ that )hat is availa$le at heap. But also note that, the finali8ation )ill automaticall+ take place
)hen an application domain or App4omain is unloaded $+ !". 'pplication domain can $e assumed to
$e 'pplication itself. Thus, once our application is a$out to shut do)n, the finali8e logic is triggered.
Thus, the ne/t rule of gar$age collection is6
8hen an App4omain is unloaded7 the Finali9e%5 method is in,o6ed or all inali9able
ob&ects.
0or illustration, consider the follo)ing e/ample <
using S+stemO
class Test
M
pu$lic Test(#
M N
cTest(#
M
R.V.COLLEGE OF ENGINEERING Page =AB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsole.%rite!ine(R0inali8ingLLLR#O
N
pu$lic static void Main(#
M
onsole.%rite!ine(3%ithin Main(#R#O
Test tQne) Test(#O
onsole.%rite!ine(3./iting Main(#R#O
N
N
Out!ut:
%ithin Main(#
./iting Main(#
0inali8ingLLL
%e can see that, once the program control goes out the scope of Main(# function, the destructor is called
for the o$7ect t. *n the destructor or the finali8er, )e need to )rite the code to release the resources that
ma+ $e held $+ the o$7ect t.
=.@G T2e *inali<ation Process
Though finali8er seems to $e good to use, it is not advised unless the o$7ects in our application are using
unmanaged resources. The good programming practice is to avoid 0inali8e(# method, as finali8ation takes
time.
R.V.COLLEGE OF ENGINEERING Page =AC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
%hen an o$7ect is placed on a heap using new, the !" automaticall+ determines )hether this o$7ect
supports a user4defined 0inali8e(# method.
*f +es, the o$7ect is marked as inali9able and a pointer to this o$7ect is stored on an internal Jueue
names as the inali9ation :ueue.
The finali8ation Jueue is a ta$le maintained $+ the !" that points to ever+ o$7ect that must $e
finali8ed $efore it is removed from the heap.
%hen the gar$age collector starts its action, it checks ever+ entr+ on the finali8ation Jueue and copies
the o$7ect from the heap to another !"4managed structure termed as inali9ation reachable table %-
reachable5.
't this moment, a separate thread is produced to invoke the 0inali8e(# method for each o$7ect on the
f4reacha$le ta$le at the ne't garbage collection.
Thus, )hen )e $uild a custom4t+pe (user4defined t+pe# that overrides the S+stem.($7ect.0inali8e(#
method, the .N.T runtime )ill ensure that this mem$er is called )hen our o$7ect is removed from the
managed heap.
But this )ill consume time and hence affects the performance of our application.
=.@1 ,uilding an (d Qoc 1estruction Met2od
%e have seen that the o$7ects holding unmanaged resources can $e destro+ed using 0inali8e(# method.
But the process of finali8ation is time consuming. & provides an alternative )a+ to avoid this pro$lem of
time consumption.
The programmer can )rite a custom ad hoc method that can $e invoked manuall+ $efore the o$7ect goes
out of the scope. This )ill avoid the o$7ect $eing placed at finali8ation Jueue and avoid )aiting for
gar$age collector to clean4up. The user4defined method )ill take care of cleaning up the unmanaged
resources.
pu$lic class ar
M ]]]]..
R.V.COLLEGE OF ENGINEERING Page =AD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic void :ill(# ??name of method can $e an+thing
M
??clean up unmanaged resources
N
N
T2e (4isposable nter"ace
*n order to provide s+mmetr+ among all o$7ects that support an e/plicit destruction, the .N.T class
li$raries define an interface named (4isposable. This interface contains a single mem$er 4ispose%5!
pu$lic interface *,isposa$le
M
pu$lic void ,ispose(#O
N
No), our application can implement this interface and define %ispose,- method. Then, this method can $e
called manuall+ to release unmanaged resources. Thus, )e can avoid the pro$lems )ith finali8ation.
pu$lic class ar6 *,isposa$le
M ]]]
pu$lic void ,ispose(#
M
??code to clean up unmanaged resources
N
N
R.V.COLLEGE OF ENGINEERING Page =AE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
class Test
M ]]]].
pu$lic static void Main(#
M
ar cQne) ar(30ord5#O
]]].
c.,ispose(#O
]]]
N ??c still remains on heap and ma+ $e collected $+ 1 no)
N
Thus, another rule for )orking )ith gar$age collection is6
Always call 4ispose%5 or any ob&ect in the heap. The assumption is! i there is a 4ispose%5
method7 the ob&ect has some clean up to perorm.
Note that, for a single class, it is possi$le to have & 4 st+le destructor and also to implement *,isposa$le
interface for defining ,ispose(# method.
4eusing t2e C7 using :ey0ord
%hen )e are using an o$7ect that implements *,isposa$le, it is Juite common to use structured
e/ceptions 7ust to ensure the ,ispose(# method is called )hen e/ception occurs6
pu$lic void Test(#
M
R.V.COLLEGE OF ENGINEERING Page =AF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
ar cQne) ar(#O
tr+
M
]]..
N
catchM ]].. N
finall+
M ]]..
c.,ispose(#O
N
N
& provides another )a+ of doing this )ith the help of using ke+)ord6
pu$lic void Test(#
M
using(ar cQne) ar(##
M
??,o something
??,ispose(# method is called automaticall+ )hen this $lock e/its
N
N
(ne good thing here is, the %ispose,- method is called automaticall+ )hen the program control comes out
of using $lock. But there is a disadvantage6 *f at all the o$7ect specified at using does not implement
*,isposa$le, then )e )ill get compile4time error.
R.V.COLLEGE OF ENGINEERING Page =BG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
=.@= Earbage Collection O!timi<ations
Till no) )e have seen t)o methodologies for cleaning user4defined t+pes. No), )e )ill discuss little
deepl+ a$out the functionalit+ of .N.T gar$age collector.
%hen !" is attempting to locate unreacha$le o$7ects, it does not literall+ search through ever+
o$7ect placed on the managed heap looking for orphaned roots.
Because, doing so )ill consume more time for larger applications.
To optimi8e the collection process, each o$7ect on the heap is assigned to a given generation.
The idea $ehind generation is as follo)s6
o *f an o$7ect is on the heap since long time, it means, the o$7ect )ill continue to e/ist for more
time. 0or e/ample, application4level o$7ects.
o onversel+, if an o$7ect has $een recentl+ placed on the heap, it ma+ $e dereferenced $+ the
application Juickl+. 0or e/ample, o$7ects )ithin a scope of a method.
Based on these assumptions, each o$7ect $elongs to one of the follo)ing generations6
o ;eneration <! *dentifies a ne)l+ allocated o$7ect that has never $een marked for collection.
o ;eneration *! *dentifies an o$7ect that has survived a gar$age collection s)eep (i.e. it )as
marked for collection, $ut )as not removed due to the fact that the heap had enough free
space#
o ;eneration =! *dentifies an o$7ect that has survived more than on s)eep of the gar$age
collector.
No), )hen a collection occurs, the 1 marks and s)eeps all generation G o$7ects first.
*f reJuired amount of memor+ is gained, the remaining o$7ects are promoted to the ne/t availa$le
generation.
To illustrate ho) an o$7ect9s generation affects the collection process, consider the follo)ing diagram <
R.V.COLLEGE OF ENGINEERING Page =B1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
*f all generation G o$7ects have $een removed from heap and still more memor+ is necessar+,
generation 1 o$7ects are checked for their reacha$ilit+ and collected accordingl+.
Surviving generation 1 o$7ects are then promoted to generation =.
*f the gar$age collector still reJuires additional memor+, generation = o$7ects are checked for their
reacha$ilit+.
't this point, if generation = o$7ects survive a gar$age collection, the+ remain at that generation onl+.
Thus, the ne)er o$7ects (local varia$les# are removed Juickl+ and older o$7ects (application level
varia$les# are assumed to $e still in use.
This is ho), the 1 is a$le to Juickl+ free heap space using the generation as a $aseline.
=.@@ T2e System.EC Ty!e
R.V.COLLEGE OF ENGINEERING Page =B=
' B , . 0 1
' B .
Gen @
Gen -
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
The programmer can interact )ith the gar$age collector using a $ase class $ystem.;C. This class
provides follo)ing mem$ers6
S+stem.1 Member Meaning
ollect(# 0orces the 1 to perform a gar$age collection.
1et1eneration(# "eturns the generation to )hich an o$7ect currentl+
$elongs.
1etTotalMemor+(# "eturns the estimated amount of memor+ (in $+tes#
currentl+ allocated on the managed heap. The Boolean
parameter specifies )hether the call should )ait for
gar$age collection to occur $efore returning.
Ma/1eneration "eturns the ma/imum of generations supported on the
target s+stem. Under Microsoft9s .N.T =.G, there are
three possi$le generations (G, 1, and =#.
Suppress0inali8e(# Sets a flag indicating that the specified o$7ect should not
have its 0inali8e(# method called.
%ait0orPending0inali8ers(# Suspends the current thread until all finali8a$le o$7ects
have $een finali8ed. This method is t+picall+ called
directl+ after invoking 1.ollect(#.
,uilding *inali<ation and 1is!osable Ty!es
onsider an e/ample to illustrate ho) to interact )ith .N.T gar$age collector.
using S+stemO
R.V.COLLEGE OF ENGINEERING Page =B@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
class ar6*,isposa$le
M
string nameO
pu$lic ar(string n#
M
nameQnO
N
car(#
M
onsole.%rite!ine(R%ithin destructor of MGNR, name#O
N
pu$lic void ,ispose(#
M
onsole.%rite!ine(R%ithin ,ispose(# of MGNR, name#O
1.Suppress0inali8e(this#O
N
N
class Test
M
pu$lic static void Main(#
M
R.V.COLLEGE OF ENGINEERING Page =BA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
ar c1Qne) ar(R(neR#O
ar c=Qne) ar(RT)oR#O
ar c@Qne) ar(RThreeR#O
ar cAQne) ar(R0ourR#O
c1.,ispose(#O
c@.,ispose(#O
N
N
Out!ut:
%ithin ,ispose(# of (ne
%ithin ,ispose(# of Three
%ithin destructor of 0our
%ithin destructor of T)o
%e have discussed earlier that $oth ,ispose(# and 0inali8e(# (or destructor# methods are used to release
the unmanaged resources. 's )e can see in the a$ove e/ample, )hen ,ispose(# method is invoked
through an o$7ect, )e can prevent the !" from calling the corresponding destructor )ith the help of
Suppress0inali8e(# method of 1 class. B+ manuall+ calling ,ispose(# method, )e are releasing the
resources and hence there is no need to call finali8er.
alling the ,ispose(# function manuall+ is termed as explicit ob&ect de-allocation and making use of
finali8er is kno)n as implicit ob&ect de-allocation.
R.V.COLLEGE OF ENGINEERING Page =BB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
*orcing Earbage Collection
%e kno) that, !" )ill automaticall+ trigger a gar$age collection )hen a managed heap is full. %e, the
programmers, )ill not $e kno)ing, )hen this process )ill happen. ;o)ever, if )e )ish, )e can force the
gar$age collection to occur using the follo)ing statements6
1.ollect(#O
1.%ait0orPending0inali8ers(#O
The method (aitor5endinginali$ers,- )ill allo) all finali8a$le o$7ects to perform an+ necessar+
cleanup $efore getting destro+ed. Though, )e can force gar$age collection to occur, it is not a good
programming practice.
nteracting 0it2 Eenerations
*t is possi$le to find generation of ever+ o$7ect at an+ moment of time in the program.
class ar6*,isposa$le
M
string nameO
pu$lic ar(string n#
M
nameQnO
N
R.V.COLLEGE OF ENGINEERING Page =BC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
car(#
M
onsole.%rite!ine(R%ithin destructor of MGNR, name#O
N
pu$lic void ,ispose(#
M
onsole.%rite!ine(R%ithin ,ispose(# of MGNR, name#O
1.Suppress0inali8e(this#O
N
N
class Test
M
pu$lic static void Main(#
M
ar c1Qne) ar(R(neR#O
ar c=Qne) ar(RT)oR#O
ar c@Qne) ar(RThreeR#O
ar cAQne) ar(R0ourR#O
onsole.%rite!ine(Rc1 is 1en MGNR, 1.1et1eneration(c1##O
onsole.%rite!ine(Rc= is 1en MGNR, 1.1et1eneration(c=##O
onsole.%rite!ine(Rc@ is 1en MGNR, 1.1et1eneration(c@##O
onsole.%rite!ine(RcA is 1en MGNR, 1.1et1eneration(cA##O
R.V.COLLEGE OF ENGINEERING Page =BD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
c1.,ispose(#O
c@.,ispose(#O
1.ollect(G#O
onsole.%rite!ine(Rc1 is 1en MGNR, 1.1et1eneration(c1##O
onsole.%rite!ine(Rc= is 1en MGNR, 1.1et1eneration(c=##O
onsole.%rite!ine(Rc@ is 1en MGNR, 1.1et1eneration(c@##O
onsole.%rite!ine(RcA is 1en MGNR, 1.1et1eneration(cA##O N
N
Out!ut 0ould be U
1 is 1en G
= is 1en G
@ is 1en G
A is 1en G
%ithin ,ispose(# of (ne
%ithin ,ispose(# of Three
1 is 1en 1
= is 1en 1
@ is 1en 1
A is 1en 1
%ithin ,estructor of 0our
%ithin ,estructor of T)o
Notice that )hen +ou reJuest a collection of generation G, each o$7ect is promoted to generation 1, given
that these o$7ects did not need to $e removed from memor+ (as the heap )as not e/hausted#. 'lso note
R.V.COLLEGE OF ENGINEERING Page =BE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
that if +ou reJuest a collection of generation = o$7ects, the o$7ect that have survived the current gar$age
collection remain at generation =.
=.@A Summary
*n this unit, )e have e/posed to various aspects of o$7ect lifetime. 1iven hat the !" makes use of
runtime gar$age collections, the $asic rule of thum$ is to assume that the runtime )ill destro+ as o$7ect
)hen it is no longer needed. ;o)ever, if +our & t+pes make use of unmanaged resources that need to $e
freed in a timel+ and predicta$le manner, +ou are free to override the virtual S+stem.($7ect.0inali8e(#
method and?or implement the *,isposa$le interface. 0inall+, +ou )ere e/posed to $e role of the
S+stem.1 t+pe and checked out a su$set of its functionalit+.
=.@B :ey0ords
Managed ;eap
andidate for gar$age collection
newob/ *nstruction
Ne) ($7ect Pointer
'pplication "oots
($7ect 1raph
Unmanaged resources
'pplication ,omain ('pp,omain#
0inali8a$le and 0inali8ation Zueue
04reacha$le ta$le
0inali8e(# method
*,isposa$le *nterface
The ne) format of using ke+)ord
1eneration
R.V.COLLEGE OF ENGINEERING Page =BF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
The S+stem.1 class and its mem$ers
./plicit and implicit o$7ect de4allocation
=.@C E;ercises
1A. ;o) does .N.T frame)ork manage gar$age collectionP ./plain using *,isposa$le interface.
1B. ./plain ho) gar$age collection is optimi8ed in .N.TP
1C. %hat are the rules of gar$age collectionP
1D. ,efine root and e/plain the role of application roots in gar$age collection.
1E. ./plain the concept of o$7ect graph )ith an e/ample.
1F. %hat is f4reacha$le ta$leP ./plain.
=G. Briefl+ e/plain the use of using ke+)ord )ith respect to gar$age collection.
=1. ./plain the concept of generations.
==. %hen do +ou override the virtual S+stem.($7ect.0inali8e(# methodP ;o) to implement it using
destructorsP
Module &
Unit &
CONTENTS:
1.AC ($7ectives
@.= *ntroduction
@.@ ,efining *nterfaces Using &
@.A *nvoking *nterface Mem$ers at the o$7ect level
R.V.COLLEGE OF ENGINEERING Page =CG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
@.B ./ercising the shapes hierarch+
@.C Understanding ./plicit *nterface *mplementation
@.D *nterfaces as Pol+morphic 'gents
@.E Building *nterface ;ierarchies
@.F Summar+
@.1G :e+)ords
@.11 ./ercises
@.1 Objectives
't the end of this lesson, the students )ill understand the follo)ing tasks in detail6
Meaning of interface
%riting user4defined?custom interface
,efining methods of interface )ithin the implemented classes
($taining interface references using three different )a+s
Passing interfaces as parameters to methods
./plicit interface implementation
*nterfaces as pol+morphic agents
Building interfaces hierarchies
*nterfaces )ith multiple $ase interfaces
@.=A ntroduction
This unit introduces the topic of interface4$ased programming. ;ere, +ou learn ho) to use & to define
and implement custom interfaces, and come to understand the $enefits of $uilding t+pes that support
multiple $ehaviors. 'long the )a+, a num$er of related topics are also discussed such as o$taining
interface references, e/plicit interface implementation and the construction of interface hierarchies.
R.V.COLLEGE OF ENGINEERING Page =C1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
@.=B 1e"ining nter"aces using C7
'n interface is nothing more than a named collection of semanticall+ related abstract members. The
specific mem$ers defined $+ an interface depend on the e/act be)avior it is modeling. 'n interface
e/presses a $ehavior that a given class or structure ma+ choose to support. 't a s+ntactic level, an
interface is defined using the & interace ke+)ord. Unlike other .N.T t+pes, interfaces never specif+ a
$ase class (not even S+stem.($7ect# and contain mem$ers that do not take an access modifier (as all
interface mem$ers are implicitl+ pu$lic#. 0ollo)ing is an e/ample sho)ing a custom interface defined in
&6
$$ T2is inter"ace de"ines t2e be2avior o" V2aving !oints.V
pu$lic interface *Point+
M
$$ m!licitly !ublic and abstract.
$+te 1etNum$er(fPoints(#O
N
's +ou can see, the *Point+ interface defines a single method. ;o)ever, .N.T interface t+pes are also
a$le to define an+ num$er of properties. 0or e/ample, +ou could create the *Point+ interface to use a read4
onl+ propert+ rather than a traditional accessor method6
$$ T2e !ointy be2avior as a read8only !ro!erty.
pu$lic interface *Point+
M
$+te Points M getO N
N
R.V.COLLEGE OF ENGINEERING Page =C=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
,o understand that interface t+pes are Juite useless on their o)n, as the+ are nothing more than a named
collection of a$stract mem$ers. 1iven this, +ou cannot allocate interface t+pes as +ou )ould a class or
structure6
$$ (c3> llegal to Vne0V inter"ace ty!es.
static void Main(stringVW args#
M
*Point+ p Q ne) *Point+(#O ?? ompiler errorL
N
*nterfaces do not $ring much to the ta$le until the+ are implemented $+ a class or structure. ;ere, *Point+
is an interface that e/presses the $ehavior of 3having points.5 's +ou can tell, this $ehavior might $e
useful in the shapes hierarch+ developed in Unit A of Module =. The idea is simple6 Some classes in the
Shapes hierarch+ have points (such as the ;e/agon#, )hile others (such as the ircle# do not. *f +ou
configure ;e/agon and Triangle to implement the *Point+ interface, +ou can safel+ assume that each class
no) supports a common $ehavior, and therefore a common set of mem$ers.
m!lementing an nter"ace using C7
%hen a class (or structure# chooses to e/tend its functionalit+ $+ supporting interface t+pes, it does so
using a comma4delimited list in the t+pe definition. Be a)are that the direct $ase class must $e the first
item listed after the colon operator. %hen +our class t+pe derives directl+ from S+stem.($7ect, +ou are
free to simpl+ list the interface(s# supported $+ the class, as the & compiler )ill e/tend +our t+pes from
S+stem.($7ect if +ou do not sa+ other)ise. (n a related note, given that structures al)a+s derive from
S+stem.2alueT+pe, simpl+ list each interface directl+ after the structure definition. onsider the
follo)ing e/amples6
$$ T2is class derives "rom System.Object and im!lements single inter"ace.
pu$lic class Somelass 6 *Some*nterface
M...N
R.V.COLLEGE OF ENGINEERING Page =C@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
$$Class derives "rom custom base class and im!lements a single inter"ace.
pu$lic class 'notherlass 6 M+Baselass, *Some*nterface
M...N
$$ T2is struct derives "rom System.+alueTy!e and im!lements t0o $$inter"aces.
pu$lic struct SomeStruct 6 *Some*nterface, *Point+
M...N
Understand that implementing an interface is an all4or4nothing proposition. That is, one has to define all
the mem$ers of interface in an implemented class. %e can not selectivel+ choose )hich mem$ers it )ill
implement. 1iven that the *Point+ interface defines a single propert+, this is not too much of a $urden.
;o)ever, if +ou are implementing an interface that defines ten mem$ers, the t+pe is no) responsi$le for
fleshing out the details of all the ten a$stract entities. ;ere is the implementation of the updated shapes
hierarch+ (note the ne) Triangle class t+pe#6
$$ Qe;agon no0 im!lements Pointy.
pu$lic class ;e/agon 6 Shape, Pointy
M
pu$lic ;e/agon(#M N
pu$lic ;e/agon(string name# 6 $ase(name#M N
pu$lic override void ,ra)(#
M
onsole.%rite!ine(R,ra)ing MGN the ;e/agonR, PetName#O
R.V.COLLEGE OF ENGINEERING Page =CA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
$$ Pointy m!lementation.
pu$lic $+te Points
M
get M return CO N
N
N
$$ Ne0 S2a!e derived class named Triangle.
pu$lic class Triangle 6 Shape, Pointy
M
pu$lic Triangle(# M N
pu$lic Triangle(string name# 6 $ase(name# M N
pu$lic override void ,ra)(#
M
onsole.%rite!ine(R,ra)ing MGN the TriangleR, PetName#O
N
$$ Pointy m!lementation.
pu$lic $+te Points
M
get M return @O N
N
N
R.V.COLLEGE OF ENGINEERING Page =CB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
.ach class no) returns its num$er of points to the caller )hen asked to do so. 0ollo)ing figure illustrates
*Point+4compati$le classes.

Contrasting nter"aces to (bstract ,ase Classes
B+ understanding a$stract classes earlier, and interfaces no), a Juestion ma+ arise6 )hat is the need of
interface t+pesP 'fter all, & alread+ allo)s +ou to $uild a$stract class t+pes containing a$stract methods.
!ike an interface, )hen a class derives from an a$stract $ase class, it is also under o$ligation to define the
a$stract methods (provided the derived class is not declared a$stract as )ell#. ;o)ever, a$stract $ase
classes do far more than define a group of a$stract methods. The+ are free to define pu$lic, private, and
protected state data, as )ell as an+ num$er of concrete methods that can $e accessed $+ the su$classes.
*nterfaces, on the other hand, are pure protocol. *nterfaces never define state data and never provide an
implementation of the methods (if +ou tr+, +ou receive a compile4time error#6
R.V.COLLEGE OF ENGINEERING Page =CC
($7ect
Triangle
Shape
ircle
;e/agon
*Point+
*Point+
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic interface *'m'Bad*nterface
M
$$ Error? inter"aces can=t de"ine data>
int m+*nt Q GO
$$ Error? only abstract members allo0ed>
void M+Method(#
M
onsole.%rite!ine(R;iLR#O
N
N
*nterface t+pes are also Juite helpful given that & (and .N.T4a)are languages in general# onl+ support
single inheritanceO the interface4$ased protocol allo)s a given t+pe to support numerous $ehaviors, )hile
avoiding the issues that arise )hen deriving from e/tending multiple $ase classes. Most importantl+,
interface4$ased programming provides +et another )a+ to in7ect pol+morphic $ehavior into a s+stem. *f
multiple classes (or structures# implement the same interface in their uniJue )a+s, +ou have the po)er to
treat each t+pe in the same manner. 's +ou )ill see a $it later in this chapter, interfaces are e/tremel+
pol+morphic, given that t+pes that are not related via classical inheritance can support identical $ehaviors.
@.=C nvo3ing nter"ace Members at t2e Object #evel
(nce the methods declared in interfaces are defined )ithin the implemented class, one can invoke that
method using the o$7ect of the class. 0or e/ample6
pu$lic static void Main(stringVW args#
M
$$ Call ne0 Points member de"ined by Pointy
R.V.COLLEGE OF ENGINEERING Page =CD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
;e/agon he/ Q ne) ;e/agon(#O
onsole.%rite!ine(RPoints6 MGNR, he/.Points#O
N
This approach )orks fine in this particular case, given that +ou are )ell a)are that the ;e/agon t+pe has
implemented the interface in Juestion. (ther times, ho)ever, +ou )ill not $e a$le to determine at compile
time )hich interfaces are supported $+ a given t+pe. 0or e/ample, assume +ou have an arra+ containing
BG Shape4compati$le t+pes, onl+ some of )hich support *Point+. ($viousl+, if +ou attempt to invoke the
Points propert+ on a t+pe that has not implemented *Point+, +ou receive a compile4time error. Ne/t
Juestion6 ;o) can )e d+namicall+ determine the set of interfaces supported $+ a t+peP This Juestion can
$e ans)ered in three different )a+s as discussed in su$seJuent sections.
Obtaining nter"ace 4e"erences: E;!licit Casting
The first )a+ +ou can determine at runtime if a t+pe supports a specific interface is to make use of an
e/plicit cast. *f the t+pe does not support the reJuested interface, +ou receive an *nvalidast./ception. To
handle this, make use of structured e/ception handling, for e/ample6
pu$lic static void Main(stringVW args#
M
......
$$ Catc2 a !ossible nvalidCastE;ce!tion
ircle c Q ne) ircle(R!isaR#O
*Point+ iptO
tr+
M
ipt Q (*Point+#cO $$bo;ing or e;!licit casting
R.V.COLLEGE OF ENGINEERING Page =CE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsole.%rite!ine(ipt.Points#O
N
catch (*nvalidast./ception e#
M
onsole.%rite!ine(e.Message#O
N
N
%hile +ou could make use of tr+?catch logic and hope for the $est, it )ould $e ideal to determine )hich
interfaces are supported $efore invoking the interface mem$ers in the first place. So, let9s see the
remaining t)o )a+s of doing so.
Obtaining nter"ace 4e"erences: T2e as :ey0ord
The second )a+ +ou can determine )hether a given t+pe supports an interface is to make use of the as
ke+)ord, )hich )as first introduced in hapter A. *f the o$7ect can $e treated as the specified interface,
+ou are returned a reference to the interface in Juestion. *f not, +ou receive a null reference6
pu$lic static void Main(stringVW args#
M
...
$$ Can 0e treat 2e;' as PointyH
;e/agon h Q ne) ;e/agon(R"amR#O
*Point+ ipt Q h as *Point+O
if(ipt LQ null#
onsole.%rite!ine(RPoints6 MGNR, ipt.Points#O
else
R.V.COLLEGE OF ENGINEERING Page =CF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsole.%rite!ine(R((PSL Not point+...R#O
N
Notice that )hen +ou make use of the as ke+)ord, +ou have no need to make use of tr+?catch logic,
given that if the reference is not null, +ou kno) +ou are calling on a valid interface reference.
Obtaining nter"ace 4e"erences: T2e is :ey0ord
0inall+, +ou ma+ also o$tain an interface from an o$7ect using the is ke+)ord. *f the o$7ect in Juestion is
not *Point+ compati$le, the condition fails. 0or e/ample,
??third )a+ to test for an interface
Triangle t Q ne) Triangle(#O
if(t is *Point+#
onsole.%rite!ine(t.Points#O
else
onsole.%rite!ine(3((PSL Not point+...R#O
@.=D E;ercising t2e S2a!es Qierarc2y
*n these previous e/amples, +ou could have avoided checking the outcome of asking for the *Point+
reference, given that +ou kne) ahead of time )hich shapes )ere *Point+ compati$le. ;o)ever, )hat if
+ou )ere to create an arra+ of generic Shape references, each of )hich has $een assigned to a given
su$classP -ou ma+ make use of an+ of the previous techniJues to discover at runtime )hich items in the
arra+ support this $ehavior. 0or e/ample,
R.V.COLLEGE OF ENGINEERING Page =DG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic static void Main(stringVW args#
M
...
ShapeV W s Q M ne) ;e/agon(#, ne) ircle(#, ne) Triangle(R"amR#, ne)
ircle(RShamR#N O
for(int i Q GO i X s.!engthO iHH#
M
$$ 4ecall t2e S2a!e base class de"ines an abstract 1ra056
$$ member? so all s2a!es 3no0 2o0 to dra0 t2emselves.
sViW.,ra)(#O
if(sViW is *Point+#
onsole.%rite!ine(RPoints6 MGN R, ((*Point+#sViW#.Points#O
else
onsole.%rite!ine(RMGN is not a point+LR, sViW.PetName#O
N
N
nter"aces (s Parameters
1iven that interfaces are valid .N.T t+pes, +ou ma+ construct methods that take interfaces as parameters.
To illustrate, assume +ou have defined another interface named *,ra)@,6
$$ Models t2e ability to render a ty!e in stunning &1.
pu$lic interface *,ra)@,
R.V.COLLEGE OF ENGINEERING Page =D1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
void ,ra)@,(#O
N
Ne/t, assume that t)o of +our three shapes (ircle and ;e/agon# have $een configured to support this
ne) $ehavior6
$$ Circle su!!orts 1ra0&1
pu$lic class ircle 6 Shape, 1ra0&1
M
...
pu$lic void ,ra)@,(#
M
onsole.%rite!ine(R,ra)ing ircle in @,LR#O
N
N
$$ Qe;agon su!!orts Pointy and 1ra0&1
pu$lic class ;e/agon 6 Shape, *Point+, 1ra0&1
M
...
pu$lic void ,ra)@,(#
M
onsole.%rite!ine(R,ra)ing ;e/agon in @,LR#O
N
R.V.COLLEGE OF ENGINEERING Page =D=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
*f +ou no) define a method taking an *,ra)@, interface as a parameter, +ou are a$le to effectivel+ send
in any o$7ect implementing *,ra)@, (if +ou attempt to pass in a t+pe not supporting the necessar+
interface, +ou receive a compile4time error#. onsider the follo)ing6
$$ Ma3e some s2a!es. " t2ey can be rendered in &1? do it>
pu$lic class Program
M
$$ =ll dra0 anyone su!!orting 1ra0&1.
pu$lic static void ,ra)*n@,(*,ra)@, itf@d#
M
onsole.%rite!ine(R,ra)ing *,ra)@, compati$le t+peR#O
itf@d.,ra)@,(#O
N
static void Main(#
M
ShapeV W s Q M ne) ;e/agon(#, ne) ircle(#, ne) Triangle(#NO
for(int i Q GO i X s.!engthO iHH#
M
]..
if(sViW is *,ra)@,#
,ra)*n@,((*,ra)@,#sViW#O
N
R.V.COLLEGE OF ENGINEERING Page =D@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
N
Notice that the triangle is never dra)n, as it is not *,ra)@,4compati$le
@.=E Understanding E;!licit nter"ace m!lementation
*n our current definition of *,ra)@,, )e )ere forced to name its sole method ,ra)@,(# in order to avoid
clashing )ith the a$stract ,ra)(# method defined in the Shape $ase class. %hile there is nothing horri$l+
)rong )ith this interface definition, a more natural method name )ould simpl+ $e ,ra)(#6
$$ 4e8"actor met2od name "rom V1ra0&1V to V1ra0V.
pu$lic interface *,ra)@,
M
void 1ra0(#O
N
*f )e )ere to make such a change, this )ould reJuire us to also update our implementation of
,ra)*n@,(#.
pu$lic static void ,ra)*n@,(*,ra)@, itf@d#
M
onsole.%rite!ine(R,ra)ing *,ra)@, compati$le t+peR#O
itf@d.1ra0(#O
N
R.V.COLLEGE OF ENGINEERING Page =DA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
No), assume +ou have defined a ne) class named Line that derives from the a$stract S)ape class and
implements *,ra)@, ($oth of )hich no) define an identicall+ named a$stract ,ra)(# method#6
pu$lic class !ine 6 S2a!e? 1ra0&1
M
pu$lic override void ,ra)(#
M
onsole.%rite!ine(R,ra)ing a line...R#O
N
N
The !ine class compiles )ithout a hitch. But consider the follo)ing Main(# logic6
static void Main(stringVW args#
M
...
$$ Calls 1ra056.
!ine m+!ine Q ne) !ine(#O
m+!ine.,ra)(#O
$$ Calls same im!lementation o" 1ra056>
*,ra)@, itf,ra)@dQ (*,ra)@,# m+!ineO
itf,ra)@d.,ra)(#O
N
R.V.COLLEGE OF ENGINEERING Page =DB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1iven )hat +ou alread+ kno) a$out the Shape $ase class and *,ra)@, interface, it looks as if +ou have
called two variations of the ,ra)(# method (one from the o$7ect level, the other from an interface
reference#. Nevertheless, the compiler is happ+ to call the same implementation from an interface or
o$7ect reference, given that the Shape a$stract $ase class and *,ra)@, interface have an identicall+
named mem$er. This )ould $e pro$lematic if +ou )ould like to have the *,ra)@,.,ra)(# method to
dra) a @, shape, )hile the overridden Shape.,ra)(# method dra)s a =,. No) consider a related
pro$lem. %hat if +ou )ish to ensure that the methods defined $+ a given interface are onl+ accessi$le
from an interface reference rather than an o$7ect referenceP urrentl+, the mem$ers defined $+ the
*Point+ interface can $e accessed using either an o$7ect reference or an *Point+ reference. The ans)er to
$oth Juestions comes $+ )a+ of e'plicit interface implementation. Using this techniJue, +ou are a$le to
ensure that the o$7ect user can onl+ access methods defined $+ a given interface using the correct
interface reference, as )ell as circumvent possi$le name clashes. To illustrate, here is the updated !ine
class (assume +ou have updated ;e/agon and ircle in a similar manner#6
$$ Using e;!licit met2od im!lementation 0e are able to !rovide distinct $$1ra056 im!lementations.
pu$lic class !ine 6 Shape, *,ra)@,
M
$$ t2is met2od can be called "rom an 1ra0&1 inter"ace re"erence.
void *,ra)@,.,ra)(#
M
onsole.%rite!ine(R,ra)ing a @, line...R#O
N
$$ Aou can only call t2is at t2e object level.
pu$lic override void ,ra)(#
M
onsole.%rite!ine(R,ra)ing a line...R#O
N
R.V.COLLEGE OF ENGINEERING Page =DC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
's +ou can see, )hen e/plicitl+ implementing an interface mem$er, the general pattern $reaks do)n to
returnDalue InterfaceName.!et)odName(args#. There are a fe) odds and ends to $e a)are of )hen using
e/plicit interface implementation. 0irst and foremost, +ou cannot define the e/plicitl+ implemented
mem$ers )ith an access modifier. 0or e/ample, the follo)ing is illegal s+nta/6
pu$lic class !ine 6 Shape, *,ra)@,
M
!ublic void *,ra)@,.,ra)(# $$ Error>
M
onsole.%rite!ine(R,ra)ing a @, line...R#O
N
...
N
This should make sense. The )hole reason to use e/plicit interface method implementation is to ensure
that a given interface method is $ound at the interface level. *f +ou )ere to add the pu$lic ke+)ord, this
)ould suggest that the method is a mem$er of the pu$lic sector of the class, )hichdefeats the pointL
1iven this design, the caller is onl+ a$le to invoke the ,ra)(# method defined $+ the Shape $ase class
from the o$7ect level6
$$ T2is invo3es t2e overridden S2a!e.1ra056 met2od.
!ine m+!ine Q ne) !ine(#O
m+!ine.,ra)(#O
R.V.COLLEGE OF ENGINEERING Page =DD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
To invoke the ,ra)(# method defined $+ *,ra)@,, )e must no) e/plicitl+ o$tain the interface reference
using an+ of the techniJues sho)n previousl+. 0or e/ample6
$$ T2is triggers t2e 1ra0&1.1ra056 met2od.
!ine m+!ine Q ne) !ine(#O
*,ra)@, i@d Q (*,ra)@,#m+!ineO
i@d.,ra)(#O
@.=F nter"aces as Polymor!2ic (gents
's +ou kno), an a$stract $ase class containing a$stract mem$ers allo)s us to define a specific $ehavior
that is common across all mem$ers in the same class hierarch+. To understand the usefulness of
interfaces, assume that the 1etNum$er(0Points(# method )as not defined $+ *Point+, $ut rather as an
a$stract mem$er of the Shape class. if this )ere the case, ;e/agon and Triangle )ould still $e a$le to
return the correct result. 't the same time, ircle )ould also $e o$ligated to contend )ith the
1etNum$er(fPoints(# method as )ell. *n this case, ho)ever, it might seem a $it inelegant to simpl+
return G.
The pro$lem )ith defining 1etNum$er(0Points(# in the Shape $ase class is that all derived t+pes must
contend )ith this mem$er, regardless of the semantics. Thus, the first ke+ point a$out interfaces is the
fact that +ou can select )hich mem$ers in the hierarch+ support custom $ehaviors. 'lso understand that
the same interface can $e implemented $+ numerous t+pes, even if the+ are not )ithin the same class
hierarch+ in the first place.
@.@G ,uilding nter"ace Qierarc2ies
To continue our investigation of creating custom interfaces, let9s e/amine the topic of interface
)ierarc)ies. Iust as a class can serve as a $ase class to other classes ()hich can in turn function as $ase
classes to +et another class#, it is possi$le to $uild inheritance relationships among interfaces. 's +ou
R.V.COLLEGE OF ENGINEERING Page =DE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
might e/pect, the topmost interface defines a general $ehavior, )hile the most derived interface defines
more specific $ehaviors. To illustrate, ponder the follo)ing interface hierarch+6
$$ T2e base inter"ace.
pu$lic interface *,ra)a$le
M
void ,ra)(#O
N
pu$lic interface *Printa$le 6 1ra0able
M
void Print(#O
N
pu$lic interface *Meta0ile"ender 6 Printable
M
void "ender(#O
N
No), if a class )ished to support each $ehavior e/pressed in this interface hierarch+, it )ould derive
from the nt)-most interface (*Meta0ile"ender in this case#. 'n+ methods defined $+ the $ase interface(s#
are automaticall+ carried into the definition. 0or e/ample6
$$ T2is class su!!orts 1ra0able? Printable? and Meta*ile4ender.
pu$lic class Super*mage 6 *Meta0ile"ender
M
R.V.COLLEGE OF ENGINEERING Page =DF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic void ,ra)(#
M
onsole.%rite!ine(RBasic dra)ing logic.R#O
N
pu$lic void Print(#
M
onsole.%rite!ine(R,ra) to printer.R#O
N
pu$lic void "ender(#
M
onsole.%rite!ine(R"ender to metafile.R#O
N
N
;ere is some sample usage of e/ercising each interface from a Super*mage instance6
$$ E;ercise t2e inter"aces.
static void Main(stringVW args#
M
Super*mage si Q ne) Super*mage(#O
$$ Eet 1ra0able.
*,ra)a$le itf,ra) Q (*,ra)a$le#siO
itf,ra).,ra)(#O
R.V.COLLEGE OF ENGINEERING Page =EG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
$$ No0 get meta*ile4ender? 02ic2 e;!oses all met2ods u!
$$ t2e c2ain o" in2eritance.
if (itf,ra) is *Meta0ile"ender#
M
*Meta0ile"ender itfM0 Q (*Meta0ile"ender#itf,ra)O
itfM0."ender(#O
itfM0.Print(#O
N
N
nter"aces 0it2 Multi!le ,ase nter"aces
's +ou $uild interface hierarchies, $e a)are that it is completel+ permissi$le to create an interface that
derives from multiple $ase interfaces. "ecall, ho)ever, that it is not permissi$le to $uild a class that
derives from multiple $ase classes. To illustrate, assume +ou are $uilding a ne) set of interfaces that
model the automo$ile $ehaviors for a particular .nglish agent6
pu$lic interface *ar
M
void ,rive(#O
N
pu$lic interface *Under)aterar
M
void ,ive(#O
N
R.V.COLLEGE OF ENGINEERING Page =E1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
$$ Qere 0e 2ave an inter"ace 0it2 T%O base inter"aces.
pu$lic interface *IamesBondar 6 Car? Under0aterCar
M
void Tur$oBoost(#O
N
*f +ou )ere to $uild a class that implements *IamesBondar, +ou )ould no) $e responsi$le for
implementing Tur$oBoost(#, ,ive(#, and ,rive(#6
pu$lic class IamesBondar 6 *IamesBondar
M
pu$lic void ,rive(#
M
onsole.%rite!ine(RSpeeding up...R#O
N
pu$lic void ,ive(#
M
onsole.%rite!ine(RSu$merging...R#O
N
pu$lic void Tur$oBoost(#
M
onsole.%rite!ine(RBlast offLR#O
N
N
This speciali8ed automo$ile can no) $e manipulated as +ou )ould e/pect6
R.V.COLLEGE OF ENGINEERING Page =E=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
static void Main(stringVW args#
M
...
IamesBondar 7 Q ne) IamesBondar(#O
7.,rive(#O
7.Tur$oBoost(#O
7.,ive(#O
N
@.@1 Summary
*nterface is a collection of a$stract mem$ers that ma+ $e implemented $+ a given class. Because an
interface does not suppl+ an+ implantation details, it is common to regard an interface as a $ehavior that
ma+ $e supported $+ a given t+pe. %hen to or more classes implement the same interface, +ou are a$le to
treat each t+pe in the same )a+. This is kno)n an interface4$ased pol+morphism. & provides the
ke+)ord interface to allo) +ou to define a ne) interface. ' t+pe can support as man+ interfaces as
necessar+ using comma4delimited list. 0urthermore, it is permissi$le to $uild interfaces that derive from
multiple $ase interfaces.
@.@= :ey0ords
*nterfaces
'$stract lass
'$stract Mem$ers
The ke+)ord is and as
Pol+morphism
R.V.COLLEGE OF ENGINEERING Page =E@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
@.@@ E;ercises
1G. ,efine an interface. Bring out the differences $et)een interface and a$stract $ase classes.
11. ;o) do +ou implement an interfaceP ./plain )ith an e/ample.
1=. ./plain different techniJues for invoking interface mem$ers at the o$7ect level.
1@. ;o) do +ou pass interface as parameter to a methodP ./plain )ith an e/ample.
1A. ./plain the concept of interface4$ased pol+morphism.

Module &
Unit 9
CONTENTS:
1.AD ($7ectives
A.= *ntroduction
A.@ Understanding the *onverti$le *nterface
A.A Building a ustom .numerator (*.nummera$le and .numerator#
A.B Building lonea$le o$7ects (*lonea$le#
A.C Building ompara$le ($7ects (*ompara$le#
A.D ./ploring the S+stem.ollections Namespace
A.E Summar+
A.F :e+)ords
A.1G ./ercises
R.V.COLLEGE OF ENGINEERING Page =EA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
C.1 Objectives
't the end of this lesson, the students )ill understand6
The mem$ers and implementation of in$uilt interfaces like *onverti$le, *.numera$le,
.numerator, *lonea$le and *ompara$le
The mem$ers of S+stem.ollections Namespace and their implementation $+ the classes.
A.=B ntroduction
The previous unit ela$orated a$out the custom interfaces. ;ere, )e )ill e/amine some of the standard
interfaces defined )ithin the .N.T $ase class li$raries. 's )e are going to see, the custom t+pes are free
to implement these predefined interfaces to support a num$er of advanced $ehaviors such as o$7ect
cloning, o$7ect enumeration and o$7ect sorting. To )rap things up, )e )ill check out the numerous
predefined interfaces that are implemented $+ various collection classes ('rra+!ist, Stack etc.# defined $+
S+stem.ollections namespace.
A.=C Understanding t2e Convertible nter"ace
The *onverti$le t+pe allo)s the programmer to d+namicall+ convert $et)een data t+pes using interface4
$ased programming techniJues. Using this interface, one can cast $et)een t+pes using language4agnostic
terms. %e kno) that a ma7orit+ of the intrinsic data t+pes of & ($ool, int, dou$le etc# are simpl+ aliases
to the structures in the S+stem namespaces. !ike an+ .N.T t+pe, each of these structures ma+ define an+
num$er of methods and ma+ optionall+ implement an+ num$er of predefined interfaces.
T2e Convertible.ToMMMM56 Members
The *onverti$le interface defines a num$er of methods of the form To>>>>(#, )hich provides a )a+ to
convert from one t+pe into another. But sometimes, conversion ma+ not $e possi$le. 0or e/ample,
R.V.COLLEGE OF ENGINEERING Page =EB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
converting from *nt@= to ,ou$le make sense, )hereas, there is no sense in converting Boolean into
,ateTime. *f the conversion is not supported, then the s+stem )ill thro) nvalidCastE;ce!tion.
Note that, all of the To>>>>(# methods take a parameter of t+pe *0ormatProvider. ($7ects that
implement this interface are a$le to format their contents $ased on culture4specific information. The
formal definition )ould $e<
pu$lic interface *0ormatProvider
M
o$7ect 1et0ormat(T+pe formatT+pe#O
N
*f )e are $uilding a custom t+pe that should $e formatted using various locals, then )e need to implement
*0ormatProvider.
Convertible.EetTy!eCode56
The 1etT+peode(# method of *onverti$le interface is availa$le to an+ class or structure )hich
implements *onverti$le. This method allo)s to programmaticall+ discover a value that represents the
t+pe code of the t+pe, )hich is represented $+ the follo)ing enumeration6
pu$lic enum T+peode
M
Boolean, B+te, har, ,ateTime, ,BNull, ,ecimal, ,ou$le, .mpt+, *nt1C, *nt@=, *ntCA,
($7ect, SB+te, Single, String, U*nt1C, U*nt@=, U*ntCA
N
R.V.COLLEGE OF ENGINEERING Page =EC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
T2e System.Convert Ty!e
To )rap up this overvie) of the *onverti$le t+pe, it is )orth pointing out that the S+stem namespace
defines a t+pe named onvert, )hich echoes the functionalit+ of the *onverti$le interface. The
S+stem.onvert does not directl+ implement *onverti$le, ho)ever, the same set of mem$ers are defined
on its default pu$lic interface.
A.=D ,uilding a Custom Enumerator 5Enumerable and
Enumerator6
;ere, )e )ill e/amine the role of *.numera$le and *.numerator. 'ssume +ou have developed a class
named 1arage that contains a set of individual ar t+pes stored )ithin a S+stem.'rra+6
$$ Earage contains a set o" Car objects.
pu$lic class 1arage
M
private arVW car'rra+O
$$ *ill 0it2 some Car objects u!on startu!.
pu$lic 1arage(#
M
car'rra+ Q ne) arVAWO
car'rra+VGW Q ne) ar(R"ust+R, @G#O
car'rra+V1W Q ne) ar(RlunkerR, BB#O
car'rra+V=W Q ne) ar(Rfipp+R, @G#O
car'rra+V@W Q ne) ar(R0redR, @G#O
N
N
R.V.COLLEGE OF ENGINEERING Page =ED
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
*deall+, it )ould $e convenient to iterate over the 1arage o$7ect9s su$4items using the & foreach
construct6
$$ T2is seems reasonable...
pu$lic class Program
M
static void Main(stringVW args#
M
1arage car!ot Q ne) 1arage(#O
foreach (ar c in car!ot#
M
onsole.%rite!ine(RMGN is going M1N MP;R, c.PetName,
c.urrSpeed#O
N
N
N
Sadl+, the compiler informs +ou that the 1arage class does not implement a method named
1et.numerator(#. This method is formali8ed $+ the *.numera$le interface, )hich is found lurking )ithin
the S+stem.ollections namespace. ($7ects that support this $ehavior advertise that the+ are a$le to
e/pose contained su$items to the caller6
$$ T2is inter"ace in"orms t2e caller t2at t2e object=s subitems can $$ be enumerated.
pu$lic interface *.numera$le
M
R.V.COLLEGE OF ENGINEERING Page =EE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
*.numerator 1et.numerator(#O
N
's +ou can see, the 1et.numerator(# method returns a reference to +et another interface named
S+stem.ollections.*.numerator. This interface provides the infrastructure to allo) the caller to traverse
the internal o$7ects contained $+ the *.numera$le4compati$le container6
$$ T2is inter"ace allo0s t2e caller to obtain a container=s subitems.
pu$lic interface *.numerator
M
$ool MoveNe/t (#O ?? 'dvance the internal position of the cursor.
o$7ect urrent M getON ?? 1et the current item (read4onl+ propert+#.
void "eset (#O ?? "eset the cursor $efore the first mem$er.
N
*f +ou )ish to update the 1arage t+pe to support these interfaces, +ou could take the long road and
implement each method manuall+. %hile +ou are certainl+ free to provide customi8ed versions of
1et.numerator(#, MoveNe/t(#, urrent, and "eset(#, there is a simpler )a+. 's the S+stem.'rra+ t+pe (as
)ell as man+ other t+pes# alread+ implements *.numera$le and *.numerator, +ou can simpl+ delegate the
reJuest to the S+stem.'rra+ as follo)s6
using S+stem.ollectionsO
...
pu$lic class 1arage 6 Enumerable
M
$$ System.(rray already im!lements Enumerator>
R.V.COLLEGE OF ENGINEERING Page =EF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
private arVW car'rra+O
pu$lic 1arage(#
M
car'rra+ Q ne) arVAWO
car'rra+VGW Q ne) ar(R0ee0eeR, =GG, G#O
car'rra+V1W Q ne) ar(RlunkerR, FG, G#O
car'rra+V=W Q ne) ar(Rfipp+R, @G, G#O
car'rra+V@W Q ne) ar(R0redR, @G, G#O
N
pu$lic *.numerator 1et.numerator(#
M
$$ 4eturn t2e array object=s Enumerator.
return car'rra+.1et.numerator(#O
N
N
(nce +ou have updated +our 1arage t+pe, +ou can no) safel+ use the t+pe )ithin the & foreach
construct. 0urthermore, given that the 1et.numerator(# method has $een defined pu$licl+, the o$7ect user
could also interact )ith the *.numerator t+pe6
$$ Manually 0or3 0it2 Enumerator.
*.numerator i Q car!ot.1et.numerator(#O
i.MoveNe/t(#O
ar m+ar Q (ar#i.urrentO
R.V.COLLEGE OF ENGINEERING Page =FG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsole.%rite!ine(RMGN is going M1N MP;R, m+ar.PetName,
m+ar.urrSpeed#O
*f +ou )ould prefer to hide the functionalit+ of *.numera$le from the o$7ect level, simpl+ make use of
e/plicit interface implementation6
pu$lic *.numerator *.numera$le.1et.numerator(#
M
$$ 4eturn t2e array object=s Enumerator.
return car'rra+.1et.numerator(#O
N
A.=E ,uilding Cloneable Objects 5Cloneable6
's +ou recall from earlier discussion, S+stem.($7ect defines a mem$er named Mem$er)iselone(#. This
method is used to o$tain a s)allow copy of the current o$7ect. ($7ect users do not call this method directl+
(as it is protected#O ho)ever, a given o$7ect ma+ call this method itself during the cloning process. To
illustrate, assume +ou have a class named Point6
$$ ( class named Point.
pu$lic class Point
M
$$ Public "or easy access.
pu$lic int /, +O
pu$lic Point(int /, int +# M this./ Q /O this.+ Q +ON
pu$lic Point(#MN
R.V.COLLEGE OF ENGINEERING Page =F1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
$$ Override Object.ToString56.
pu$lic override string ToString(#
M
return string.0ormat(R> Q MGNO - Q M1NR, /, + #O
N
N
1iven )hat +ou alread+ kno) a$out reference t+pes and value t+pes, +ou are a)are that if +ou assign one
reference varia$le to another, +ou have t)o references pointing to the same o$7ect in memor+. Thus, the
follo)ing assignment operation results in t)o references to the same Point o$7ect on the heapO
modifications using either reference affect the same o$7ect on the heap6
static void Main(stringVW args#
M
$$ T0o re"erences to same object>
Point p1 Q ne) Point(BG, BG#O
Point p= Q p1O
p=./ Q GO
onsole.%rite!ine(p1#O
onsole.%rite!ine(p=#O
N
%hen +ou )ish to eJuip +our custom t+pes to support the a$ilit+ to return an identical cop+ of itself to the
caller, +ou ma+ implement the standard *lonea$le interface. This t+pe defines a single method named
lone(#6
R.V.COLLEGE OF ENGINEERING Page =F=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic interface Cloneable
M
o$7ect lone(#O
N
($viousl+, the implementation of the lone(# method varies $et)een o$7ects. ;o)ever, the $asic
functionalit+ tends to $e the same6 op+ the values of +our mem$er varia$les into a ne) o$7ect instance,
and return it to the user. To illustrate, ponder the follo)ing update to the Point class6
$$ T2e Point no0 su!!orts Vclone8ability.V
pu$lic class Point 6 Cloneable
M
pu$lic int /, +O
pu$lic Point(#M N
pu$lic Point(int /, int +#
M
this./ Q /O this.+ Q +O
N
$$ 4eturn a co!y o" t2e current object.
pu$lic o$7ect lone(#
M
return ne) Point(this./, this.+#O
N
pu$lic override string ToString(#
M
R.V.COLLEGE OF ENGINEERING Page =F@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
return string.0ormat(R> Q MGNO - Q M1NR, /, + #O
N
N
*n this )a+, +ou can create e/act stand4alone copies of the Point t+pe, as illustrated $+ the follo)ing code6
static void Main(stringVW args#
M
$$ Notice Clone56 returns a generic object ty!e.
$$ Aou must !er"orm e;!licit cast to obtain t2e derived ty!e.
Point p@ Q ne) Point(1GG, 1GG#O
Point pA Q (Point#p@.lone(#O
$$ C2ange !9.; 502ic2 0ill not c2ange !&.;6.
pA./ Q GO
$$ Print eac2 object.
onsole.%rite!ine(p@#O
onsole.%rite!ine(pA#O
N
%hile the current implementation of Point fits the $ill, +ou can streamline things 7ust a $it. Because the
Point t+pe does not contain reference t+pe varia$les, +ou could simplif+ the implementation of the
lone(# method as follo)s6
pu$lic o$7ect lone(#
M
$$ Co!y eac2 "ield o" t2e Point member by member.
R.V.COLLEGE OF ENGINEERING Page =FA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
return this.Mem$er)iselone(#O
N
Be a)are, ho)ever, that if the Point did contain an+ reference t+pe mem$er varia$les,
Mem$er)iselone(# )ill cop+ the references to those o$7ects (aka a s)allow copy#. *f +ou )ish to support
a true deep cop+, +ou )ill need to create a ne) instance of an+ reference t+pe varia$les during the cloning
process. !et9s see an e/ample.
( More Elaborate Cloning E;am!le
No) assume the Point class contains a reference t+pe mem$er varia$le of t+pe Point,escription. This
class maintains a point9s friendl+ name as )ell as an identification num$er e/pressed as a S+stem.1uid
(1lo$all+ UniJue *dentifier V1U*,W is a statisticall+ uniJue 1=E4$it num$er#. ;ere is the implementation6
$$ T2is class describes a !oint.
pu$lic class Point,escription
M
$$ E;!osed !ublicly "or sim!licity.
pu$lic string petNameO
pu$lic 1uid point*,O
pu$lic Point,escription(#
M
this.petName Q RNo4nameRO
point*, Q 1uid.Ne)1uid(#O
N
N
R.V.COLLEGE OF ENGINEERING Page =FB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
The initial updates to the Point class itself included modif+ing ToString(# to account for these ne) $its of
state data, as )ell as defining and creating the Point,escription reference t+pe. To allo) the outside
)orld to esta$lish a pet name for the Point, +ou also update the arguments passed into the overloaded
constructor6
pu$lic class Point 6 *lonea$le
M
pu$lic int /, +O
pu$lic Point,escription desc Q ne) Point,escription(#O
pu$lic Point(#M N
pu$lic Point(int /, int +#
M
this./ Q /O this.+ Q +O
N
pu$lic Point(int /, int +, string petname#
M
this./ Q /O
this.+ Q +O
desc.petName Q petnameO
N
pu$lic o$7ect lone(#
M
return this.Mem$er)iselone(#O
N
pu$lic override string ToString(#
R.V.COLLEGE OF ENGINEERING Page =FC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
return string.0ormat(R> Q MGNO - Q M1NO Name Q M=NO[n *, Q
M@N[nR, /, +, desc.petName, desc.point*,#O
N
N
Notice that +ou did not +et update +our lone(# method. Therefore, )hen the o$7ect user asks for a clone
using the current implementation, a shallo) (mem$er4$+4mem$er# cop+ is achieved. To illustrate, assume
+ou have updated Main(# as follo)s6
static void Main(stringVW args#
M
onsole.%rite!ine(Rloned p@ and stored ne) Point in pAR#O
Point p@ Q ne) Point(1GG, 1GG, RIaneR#O
Point pA Q (Point#p@.lone(#O
onsole.%rite!ine(RBefore modification6R#O
onsole.%rite!ine(Rp@6 MGNR, p@#O
onsole.%rite!ine(RpA6 MGNR, pA#O
pA.desc.petName Q RMr. >RO
pA./ Q FO
onsole.%rite!ine(R[nhanged pA.desc.petName and pA./R#O
onsole.%rite!ine(R'fter modification6R#O
onsole.%rite!ine(Rp@6 MGNR, p@#O
onsole.%rite!ine(RpA6 MGNR, pA#O
N
R.V.COLLEGE OF ENGINEERING Page =FD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
*n order for +our lone(# method to make a complete deep cop+ of the internal reference t+pes, +ou need
to configure the o$7ect returned $+ Mem$er)iselone(# t o account for the current point9s name (the
S+stem.1uid t+pe is in fact a structure, so the numerical data is indeed copied#. ;ere is one possi$le
implementation6
$$ No0 0e need to adjust "or t2e Point1escri!tion member.
pu$lic o$7ect lone(#
M
Point ne)Point Q (Point#this.Mem$er)iselone(#O
Point,escription current,esc Q ne) Point,escription(#O
current,esc.petName Q this.desc.petNameO
ne)Point.desc Q current,escO
return ne)PointO
N
*f +ou rerun the application once again as sho)n in 0igure D4F, +ou see that the Point returned from
lone(# does cop+ its internal reference t+pe mem$er varia$les (note the pet name is no) uniJue for $oth
p@ and pA#.
To summari8e the cloning process, if +ou have a class or structure that contains nothing $ut value t+pes,
implement +our lone(# method using Mem$er)iselone(#. ;o)ever, if +ou have a custom t+pe that
maintains other reference t+pes, +ou need to esta$lish a ne) t+pe that takes into account each reference
t+pe mem$er varia$le.
A.=F ,uilding Com!arable Objects 5Com!arable6
R.V.COLLEGE OF ENGINEERING Page =FE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
The S+stem.*ompara$le interface specifies a $ehavior that allo)s an o$7ect to $e sorted $ased on some
specified ke+. ;ere is the formal definition6
$$ T2is inter"ace allo0s an object to s!eci"y its relations2i! $$bet0een ot2er li3e objects.
pu$lic interface *ompara$le
M
int ompareTo(o$7ect o#O
N
!et9s assume +ou have updated the ar class to maintain an internal *, num$er (represented $+ a simple
integer named car*,# that can $e set via a constructor parameter and manipulated using a ne) propert+
named *,. ;ere are the relevant updates to the ar t+pe6
pu$lic class ar
M
...
private int car*,O
pu$lic int *,
M
get M return car*,O N
set M car*, Q valueO N
N
pu$lic ar(string name, int currSp, int id#
M
currSpeed Q currSpO
petName Q nameO
car*, Q idO
R.V.COLLEGE OF ENGINEERING Page =FF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
...
N
($7ect users might create an arra+ of ar t+pes as follo)s6
static void Main(stringVW args#
M
$$ Ma3e an array o" Car ty!es.
arVW m+'utos Q ne) arVBWO
m+'utosVGW Q ne) ar(R"ust+R, EG, 1#O
m+'utosV1W Q ne) ar(RMar+R, AG, =@A#O
m+'utosV=W Q ne) ar(R2iperR, AG, @A#O
m+'utosV@W Q ne) ar(RMelR, AG, A#O
m+'utosVAW Q ne) ar(Rhuck+R, AG, B#O
N
's +ou recall, the S+stem.'rra+ class defines a static method named Sort(#. %hen +ou invoke this method
on an arra+ of intrinsic t+pes (int, short, string, etc.#, +ou are a$le to sort the items in the arra+ in
numerical?alpha$etic order as these intrinsic data t+pes implement *ompara$le. ;o)ever, )hat if +ou
)ere to send an arra+ of ar t+pes into the Sort(# method as follo)sP
$$ Sort my carsH
'rra+.Sort(m+'utos#O
*f +ou run this test, +ou )ould find that an 'rgument./ception e/ception is thro)n $+ the runtime, )ith
the follo)ing message6 3't least one o$7ect must implement *ompara$le.5 %hen +ou $uild custom
t+pes, +ou can implement *ompara$le to allo) arra+s of +our t+pes to $e sorted. %hen +ou flesh out the
R.V.COLLEGE OF ENGINEERING Page @GG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
details of ompareTo(#, it )ill $e up to +ou to decide )hat the $aseline of the ordering operation )ill $e.
0or the ar t+pe, the internal car*, seems to $e the most logical candidate6
$$ T2e iteration o" t2e Car can be ordered based on t2e Car1.
pu$lic class ar 6 Com!arable
M
...
$$ Com!arable im!lementation.
int *ompara$le.ompareTo(o$7ect o$7#
M
ar temp Q (ar#o$7O
if(this.car*, Y temp.car*,#
return 1O
if(this.car*, X temp.car*,#
return 41O
else
return GO
N
N
's +ou can see, the logic $ehind ompareTo(# is to test the incoming t+pe against the current instance
$ased on a specific point of data. The return value of ompareTo(# is used to discover if this t+pe is less
than, greater than, or eJual to the o$7ect it is $eing compared )ith (see the follo)ing ta$le#.
Com!areTo56 4eturn +alue Meaning
R.V.COLLEGE OF ENGINEERING Page @G1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
'n+ num$er less than 8ero This instance comes $efore the specified o$7ect
in the sort order.
fero This instance is eJual to the specified o$7ect.
'n+ num$er greater than 8ero This instance comes after the specified o$7ect
in the sort order.
No) that +our ar t+pe understands ho) to compare itself to like o$7ects, +ou can )rite the follo)ing
user code6
$$ E;ercise t2e Com!arable inter"ace.
static void Main(stringVW args#
M
$$ Ma3e an array o" Car ty!es.
...
$$ 1um! current array.
onsole.%rite!ine(R;ere is the unordered set of cars6R#O
foreach(ar c in m+'utos#
onsole.%rite!ine(RMGN M1NR, c.*,, c.PetName#O
$$ No0? sort t2em using Com!arable>
'rra+.Sort(m+'utos#O
$$ 1um! sorted array.
onsole.%rite!ine(R;ere is the ordered set of cars6R#O
foreach(ar c in m+'utos#
onsole.%rite!ine(RMGN M1NR, c.*,, c.PetName#O
onsole."ead!ine(#O
N
R.V.COLLEGE OF ENGINEERING Page @G=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
A.@G E;!loring t2e System.Collections Names!ace
%e kno) that the S+stem.'rra+ class provides a num$er of services (e.g., reversing, sorting, clearing, and
enumerating#. ;o)ever, the simple 'rra+ class has a num$er of limitations, most nota$l+ it does not
d+namicall+ resi8e itself as +ou add or clear items. %hen +ou need to contain t+pes in a more fle/i$le
container, +ou ma+ )ish to leverage the t+pes defined )ithin the S+stem.ollections namespace.
The S+stem.ollections namespace defines a num$er of interfaces. 's +ou can guess, a ma7orit+ of the
collection classes implement these interfaces to provide access to their contents. 0ollo)ing ta$le gives a
$reakdo)n of the core collection4centric interfaces.
System.Collections
nter"ace
Meaning
*ollection ,efines generic characteristics (e.g., count and thread
safet+# for a collection t+pe.
*omparer ,efines methods to support the comparison of o$7ects for
eJualit+.
*,ictionar+ 'llo)s an o$7ect to represent its contents using name?value
pairs.
*,ictionar+.numerator .numerates the contents of a t+pe supporting *,ictionar+.
*.numera$le "eturns the *.numerator interface for a given o$7ect.
*.numerator 1enerall+ supports foreach4st+le iteration of su$t+pes.
*;ashodeProvider "eturns the hash code for the implementing t+pe using a
customi8ed hash algorithm.
*!ist Provides $ehavior to add, remove, and inde/ items in a list
R.V.COLLEGE OF ENGINEERING Page @G@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
of o$7ects.
0ollo)ing figure illustrates the relationship $et)een each t+pe of the interfaces6
T2e Class Ty!es o" System.Collections
%e, kno) that interfaces $+ themselves are not ver+ useful until the+ are implemented $+ a given class or
structure. The follo)ing ta$le provides a rundo)n of the core classes in the S+stem.ollections
namespace and the ke+ interfaces the+ support.
System.Collections Class Meaning :ey m!lemented
nter"aces
'rra+!ist "epresents a d+namicall+ si8ed arra+ of *!ist, *ollection,
R.V.COLLEGE OF ENGINEERING Page @GA
*;ashodeProvider *.numerator
*,ictionar+.numerator *omparer
*,ictionar+ *!ist
*.numera$le
*ollection
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
o$7ects. *.numera$le, and
*lonea$le
;ashta$le "epresents a collection of o$7ects identified
$+ a numerical ke+. ustom t+pes stored in
a ;ashta$le should al)a+s override
S+stem.($7ect.1et;ashode(#.
*,ictionar+,
*ollection,
*.numera$le, and
*lonea$le
Zueue "epresents a standard first4in, first4out
(0*0(# Jueue.
*ollection,
*lonea$le, and
*.numera$le
Sorted!ist !ike a dictionar+O ho)ever, the elements
can also $e accessed $+ ordinal position
(e.g., inde/#.
*,ictionar+,
*ollection,
*.numera$le, and
*lonea$le
Stack ' last4in, first4out (!*0(# Jueue providing
push and pop (and peek# functionalit+.
*ollection,
*lonea$le, and
*.numera$le
*n addition to these ke+ t+pes, S+stem.ollections defines some minor pla+ers (at least in terms of their
da+4to4da+ usefulness# such as Bit'rra+, ase*nsensitiveomparer, and
ase*nsensitive;ashodeProvider. 0urthermore, this namespace also defines a small set of a$stract $ase
classes (ollectionBase, "ead(nl+ollectionBase, and ,ictionar+Base# that can $e used to $uild strongl+
t+ped containers.
%or3ing 0it2 t2e (rray#ist Ty!e
The 'rra+!ist t+pe is $ound to $e +our most freJuentl+ used t+pe in the S+stem.ollections namespace in
that it allo)s +ou to d+namicall+ resi8e the contents at +our )him. To illustrate the $asics of this t+pe,
ponder the follo)ing code, )hich leverages the 'rra+!ist to manipulate a set of ar o$7ects6
static void Main(stringVW args#
R.V.COLLEGE OF ENGINEERING Page @GB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
$$ Create (rray#ist and "ill 0it2 some initial values.
'rra+!ist car'r!ist Q ne) 'rra+!ist(#O
car'r!ist.'dd"ange(ne) arV W M ne) ar(R0redR, FG, 1G#,
ne) ar(RMar+R, 1GG, BG#, ne) ar(RMBR, 1FG, 11#N#O
onsole.%rite!ine(R*tems in car'r!ist6 MGNR, car'r!ist.ount#O
$$ Print out current values.
foreach(ar c in car'r!ist#
onsole.%rite!ine(Rar pet name6 MGNR, c.PetName#O
$$ nsert a ne0 item.
onsole.%rite!ine(R[n4Y*nserting ne) ar.R#O
car'r!ist.*nsert(=, ne) ar(RTheNe)arR, G, 1=##O
onsole.%rite!ine(R*tems in car'r!ist6 MGNR, car'r!ist.ount#O
$$ Eet object array "rom (rray#ist and !rint again.
o$7ectVW arra+(fars Q car'r!ist.To'rra+(#O
for(int i Q GO i X arra+(fars.!engthO iHH#
M
onsole.%rite!ine(Rar pet name6 MGNR,
((ar#arra+(farsViW#.PetName#O
N
N
R.V.COLLEGE OF ENGINEERING Page @GC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
;ere +ou are making use of the 'dd"ange(# method to populate +our 'rra+!ist )ith a set of ar t+pes
(this is $asicall+ a shorthand notation for calling 'dd(# n num$er of times#. (nce +ou print out the
num$er of items in the collection (as )ell as enumerate over each item to o$tain the pet name#, +ou
invoke *nsert(#. The *nsert(# allo)s +ou to plug a ne) item into the 'rra+!ist at a specified inde/. 0inall+,
notice the call to the To'rra+(# method, )hich returns a generic arra+ of S+stem.($7ect t+pes $ased on
the contents of the original 'rra+!ist.
%or3ing 0it2 t2e Pueue Ty!e
Zueues are containers that ensure items are accessed using a first4in, first4out manner. Sadl+, )e humans
are su$7ect to Jueues all da+ long6 lines at the $ank, lines at the movie theater, and lines at the morning
coffeehouse. %hen +ou are modeling a scenario in )hich items are handled on a first4come, first4served
$asis, S+stem.ollections.Zueue is +our t+pe of choice. *n addition to the functionalit+ provided $+ the
supported interfaces, Zueue defines the ke+ mem$ers sho)n in the follo)ing ta$le.
Member o"
System.Collection.Pueue
Meaning
,eJueue(# "emoves and returns the o$7ect at the $eginning of the
Zueue
.nJueue(# 'dds an o$7ect to the end of the Zueue
Peek(# "eturns the o$7ect at the $eginning of the Zueue
)ithout removing it
%or3ing 0it2 t2e Stac3 Ty!e
The S+stem.ollections.Stack t+pe represents a collection that maintains items using a last4in, first4out
manner. 's +ou )ould e/pect, Stack defines a mem$er named Push(# and Pop(# (to place items onto or
remove items from the stack#. The follo)ing stack e/ample makes use of the standard S+stem.String6
R.V.COLLEGE OF ENGINEERING Page @GD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
static void Main(stringVW args#
M
...
Stack stringStack Q ne) Stack(#O
stringStack.Push(R(neR#O
stringStack.Push(RT)oR#O
stringStack.Push(RThreeR#O
$$ No0 loo3 at t2e to! item? !o! it? and loo3 again.
onsole.%rite!ine(RTop item is6 MGNR, stringStack.Peek(##O
onsole.%rite!ine(RPopped off MGNR, stringStack.Pop(##O
onsole.%rite!ine(RTop item is6 MGNR, stringStack.Peek(##O
onsole.%rite!ine(RPopped off MGNR, stringStack.Pop(##O
onsole.%rite!ine(RTop item is6 MGNR, stringStack.Peek(##O
onsole.%rite!ine(RPopped off MGNR, stringStack.Pop(##O
tr+
M
onsole.%rite!ine(RTop item is6 MGNR, stringStack.Peek(##O
onsole.%rite!ine(RPopped off MGNR, stringStack.Pop(##O
N
catch(./ception e#
M onsole.%rite!ine(R.rrorLL MGNR, e.Message#O N
N
;ere, +ou $uild a stack that contains three string t+pes (named according to their order of insertion#. 's
+ou peek onto the stack, +ou )ill al)a+s see the item at the ver+ top, and therefore the first call to Peek(#
reveals the third string. 'fter a series of Pop(# and Peek(# calls, the stack is eventuall+ empt+, at )hich
time additional Peek(#?Pop(# calls raise a s+stem e/ception.
R.V.COLLEGE OF ENGINEERING Page @GE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
A.@1 Summary
*n addition to $uilding +ou custom interfaces, the .N.T li$raries define a num$er of standard (i.e.
frame)ork4supplied# interfaces. This unit focused on the interfaces defined )ithin the
S+stem.ollections namespace. 's +ou have seen, +ou are free to $uild custom t+pes that implement
these predefined interfaces to gain a num$er of desira$le traits such as cloning, sorting and enumerating.
A.@= :ey0ords
*onverti$le.To>>>>(# method
*0ormatProvider *nterface
1et0ormat(# method
*onverti$le.1etT+peode(# method
S+stem.onvert
1et.numerator(# method
lone(# method
1U*,
ompareTo(# method
The classes6 'rra+!ist, ;ashta$le, Zueue, Sorted!ist, Stack
A.@@ E;ercises
=@. ./plain an+ t)o methods of *onverti$le interface.
=A. ./plain the usage of *.numera$le and *.numerator interfaces )ith suita$le e/amples.
=B. %hat do +ou mean $+ clonea$le o$7ectP %rite an e/ample to depict the implementation of
*lonea$le *nterface.
=C. *llustrate )ith an e/ample, the implementation of *ompara$le interface.
=D. 1ive the s+nta/ for the method ompareTo(# and e/plain $riefl+.
=E. !ist out some of the interfaces provided $+ S+stem.ollection namespace. ,ra) the diagram to
sho) the hierarchical relationship that e/ists $et)een these interfaces.
=F. %hat are the ma7or classes in S+stem.ollections namespaceP ./plain.
R.V.COLLEGE OF ENGINEERING Page @GF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
@G. %rite a code segment to illustrate the )orking of 'rra+!ist class.
@1. %hat the mem$ers of S+stem.ollection.ZueueP ./plain.
@=. %rite a code snippet to sho) the usage of Stack class.
Module 9
Unit 1
CONTENTS:
1.AE ($7ectives
1.AF *ntroduction
1.BG Understanding all$ack *nterfaces
1.B1 Understanding the .N.T ,elegate T+pe
1.B= Mem$ers of S+stem.Multicast ,elegate
1.B@ The Simplest Possi$le ,elegate ./ample
1.BA Building More .la$orate ,elegate ./ample
1.BB Understanding 's+nchronous ,elegates
1.BC Understanding (and Using# .vents
1.BD Summar+
1.BE :e+)ords
1.BF ./ercises
1.AG Objectives
't the end of this lesson, the students )ill understand6
The meaning of call$ack interfaces and its usage
,elegate t+pes, their usage, mem$ers of Multicast delegate, s+nchronous and as+nchronous
delegates
.vents
R.V.COLLEGE OF ENGINEERING Page @1G
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1.A1 ntroduction
Up to this point in the te/t, ever+ application +ou have developed added various $its of code to Main(#,
)hich, in some )a+ or another, sent reJuests to a given o$7ect. ;o)ever, +ou have not +et e/amined ho)
an o$7ect can talk $ack to the entit+ that created it. *n most programs, it is Juite common for o$7ects in a
s+stem to engage in a t)o4)a+ conversation through the use of call$ack interfaces, events, and other
programming constructs. To set the stage, this chapter $egins $+ e/amining ho) interface t+pes ma+ $e
used to ena$le call$ack functionalit+.
Ne/t, +ou learn a$out the .N.T delegate t+pe, )hich is a t+pe4safe o$7ect that 3points to5 other method(s#
that can $e invoked at a later time. Unlike a traditional HH function pointer, ho)ever, .N.T delegates
are o$7ects that have $uilt4in support for multicasting and as+nchronous method invocation. (nce +ou
learn ho) to create and manipulate delegate t+pes, +ou then investigate the & event ke+)ord, )hich
simplifies and streamlines the process of )orking )ith delegate t+pes.
1.A= Understanding Callbac3 nter"aces
's +ou have seen in the previous module, interfaces define a $ehavior that ma+ $e supported $+ various
t+pes in +our s+stem. Be+ond using interfaces to esta$lish pol+morphism, interfaces ma+ also $e used as
a callbac0 mec)anism. This techniJue ena$les o$7ects to engage in a t)o4)a+ conversation using a
common set of mem$ers. To illustrate the use of call$ack interfaces, let9s update the no) familiar ar
t+pe in such a )a+ that it is a$le to inform the caller )hen it is a$out to e/plode (the current speed is 1G
miles $elo) the ma/imum speed# and has e/ploded (the current speed is at or a$ove the ma/imum
speed#. The a$ilit+ to send and receive these events )ill $e facilitated )ith a custom interface named
*.ngine.vents6
$$ T2e callbac3 inter"ace.
R.V.COLLEGE OF ENGINEERING Page @11
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic interface EngineEvents
M
void '$outToBlo)(string msg#O
void ./ploded(string msg#O
N
.vent interfaces are not t+picall+ implemented directl+ $+ the o$7ect directl+ interested in receiving the
events, $ut rather $+ a helper o$7ect called a sin0 ob/ect. The sender of the events (the ar t+pe in this
case# )ill make calls on the sink under the appropriate circumstances. 'ssume the sink class is called
ar.ventSink, )hich simpl+ prints out the incoming messages to the console. Be+ond this point, our sink
)ill also maintain a string that identifies its friendl+ name6
$$ Car event sin3.
pu$lic class ar.ventSink 6 EngineEvents
M
private string nameO
pu$lic ar.ventSink(#M N
pu$lic ar.ventSink(string sinkName#
M name Q sinkNameO N
pu$lic void '$outToBlo)(string msg#
M onsole.%rite!ine(RMGN reporting6 M1NR, name, msg#O N
pu$lic void ./ploded(string msg#
M onsole.%rite!ine(RMGN reporting6 M1NR, name, msg#O N
N
R.V.COLLEGE OF ENGINEERING Page @1=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
No) that +ou have a sink o$7ect that implements the event interface, +our ne/t task is to pass a reference
to this sink into the ar t+pe. The ar holds onto the reference and makes calls $ack on the sink )hen
appropriate. *n order to allo) the ar to o$tain a reference to the sink, )e )ill need to add a pu$lic helper
mem$er to the ar t+pe that )e )ill call 'dvise(#. !ike)ise, if the caller )ishes to detach from the event
source, it ma+ call another helper method on the ar t+pe named Unadvise(#. 0inall+, in order to allo) the
caller to register multiple event sinks (for the purposes of multicasting#, the ar no) maintains an
'rra+!ist to represent each outstanding connection6
$$ T2is Car and caller can no0 communicate
$$ using t2e EngineEvents inter"ace.
pu$lic class ar
M
$$ T2e set o" connected sin3s.
'rra+!ist clientSinks Q ne) 'rra+!ist(#O
$$ (ttac2 or disconnect "rom t2e source o" events.
pu$lic void 'dvise(*.ngine.vents sink#
M clientSinks.'dd(sink#O N
pu$lic void Unadvise(*.ngine.vents sink#
M clientSinks."emove(sink#O N
...
N
To actuall+ send the events, let9s update the ar.'ccelerate(# method to iterate over the list of connections
maintained $+ the 'rra+!ist and fire the correct notification )hen appropriate (note the ar class no)
maintains a Boolean mem$er varia$le named car*s,ead to represent the engine9s state#6
$$ nter"ace8based event !rotocol>
R.V.COLLEGE OF ENGINEERING Page @1@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
class ar
M
...
$$ s t2e car alive or deadH
$ool car*s,eadO
pu$lic void 'ccelerate(int delta#
M
$$ " t2e car is =dead=? send E;!loded event to eac2 sin3.
if(car*s,ead#
M
foreach(*.ngine.vents e in clientSinks#
e../ploded(RSorr+, this car is dead...R#O
N
else
M
currSpeed HQ deltaO
$$ Send (boutTo,lo0 event.
if(1G QQ ma/Speed 4 currSpeed#
M
foreach(*.ngine.vents e in clientSinks#
e.'$outToBlo)(Rareful LLLR#O
N
if(currSpeed YQ ma/Speed#
car*s,ead Q trueO
else
R.V.COLLEGE OF ENGINEERING Page @1A
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsole.%rite!ine(RurrSpeedQ MGN R, currSpeed#O
N
N
N
;ere is some client4side code, no) making use of a call$ack interface to listen to the ar events6
$$ Ma3e a car and listen to t2e events.
pu$lic class ar'pp
M
static void Main(stringVW args#
M
onsole.%rite!ine(RKKKKK *nterfaces as event ena$lers KKKKKR#O
ar c1 Q ne) ar(RSlugBugR, 1GG, 1G#O
$$ Ma3e sin3 object.
ar.ventSink sink Q ne) ar.ventSink(#O
$$ Pass t2e Car a re"erence to t2e sin3.
c1.'dvise(sink#O
$$ S!eed u! 5t2is 0ill trigger t2e events6.
for(int i Q GO i X 1GO iHH#
c1.'ccelerate(=G#O
R.V.COLLEGE OF ENGINEERING Page @1B
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
$$ 1etac2 "rom event source.
c1.Unadvise(sink#O
onsole."ead!ine(#O
N
N
,o note that the Unadvise(# method can $e ver+ helpful in that it allo)s the caller to selectivel+ detach
from an event source at )ill. ;ere, +ou call Unadvise(# $efore e/iting Main(#, although this is not
technicall+ necessar+. ;o)ever, assume that the application no) )ishes to register t)o sinks,
d+namicall+ remove a particular sink during the flo) of e/ecution, and continue processing the program
at large.
1.A@ Understanding t2e .NET 1elegate Ty!e
Before formall+ defining .N.T delegates, let9s gain a $it of perspective. ;istoricall+ speaking, the
%indo)s 'P* makes freJuent use of 4st+le function pointers to create entities termed callbac0 functions
or simpl+ callbac0s. Using call$acks, programmers )ere a$le to configure one function to report $ack to
(call $ack# another function in the application. The pro$lem )ith standard 4st+le call$ack functions is
that the+ represent little more than a ra) address in memor+. *deall+, call$acks could $e configured to
include additional t+pe4safe information such as the num$er of (and t+pes of# parameters and the return
value (if an+# of the method pointed to. Sadl+, this is not the case in traditional call$ack functions, and, as
+ou ma+ suspect, can therefore $e a freJuent source of $ugs, hard crashes, and other runtime disasters.
Nevertheless, call$acks are useful entities. *n the .N.T 0rame)ork, call$acks are still possi$le, and their
functionalit+ is accomplished in a much safer and more o$7ect4oriented manner using delegates. *n
essence, a delegate is a t+pe4safe o$7ect that points to another method (or possi$l+ multiple methods# in
the application, )hich can $e invoked at a later time. Specificall+ speaking, a delegate t+pe maintains
three important pieces of information6
The name of the method on )hich it makes calls
The arguments (if an+# of this method
The return value (if an+# of this method
R.V.COLLEGE OF ENGINEERING Page @1C
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
(nce a delegate has $een created and provided the aforementioned information, it ma+ d+namicall+
invoke the method(s# it points to at runtime. 's +ou )ill see, ever+ delegate in the .N.T 0rame)ork
(including +our custom delegates# is automaticall+ endo)ed )ith the a$ilit+ to call their methods
sync)ronously or async)ronously. This fact greatl+ simplifies programming tasks, given that )e can call a
method on a secondar+ thread of e/ecution )ithout manuall+ creating and managing a Thread o$7ect.
1e"ining a 1elegate in C7
%hen +ou )ant to create a delegate in &, +ou make use of the delegate ke+)ord. The name of +our
delegate can $e )hatever +ou desire. ;o)ever, +ou must define the delegate to match the signature of the
method it )ill point to. 0or e/ample, assume +ou )ish to $uild a delegate named Binar+(p that can point
to an+ method that returns an integer and takes t)o integers as input parameters6
$$ T2is delegate can !oint to any met2od? ta3ing t0o integers
$$ and returning an integer.
pu$lic delegate int Binar+(p(int /, int +#O
%hen the & compiler processes delegate t+pes, it automaticall+ generates a sealed class deriving from
S+stem.Multicast,elegate. This class (in con7unction )ith its $ase class, S+stem.,elegate# provides the
necessar+ infrastructure for the delegate to hold onto the list of methods to $e invoked at a later time.
1.AA Members o" System.Multicast1elegate
%hen +ou $uild a t+pe using the & delegate ke+)ord, +ou indirectl+ declare a class t+pe that derives
from S+stem.Multicast,elegate. This class provides descendents )ith access to a list that contains the
addresses of the methods maintained $+ the delegate t+pe, as )ell as several additional methods (and a
fe) overloaded operators# to interact )ith the invocation list. ;ere are some select mem$ers of
S+stem.Multicast,elegate6
R.V.COLLEGE OF ENGINEERING Page @1D
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
n2erited Member Meaning
Method This propert+ returns a S+stem."eflection.Method*nfo t+pe that
represents details of a static method that is maintained $+ the delegate.
Target *f the method to $e called is defined at the o$7ect level (rather than a
static method#, Target returns an o$7ect that represents the method
maintained $+ the delegate. *f the value returned from Target eJuals
null, the method to $e called is a static mem$er.
om$ine(# This static method adds a method to the list maintained $+ the delegate.
*n &, +ou trigger this method using the overloaded HQ operator as
a shorthand notation.
1et*nvocation!ist(# This method returns an arra+ of S+stem.,elegate t+pes, each
representing a particular method that ma+ $e invoked.
"emove(#
"emove'll(#
These static methods remove a method (or all methods# from the
invocation list. *n &, the "emove(# method can $e called indirectl+
using
the overloaded 4Q operator.
1.AB T2e Sim!lest Possible 1elegate E;am!le
,elegates can tend to cause a great deal of confusion )hen encountered for the first time. Thus, to get the
$all rolling, let9s take a look at a ver+ simple e/ample that leverages our Binar+(p delegate t+pe. ;ere is
the complete code, )ith anal+sis to follo)6
namespace Simple,elegate
M
$$ T2is delegate can !oint to any met2od? ta3ing t0o
R.V.COLLEGE OF ENGINEERING Page @1E
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
$$ integers and returning an integer.
pu$lic delegate int Binar+(p(int /, int +#O
$$ T2is class contains met2ods ,inaryO! 0ill !oint to.
pu$lic class SimpleMath
M
pu$lic static int 'dd(int /, int +#
M return / H +O N
pu$lic static int Su$tract(int /, int +#
M return / < +O N
N
class Program
M
static void Main(stringVW args#
M
onsole.%rite!ine(RSimple ,elegate ./ampleR#O
$$ Create a ,inaryO! object t2at
$$ V!oints toV Sim!leMat2.(dd56.
Binar+(p $ Q ne) Binar+(p(SimpleMath.'dd#O
$$ nvo3e (dd56 met2od using delegate.
onsole.%rite!ine(R1G H 1G is MGNR, $(1G, 1G##O
onsole."ead!ine(#O
N
N
N
R.V.COLLEGE OF ENGINEERING Page @1F
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
'gain notice the format of the Binar+(p delegate, )hich can point to an+ method taking t)o integers and
returning an integer. 1iven this, )e have created a class named SimpleMath, )hich defines t)o static
methods that match the pattern defined $+ the Binar+(p delegate. %hen +ou )ant to insert the target
method to a given delegate, simpl+ pass in the name of the method to the delegate9s constructor. 't this
point, +ou are a$le to invoke the mem$er pointed to using a s+nta/ that looks like a direct function
invocation6
$$ nvo3e56 is really called 2ere>
onsole.%rite!ine(R1G H 1G is MGNR, $(1G, 1G##O
Under the hood, the runtime actuall+ calls the compiler4generated *nvoke(# method. "ecall that .N.T
delegates (unlike 4st+le function pointers# are type safe. Therefore, if +ou attempt to pass a delegate a
method that does not 3match the pattern,5 +ou receive a compile4time error. To illustrate, assume the
SimpleMath class defines an additional method named SJuareNum$er(#6
pu$lic class SimpleMath
M
...
pu$lic static int SJuareNum$er(int a#
M return a K aO N
N
1iven that the Binar+(p delegate can only point to methods that take t)o integers and return an integer,
the follo)ing code is illegal and )ill not compile6
$$ Error> Met2od does not matc2 delegate !attern>
Binar+(p $ Q ne) Binar+(p(SimpleMath.SJuareNum$er#O
R.V.COLLEGE OF ENGINEERING Page @=G
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1.AC ,uilding a More Elaborate 1elegate E;am!le
To illustrate a more advanced use of delegates, let9s $egin $+ updating the ar class to include t)o ne)
Boolean mem$er varia$les. The first is used to determine )hether +our automo$ile is due for a )ash
(is,irt+#O the other represents )hether the car in Juestion is in need of a tire rotation (should"otate#. To
ena$le the o$7ect user to interact )ith this ne) state data, ar also defines some additional properties and
an updated constructor. ;ere is the stor+ so far6
$$ U!dated Car class.
pu$lic class ar
M
...
$$ (re 0e in need o" a 0as2H Need to rotate tiresH
private $ool is,irt+O
private $ool should"otateO
$$ E;tra !arams to set bools.
pu$lic ar(string name, int ma/, int curr, $ool )ashar, $ool rotateTires#
M
...
is,irt+ Q )asharO
should"otate Q rotateTiresO
N
pu$lic $ool ,irt+
M
R.V.COLLEGE OF ENGINEERING Page @=1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
getM return is,irt+O N
setM is,irt+ Q valueO N
N
pu$lic $ool "otate
M
getM return should"otateO N
setM should"otate Q valueO N
N
N
No), also assume the ar t+pe nests a ne) delegate, ar,elegate6
$$ Car de"ines yet anot2er delegate.
pu$lic class ar
M
...
$$ Can call any met2od ta3ing a Car as
$$ a !arameter and returning not2ing.
pu$lic delegate void ar,elegate(ar c#O
...
N
;ere, +ou have created a delegate named ar,elegate. The ar,elegate t+pe represents 3some function5
taking a ar as a parameter and returning void.
R.V.COLLEGE OF ENGINEERING Page @==
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1.AD Understanding (sync2ronous 1elegates
Till no), )e have seen the s+nchronous $ehavior of .N.T delegate t+pes. No) let us e/amine ho) to
invoke methods as+nchronousl+. 0irst off, )hat e/actl+ )arrants an as+nchronous method invocationP
's +ou are a)are, some programming operations take time. 0or e/ample, if +ou $uild a )ord processing
application that has the a$ilit+ to print the current document, and that document happens to $e 1GGG pages
in length, the computer9s PU has the potential to spin a)a+ for Juite some time.
No) assume that this application has all of its programming logic taking place )ithin the Main(# method
using a single t)read. Simpl+ put, a thread is a path of e/ecution )ithin a .N.T application. Single4
threaded applications are Juite simple to programO ho)ever, in the case of )ord processor application, the
end user is far less than pleased. The reason has to do )ith the fact that )hile the application9s single
thread of e/ecution is crunching out the 1GGG4page document, all other aspects of this program (such as
menu activation, tool$ar clicking, and ke+$oard input# are unresponsive.
%hen programmers )ish to $uild applications that are a$le to simulate numerous tasks performing 3at the
same time5, the+ )ill t+picall+ spa)n additional threads to perform $ackground tasks (e.g. printing
documents# )hile the main thread is still a$le to respond to $asic user4input needs.
So, )hat does threading have to do )ith .N.T delegatesP %ell, to illustrate the potential pro$lem )ith
sync)ronous delegate invocations, consider the follo)ing application6
using S+stemO
using S+stem.ThreadingO
R.V.COLLEGE OF ENGINEERING Page @=@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
namespace 's+nc,elegate
M
?? a ne) delegate t+pe
pu$lic delegate string Ne)ar,elegate(ar carTo,etail#O
pu$lic class ar M ].N
class 'pp
M
pu$lic static stirng ,etailar(ar c#
M
??,etailing a car takes 1G seconds
onsole.%rite!ine(3,etailing ar on Thread MGN5,
Thread.urrentThread.1et;ashode(##O
Thread.Sleep(1GGGG#O
return 3-our car is read+LL5O
N
static void Main(stringVW args#
M
onsole.%rite!ine(3Main(# is on thread MGN5,
Thread.urrentThread.1et;ashode(##O
Ne)ar,elegate dQ ne) Ne)ar,elegate(,etailar#O
ar m+carQne) ar(#O
onsole.%rite!ine(d(m+car##O
R.V.COLLEGE OF ENGINEERING Page @=A
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsole.%rite!ine(3,one invoking delegate5#O
N
N
N
Notice that, this e/ample makes use of a ne) namespace named S+stem.Threading. This namespace
defines a t+pe named Thread, )hich provides a static method named urrentThread(#. *f +ou o$tain the
hash code for the current thread, +ou o$tain a uniJue identifier for the currentl+ e/ecuting thread.
;ere, +ou print out the hash code of the current thread )ithin Main(#, and then s+nchronousl+ invoke the
Ne)ar,elegate t+pe. (nce the flo) of e/ecution passes into the ,etailar(# helper function, +ou print
out the hash code for the active thread once again and put it to sleep for 1G seconds. 1iven this, +ou )ill
not see the final message of Main(# print to the console until appro/imatel+ 1G seconds after the
delegate9s invocation.
nvo3ing Met2ods (sync2ronously
%hen the & compiler processes the 3delegate5 ke+)ord, +ou d+namicall+ receive t)o methods named
Begin*nvoke(# and .nd*nvoke(#. Thus, for the Ne)ar,elegate t+pe, +ou are provided )ith the
follo)ing mem$er6
pu$lic *'s+nc"esult Begin*nvoke(ar carTo,etail,
S+stem.'s+ncall$ack call$ack, o$7ect state#O
pu$lic string .nd*nvoke(*'s+nc"esult result#O
R.V.COLLEGE OF ENGINEERING Page @=B
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Note that Begin*nvoke(# returns an *'s+nc"esult interface, )hile .nd*nvoke(# reJuires an *'s+nc*nvoke
t+pe as parameter.
*n the simplest case, one is a$le to effectivel+ ignore directl+ interacting )ith these mem$ers. 'll +ou
have to do is cache the returned *'s+nc"esult t+pe in a local varia$le in order to pass it to .nd*nvoke(#
)hen +ou are read+ to o$tain the result of the method invocation.
1.AE Understanding 5and using6 Events
,elegates are fairl+ interesting constructs in that the+ ena$le t)o o$7ects in memor+ to engage in a t)o4
)a+ conversation. 's +ou ma+ agree, ho)ever, )orking )ith delegates in the ra) does reJuire a good
amount of $oilerplate code (defining the delegate, declaring necessar+ mem$er varia$les, and creating
custom registration?un4registration methods#. Because the a$ilit+ for one o$7ect to call $ack to another
o$7ect is such a helpful construct, & provides the event ke+)ord to lessen the $urden of using delegates
in the ra). %hen the compiler processes the event ke+)ord, +ou are automaticall+ provided )ith
registration and un4registration methods as )ell as an+ necessar+ mem$er varia$le for +our delegate
t+pes. *n this light, the event ke+)ord is little more than s+ntactic sugar, )hich can $e used to save +ou
some t+ping time.
,efining an event is a t)o4step process. 0irst, +ou need to define a delegate that contains the methods to
$e called )hen the event is fired. Ne/t, +ou declare the events (using the & event ke+)ord# in terms of
the related delegate. *n a nutshell, defining a t+pe that can send events entails the follo)ing pattern
(sho)n in pseudo4code#6
pu$lic class Sender(f.vents
M
pu$lic delegate ret,al 'ssociated,elegate(args#O
R.V.COLLEGE OF ENGINEERING Page @=C
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic event 'ssociated,elegate NameO"EventO
...
N
The events of the ar t+pe )ill take the same name as the previous delegates ('$outToBlo) and
./ploded#. The ne) delegate to )hich the events are associated )ill $e called ar.vent;andler. ;ere are
the initial updates to the ar t+pe6
pu$lic class ar
M
$$ T2is delegate 0or3s in conjunction 0it2 t2e
$$ Car=s events.
pu$lic delegate void ar.vent;andler(string msg#O
$$ T2is car can send t2ese events.
pu$lic event ar.vent;andler ./plodedO
pu$lic event ar.vent;andler '$outToBlo)O
...
N
Sending an event to the caller is as simple as specif+ing the event $+ name as )ell as an+ reJuired
parameters as defined $+ the associated delegate. To ensure that the caller has indeed registered )ith
event, +ou )ill )ant to check the event against a null value $efore invoking the delegate9s method set.
These things $eing said, here is the ne) iteration of the ar9s 'ccelerate(# method6
pu$lic void 'ccelerate(int delta#
M
$$ " t2e car is dead? "ire E;!loded event.
R.V.COLLEGE OF ENGINEERING Page @=D
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
if (car*s,ead#
M
if (./ploded LQ null#
./ploded(RSorr+, this car is dead...R#O
N
else
M
currSpeed HQ deltaO
$$ (lmost deadH
if (1G QQ ma/Speed < currSpeed UU '$outToBlo) LQ null#
M
'$outToBlo)(Rareful $udd+L 1onna $lo)LR#O
N
$$ Still O:>
if (currSpeed YQ ma/Speed#
car*s,ead Q trueO
else
onsole.%rite!ine(R4YurrSpeed Q MGNR, currSpeed#O
N
N
%ith this, +ou have configured the car to send t)o custom events )ithout the need to define custom
registration functions. -ou )ill see the usage of this ne) automo$ile in 7ust a moment, $ut first, let9s
check the event architecture in a $it more detail.
R.V.COLLEGE OF ENGINEERING Page @=E
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1.AF Summary
*n this unit, +ou have e/amined a num$er of )a+s in )hich multiple o$7ects can partake in a $idirectional
conversation under .N.T. 0irst, +ou e/amined the use of call$ack interfaces, )hich provide a )a+ to
have o$7ect B make calls on o$7ect ' via an interface reference. Ne/t, +ou e/amined the & delegate
t+pes )hich is used to indirectl+ construct a class derived from S+stem.Multicast,elegate. *t is simpl+ an
o$7ect that maintains a list of methods to call )hen told to do so. These invocations ma+ $e made
s+nchronousl+ (using *nvoke(# method# or as+nchronousl+ (via Begin*nvoke(# and .nd*nvoke(#
methods#. 0inall+, +ou have seen event, )hich )hen used in con7unction )ith a delegate t+pe, can
simplif+ the process of sending +our even notifications to a)aiting callers.
1.BG :ey0ords
0unction Pointer
all$ack Mechanism
Sink ($7ect
'dvice(# and Unadvice(# methods
all$ack functions
S+nchronous and as+nchronous $ehavior of delegates
Thread
Thread o$7ect
Begin*nvoke(# and .nd*nvoke(# methods
The ke+)ord event
1.B1 E;ercises
D. ./plain the concept of call$ack mechanism )ith an e/ample.
E. ,efine sink o$7ects.
F. *llustrate )ith an e/ample, the usage of 'dvise(# and Un'dvise(# methods.
1G. ,efine delegate )ith s+nta/. !ist out the information maintained $+ delegates.
11. !ist out the mem$ers of S+stem.Multicast,elegate along )ith the purpose.
1=. 1ive an e/ample for the implementation of delegates.
R.V.COLLEGE OF ENGINEERING Page @=F
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1@. ./plain the concept of s+nchronous and as+nchronous delegate invocation.
1A. ,efine thread.
1B. %hat are eventsP ./plain )ith an e/ample.
Module 9
Unit '
CONTENTS:
1.CG ($7ectives
=.@E *ntroduction
=.@F The advanced ke+)ords of &
=.AG Building a ustom *nde/er
=.A1 (verloading operators
=.A= The *nternal "epresentation of (verloading (perators
=.A@ reating ustom onversion "outines
=.AA ,efining *mplicit onversion "outines
=.AB Summar+
=.AC :e+)ords
=.AD ./ercises
=.1 Objectives
't the end of this lesson, the students )ill understand the follo)ing tasks in detail6
The usage of ke+)ords like checked, unchecked, unsafe, volatile etc.
Meaning of inde/er and its usage
(perator overloading and the )a+ the+ are represented $+ *!
./plicit and implicit conversions.
R.V.COLLEGE OF ENGINEERING Page @@G
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
=.@D ntroduction
This unit investigates advanced constructs of &. -ou )ill learn ho) to programmaticall+ account for
overflo)?underflo) conditions using checked?unchecked ke+)ords, ho) to create an unsafe code for
directl+ manipulating pointer t+pes. Ne/t, +ou learn ho) to construct and use an inde/er method,
overloading operators (like H, 4 etc# and create custom conversion functions (the & eJuivalent to
overloading the (# operator under HH#.
=.@E T2e (dvanced :ey0ords o" C7
Throughout our discussion till all these units, )e have seen man+ & ke+)ords. *n addition to those, &
provides a set of ke+)ords vi8.
checked?unchecked
unsafe?stackalloc? fi/ed?volatile?si8eof
lock
./cept the ke+)ord loc0, that is used in multithreading, )e )ill discuss other ke+)ords here in detail.
T2e chec6ed :ey0ord
's +ou kno), each numerical data t+pe has a fi/ed upper and lo)er limit ()hich ma+ $e o$tained
programmaticall+ using the Ma/2alue and Min2alue properties#. No), )hen +ou are performing
arithmetic operations on a specific t+pe, it is possi$le that +ou ma+ accidentall+ overflow the ma/imum
storage of the t+pe (i.e., assign a value that is greater than the ma/imum value# or underflow the minimum
storage of the t+pe (i.e., assign a value that is less than the minimum value#. These t)o situations are
together termed as overflow. onsider the follo)ing e/ample for illustration.
namespace heckedUnchecked
M
R.V.COLLEGE OF ENGINEERING Page @@1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
class Program
M
static void Main(stringVW args#
M
$$ ma; value o" byte is 'I.
onsole.%rite!ine(RMa/ value of $+te is MGN.R, $+te.Ma/2alue#O
onsole.%rite!ine(RMin value of $+te is MGN.R, $+te.Min2alue#O
$+te $1 Q 1GGO
$+te $= Q =BGO
$+te sum Q ($+te#($1 H $=#O
onsole.%rite!ine(Rsum Q MGNR, sum#O
N
N
N
The value of sum )ill $e FA $ut not @BG. The reason is simple. 1iven that a S+stem.B+te can hold a value
onl+ $et)een G and =BB (inclusive, for a grand total of =BC slots#, sum no) contains the overflo) value
(@BG < =BC Q FA#. 's +ou have 7ust seen, if +ou take no corrective course of action, overflo) occurs
)ithout e/ception. 't times, this hidden overflo) ma+ cause no harm )hatsoever in +our pro7ect. (ther
times, this loss of data is completel+ unaccepta$le.
To handle overflo) or underflo) conditions in +our application, +ou have t)o options. The first choice is
to handle all overflo) conditions manuall+. That, is +ou can modif+ the statements like <
$+te $1 Q 1GGO
$+te $= Q =BGO
R.V.COLLEGE OF ENGINEERING Page @@=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
int sum Q $1 H $=O $$ Store sum in integer to !revent over"lo0.
But, if the values of $1 and $= are input from the ke+$oard, and if +ou forget to declare sum as integer,
then there )ill $e an une/pected output. To avoid this pro$lem, & provides the c)ec0ed ke+)ord. %hen
+ou )rap a statement (or a $lock of statements# )ithin the scope of the checked ke+)ord, the &
compiler emits specific *! instructions that test for overflo) conditions that ma+ result )hen adding,
multipl+ing, su$tracting, or dividing t)o numerical data t+pes. *f an overflo) has occurred, the runtime
)ill thro) a S+stem.(verflo)./ception t+pe. ($serve the changes in the follo)ing program6
class Program
M
static void Main(stringVW args#
M
$$ Over"lo0 t2e ma; value o" a System.,yte.
onsole.%rite!ine(RMa/ value of $+te is MGN.R, $+te.Ma/2alue#O
$+te $1 Q 1GGO
$+te $= Q =BGO
tr+
M
$+te sum Q c2ec3ed(($+te#($1 H $=##O
onsole.%rite!ine(Rsum Q MGNR, sum#O
N
catch((verflo)./ception e#
M onsole.%rite!ine(e.Message#O N
N
R.V.COLLEGE OF ENGINEERING Page @@@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
;ere, +ou )rap the addition of $1 and $= )ithin the scope of the c)ec0ed ke+)ord. *f +ou )ish to force
overflo) checking to occur over a $lock of code, the s+nta/ )ould $e6
tr+
M
c2ec3ed
M
$+te sum Q ($+te#($1 H $=#O
onsole.%rite!ine(Rsum Q MGNR, sum#O
N
N
catch((verflo)./ception e#
M
onsole.%rite!ine(e.Message#O
N
*n either case, the code in Juestion )ill $e evaluated for possi$le overflo) conditions automaticall+,
)hich )ill trigger an overflo) e/ception if encountered.
T2e unchec6ed :ey0ord
'ssume that, +ou have a $lock of code )here silent overflo) is accepta$le. 0or this purpose, & provides
the unc)ec0ed ke+)ord to disa$le the thro)ing of S+stem.(verflo)./ception on a case4$+4case $asis.
The s+nta/ is as same as that of c)ec0ed ke+)ord. 0or e/ample6
$$ (ssuming $c2ec3ed is enabled? t2is bloc3 0ill not trigger
$$ a runtime e;ce!tion.
R.V.COLLEGE OF ENGINEERING Page @@A
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
unchecked
M
$+te sum Q ($+te#($1 H $=#O
onsole.%rite!ine(Rsum Q MGNR, sum#O
N
So, to summari8e the & checked and unchecked ke+)ords, remem$er that the default $ehavior of the
.N.T runtime is to ignore arithmetic overflo). %hen +ou )ant to selectivel+ handle discrete statements,
make use of the checked ke+)ord. *f +ou )ish to trap overflo) errors throughout +our application, ena$le
the ?checked flag. 0inall+, the unchecked ke+)ord ma+ $e used if +ou have a $lock of code )here
overflo) is accepta$le (and thus should not trigger a runtime e/ception#.
%or3ing 0it2 unsae Code
%e have three ke+)ords that allo) the & programmer to $+pass the !"9s memor+ management
scheme in order to make use of or HH st+le pointers. 0or this purpose, & provides follo)ing
operators6
C7 Pointer8Centric
O!erator
Meaning
K Used to create a pointer varia$le that represents a direct
location in memor+. !ike ?HH, this same operator is used
to represent pointer indirection.
U Used to o$tain the address of a pointer
4Y Used to access fields of a t+pe that is represented $+ a pointer
varia$le (the unsafe version of & dot operator#
V W This allo)s +ou to inde/ the slot pointed to $+ a pointer
varia$le.

R.V.COLLEGE OF ENGINEERING Page @@B
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
There )ill $e onl+ t)o situations )here )e need to use unsafe code (usage of pointers6
-ou are looking to optimi8e selected parts of +our application $+ $+passing the !". 0or
e/ample, +ou )ant to $uild a function that copies an arra+ using pointer arithmetic.
-ou are attempting to trigger the functionalit+ of a 4$ased K.dll (such as the %in@= 'P* or a
custom 4$ased K.dll# and need to create pointer varia$les to call various methods.
T2e unsae :ey0ord
%hen +ou )ish to )ork )ith pointers in &, +ou must specificall+ declare a $lock of 3unsafe5 code using
the unsafe ke+)ord6
unsa"e
M
$$ %or3 0it2 !ointer ty!es 2ere>
N
*n addition to declaring a scope of unsafe code, +ou are a$le to $uild structures, classes, t+pe mem$ers,
and parameters that are 3unsafe.5 ;ere are a fe) e/amples to gna) on6
$$ T2is entire structure is unsa"e W can be used only in an unsa"e conte;t.
pu$lic unsa"e struct Node
M
pu$lic int 2alueO
pu$lic NodeK !eftO
pu$lic NodeK "ightO
N
$$ T2is struct is sa"e? but t2e NodeB members are not. Tec2nically? you $$ may access =+alue= "rom
outside an unsa"e conte;t? but not =#e"t= and
$$ =4ig2t=.
pu$lic struct Node
R.V.COLLEGE OF ENGINEERING Page @@C
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
pu$lic int 2alueO
$$ T2ese can be accessed only in an unsa"e conte;t>
pu$lic unsa"e NodeK !eftO
pu$lic unsa"e NodeK "ightO
N
Methods (static or instance level# ma+ $e marked as unsafe as )ell. 0or e/ample, assume that +ou kno) a
given static method )ill make use of pointer logic. To ensure that this method can $e called onl+ from an
unsafe conte/t, +ou could define the method as follo)s6
unsa"e pu$lic static void SomeUnsafeode(#
M
$$ %or3 0it2 !ointer ty!es 2ere>
N
This configuration demands that the caller invoke SomeUnsafeode(# as so6
static void Main(stringVW args#
M
unsafe
M
SomeUnsafeode(#O
N
N
R.V.COLLEGE OF ENGINEERING Page @@D
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onversel+, if +ou )ould rather not force the caller to )rap the invocation )ithin an unsafe conte/t, +ou
could remove the unsafe ke+)ord from the SomeUnsafeode(# method signature and opt for the
follo)ing6
pu$lic static void SomeUnsafeode(#
M
unsafe
M
$$ %or3 0it2 !ointers 2ere>
N
N
this )ould simplif+ the call to this6
static void Main(stringVW args#
M
SomeUnsafeode(#O
N
%or3ing 0it2 t2e B and W O!erators
(nce +ou have esta$lished an unsafe conte/t, +ou are then free to $uild pointers to data t+pes using the K
operator and o$tain the address of said pointer using the U operator. Using &, the K operator is applied to
the underl+ing t+pe onl+, not as a prefi/ to each pointer varia$le name. 0or e/ample, the follo)ing code
declares t)o varia$les, $oth of t+pe intK (a pointer to an integer#6
$$ %rong synta; in C7
int Kp1, Kp=O
R.V.COLLEGE OF ENGINEERING Page @@E
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
$$ Correct synta; o" C7.
intK p1, p=O
onsider the follo)ing e/ample6
unsafe
M
int m+*ntO
$$ 1e"ine an int !ointer? and assign it t2e address o" mynt.
intK ptrToM+*nt Q Um+*ntO
$$ (ssign value o" mynt using !ointer indirection.
KptrToM+*nt Q 1=@O
$$ Print some stats.
onsole.%rite!ine(R2alue of m+*nt MGNR, m+*nt#O
onsole.%rite!ine(R'ddress of m+*nt MG6>NR, (int#UptrToM+*nt#O
N
(n Unsa"e 5and Sa"e6 S0a! *unction
,eclaring pointers to local varia$les simpl+ to assign their value (as sho)n in the previous e/ample# is
never reJuired and not altogether useful. To illustrate a more practical e/ample of unsafe code, assume
+ou )ish to $uild a s)ap function using pointer arithmetic6
unsafe pu$lic static void UnsafeS)ap(intK i, intK 7#
M
int temp Q KiO
R.V.COLLEGE OF ENGINEERING Page @@F
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Ki Q K7O
K7 Q tempO
N
But the same task can $e achieved $+ a safe mode in & as6
pu$lic static void SafeS)ap(re" int i, re" int 7#
M
int temp Q iO
i Q 7O
7 Q tempO
N
*ield (ccess via Pointers 5T2e 8X O!erator6
No) assume that +ou have defined a Point structure and )ish to declare a pointer to a Point t+pe. !ike
?HH, )hen +ou )ish to invoke methods or trigger fields of a pointer t+pe, +ou )ill need to make use of
the pointer4field access operator (4Y#. This is the unsafe version of the standard (safe# dot operator (.#. *n
fact, using the pointer indirection operator (K#, it is possi$le to dereference a pointer to (once again# appl+
the dot operator notation. heck out the follo)ing6
struct Point
M
pu$lic int /O
pu$lic int +O
pu$lic override string ToString(#
M
R.V.COLLEGE OF ENGINEERING Page @AG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
return string.0ormat(R(MGN, M1N#R, /, +#O
N
static void Main(stringVW args#
M
unsafe $$ (ccess members via !ointer.
M
Point pointO
PointK p Q UpointO
p4Y/ Q 1GGO
p4Y+ Q =GGO
onsole.%rite!ine(p4YToString(##O
N
unsafe $$ (ccess members via !ointer indirection.
M
Point pointO
PointK p Q UpointO
(Kp#./ Q 1GGO
(Kp#.+ Q =GGO
onsole.%rite!ine((Kp#.ToString(##O
N
N
N
R.V.COLLEGE OF ENGINEERING Page @A1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
T2e stac6alloc :ey0ord
*n an unsafe conte/t, +ou ma+ need to declare a local varia$le that allocates memor+ directl+ from the call
stack (and is therefore not su$7ect to .N.T gar$age collection#. To do so, & provides the stackalloc
ke+)ord, )hich is the & eJuivalent to the Salloca(# function of the runtime li$rar+. ;ere is a simple
e/ample6
unsafe
M
charK p Q stac3alloc charV=BCWO
for (int k Q GO k X =BCO kHH#
pVkW Q (char#kO
N
Pinning a Ty!e via t2e ixed :ey0ord
's +ou sa) in the previous e/ample, allocating a chunk of memor+ )ithin an unsafe conte/t ma+ $e
facilitated via the stackalloc ke+)ord. B+ the ver+ nature of this operation, the allocated memor+ is
cleaned up as soon as the allocating method has returned (as the memor+ is acJuired from the stack#.
;o)ever, assume a more comple/ e/ample. ,uring our e/amination of the 4Y operator, +ou created a
value t+pe named Point. !ike all value t+pes, the allocated memor+ is popped off the stack once the
e/ecuting scope has terminated. 0or the sake of argument, assume Point )as instead defined as a
reference t+pe6
class Point $$ No0 a class>
M
pu$lic int /O
pu$lic int +O
pu$lic override string ToString(#
M
R.V.COLLEGE OF ENGINEERING Page @A=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
return string.0ormat(R(MGN, M1N#R, /, +#O
N
N
's +ou are )ell a)are, if the caller declares a varia$le of t+pe Point, the memor+ is allocated on the
gar$age collected heap. No) the Juestion is, )hat if an unsafe conte/t )ishes to interact )ith this o$7ect
(or an+ o$7ect on the heap#P 1iven that gar$age collection can occur at an+ moment, imagine the pain of
accessing the mem$ers of Point at the ver+ point in time at )hich a s)eep of the heap is under )a+.
Theoreticall+, it is possi$le that the unsafe conte/t is attempting to interact )ith a mem$er that is no
longer accessi$le or has $een repositioned on the heap after surviving a generational s)eep ()hich is an
o$vious pro$lem#.
To lock a reference t+pe varia$le in memor+ from an unsafe conte/t, & provides the fi/ed ke+)ord. The
fi/ed statement sets a pointer to a managed t+pe and 3pins5 that varia$le during the e/ecution of
statement. %ithout fi/ed, pointers to managed varia$les )ould $e of little use, since gar$age collection
could relocate the varia$les unpredicta$l+. (*n fact, the & compiler )ill not allo) +ou to set a pointer to a
managed varia$le e/cept in a fi/ed statement.# Thus, if +ou create a Point t+pe (no) redesigned as a
class# and )ant to interact )ith its mem$ers, +ou must )rite the follo)ing code (or receive a compiler
error#6
unsafe pu$lic static void Main(#
M
Point pt Q ne) Point(#O
pt./ Q BO
pt.+ Q CO
$$ !in !t in !lace so it 0ill not be moved or EC8ed.
"i;ed (intK p Q Upt./#
M
R.V.COLLEGE OF ENGINEERING Page @A@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
$$ Use intB variable 2ere>
N
$$ !t is no0 un!inned? and ready to be EC8ed.
onsole.%rite!ine (RPoint is6 MGNR, pt#O
N
*n a nutshell, the fi/ed ke+)ord allo)s +ou to $uild a statement that locks a reference varia$le in
memor+, such that its address remains constant for the duration of the statement. To $e sure, an+ time +ou
interact )ith a reference t+pe from )ithin the conte/t of unsafe code, pinning the reference is a must.
T2e ,olatile :ey0ord
%hen +ou define a volatile varia$le, +ou are performing the converse operation of pinning a t+pe in
memor+, in that +ou are telling the runtime that it is completel+ fine to allo) an outside agent to modif+
the item in Juestion at an+ time. The s+nta/ )ould $e <
volatile int /O
Basicall+, this ke+)ord ma+ $e used to define a t+pe filed that is accessed $+ multiple threads )ithout
using the lock statement to seriali8e access.
T2e si9eo :ey0ord
's in ?HH, the & si8eof ke+)ord is used to o$tain the si8e in $+tes for a value t+pe (never a reference
t+pe#, and it ma+ onl+ $e used )ithin an unsafe conte/t. 's +ou ma+ imagine, this a$ilit+ ma+ prove
helpful )hen +ou are interacting )ith unmanaged 4$ased 'P*s. *ts usage is straightfor)ard6
unsafe
M
R.V.COLLEGE OF ENGINEERING Page @AA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
onsole.%rite!ine(RThe si8e of short is MGN.R, si<eo"(short##O
onsole.%rite!ine(RThe si8e of int is MGN.R, si<eo"(int##O
onsole.%rite!ine(RThe si8e of long is MGN.R, si<eo"(long##O
N
's si8eof )ill evaluate the num$er of $+tes for an+ S+stem.2alueT+pe4derived entit+, +ou are a$le to
o$tain the si8e of custom structures as )ell. 'ssume +ou have defined the follo)ing struct6
struct M+2alueT+pe
M
pu$lic short sO
pu$lic int iO
pu$lic long lO
N
onsole.%rite!ine(RThe si8e of M+2alueT+pe is MGN.R, si<eo"(M+2alueT+pe##O
=.@F ,uilding a Custom nde;er
's programmers, )e are ver+ familiar )ith the process of accessing discrete items contained )ithin a
standard arra+ using the inde/ operator, for e/ample6
$$ 1eclare an array o" integers.
intV W m+*nts Q M 1G, F, 1GG, A@=, FEDANO
$$ Use t2e F G o!erator to access eac2 element.
for(int 7 Q GO 7 X m+*nts.!engthO 7HH#
onsole.%rite!ine(R*nde/ MGN Q M1N R, 7, m+*ntsV7W#O
R.V.COLLEGE OF ENGINEERING Page @AB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
The & language provides the capa$ilit+ to $uild custom classes and structures that ma+ $e inde/ed 7ust
like a standard arra+. The method that provides the capa$ilit+ to access items in this manner is termed an
inde'er.
onsider the follo)ing e/ample6
$$ nde;ers allo0 you to access items in an arrayli3e "as2ion.
pu$lic class Program
M
static void Main(stringVW args#
M
$$ (ssume t2e Earage ty!e 2as an inde;er met2od.
1arage car!ot Q ne) 1arage(#O
car!otVGW Q ne) ar(R0ee0eeR, =GG#O
car!otV1W Q ne) ar(RlunkerR, FG#O
car!otV=W Q ne) ar(Rfipp+R, @G#O
$$ No0 obtain and dis!lay eac2 item using inde;er.
$$(ssume PetName? CurrS!eed are de"ined !ro!erties o" class
for (int i Q GO i X @O iHH#
M
onsole.%rite!ine(Rar num$er6 MGNR, i#O
onsole.%rite!ine(RName6 MGNR, car!otViW.PetName#O
onsole.%rite!ine(RMa/ speed6 MGNR, car!otViW.urrSpeed#O
N
N
R.V.COLLEGE OF ENGINEERING Page @AC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
=.AG Overloading O!erators
onsider the follo)ing code snippet6
int aQ=G, $Q@GO
int cQaH$O ??no) c )ill $e BG
string s1Q 3;ello5, s=Q 3%orld5O
string s@Q s1Hs=O ??no) s@ is 3;ello%orld5
The H operator could a$le to perform addition of t)o num$ers and concatenation of t)o strings $ecause,
it has $een overloaded internall+. & allo)s the programmer to overload the intrinsic operators so as to
)ork on o$7ects of user4defined?custom t+pes (ma+ $e classes or structures etc.#. This method is kno)n as
operator overloading.
To illustrate the process of overloading $inar+ operators, assume the follo)ing simple Point structure6
pu$lic struct Point
M
private int /, +O
pu$lic Point(int /Pos, int +Pos#
M
/ Q /PosO
+ Q +PosO
R.V.COLLEGE OF ENGINEERING Page @AD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
pu$lic override string ToString(#
M
return string.0ormat(RVMGN, M1NWR, this./, this.+#O
N
$$ overloaded o!erator )
pu$lic static Point o!erator ) (Point p1, Point p=#
M
return ne) Point(p1./ H p=./, p1.+ H p=.+#O
N
$$ overloaded o!erator 8
pu$lic static Point o!erator 8 (Point p1, Point p=#
M
return ne) Point(p1./ 4 p=./, p1.+ 4 p=.+#O
N
static void Main(stringVW args#
M
Point pt(ne Q ne) Point(1GG, 1GG#O
Point ptT)o Q ne) Point(AG, AG#O
onsole.%rite!ine(Rpt(ne Q MGNR, pt(ne#O
onsole.%rite!ine(RptT)o Q MGNR, ptT)o#O
R.V.COLLEGE OF ENGINEERING Page @AE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Point p1Qpt(ne H ptT)oO
Point p=Qpt(ne4ptT)oO
onsole.%rite!ine(Rp16 MGN R, p1.ToString(##O
onsole.%rite!ine(Rp=6 MGN R, p=.ToString(##O
onsole."ead!ine(#O
N
N
*n the similar manner, one can overload all $inar+, unar+ and relational operators.
=.A1 nternal 4e!resentation o" Overloaded O!erators
!ike an+ & programming element, overloaded operators are represented using specific *! instructions.
That is, an+ operator that +ou ma+ overload eJuates to a speciall+ named method in terms of *!. The
follo)ing ta$le lists fe) & operator4to4*! mapping for the & operators.
ntrinsic C7
O!erator
C#
4e!resentation
ntrinsic C7
O!erator
C# 4e!resentation
44 opS,ecrement(# L opS!ogiaclNot(#
HH opS*ncrement Binar+ H opS'ddition(#
Unar+ 4 opSUnar+Negation(# Binar+ 4 opSSu$traction(#
Unar+ H opSUnar+Plus(# Binar+ K opSMultipl+(#
X opS!essThan(# ? opS,ivision(#
R.V.COLLEGE OF ENGINEERING Page @AF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
=.A= Creating Custom Conversion 4outines
& provides t)o ke+)ords, e'plicit and implicit, that +ou can use to control ho) +our t+pes respond
during an attempted conversion. 'ssume +ou have the follo)ing structure definitions6
pu$lic struct "ectangle
M
$$ Public "or ease o" useC
$$ 2o0ever? "eel "ree to enca!sulate 0it2 !ro!erties.
pu$lic int %idth, ;eightO
pu$lic void ,ra)(#
M
onsole.%rite!ine(R,ra)ing a rect.R#O
N
pu$lic override string ToString(#
M
return string.0ormat(RV%idth Q MGNO ;eight Q M1NWR, %idth, ;eight#O
N
N
pu$lic struct SJuare
M
pu$lic int !engthO
pu$lic void ,ra)(#
R.V.COLLEGE OF ENGINEERING Page @BG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
onsole.%rite!ine(R,ra)ing a sJuare.R#O
N
pu$lic override string ToString(#
M
return string.0ormat(RV!ength Q MGNWR, !ength#O
N
$$ 4ectangles can be e;!licitly converted into S@uares.
pu$lic static e/plicit operator SJuare("ectangle r#
M
SJuare sO
s.!ength Q r.%idthO
return sO
N
N
Notice that this iteration of the "ectangle t+pe defines an e/plicit conversion operator. !ike the process of
overloading an operator, conversion routines make use of the & operator ke+)ord (in con7unction )ith
the e/plicit or implicit ke+)ord# and must $e defined as static. The incoming parameter is the entit+ +ou
are converting from, )hile the return value is the entit+ +ou are converting to6
pu$lic static e;!licit operator SJuare("ectangle r#
M...N
R.V.COLLEGE OF ENGINEERING Page @B1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
*n an+ case, the assumption is that a sJuare ($eing a geometric pattern in )hich all sides are of eJual
length# can $e o$tained from the )idth of a rectangle. Thus, +ou are free to convert a "ectangle into a
SJuare as so6
static void Main(stringVW args#
M
onsole.%rite!ine(RKKKKK 0un )ith ustom onversions KKKKK[nR#O
$$ Create a I B 1. 4ectangle.
"ectangle rectO
rect.%idth Q 1GO
rect.;eight Q BO
onsole.%rite!ine(Rrect Q MGNR, rect#O
$$ Convert 4ectangle to a 1. B 1. S@uare.
SJuare sJ Q (SJuare#rectO
onsole.%rite!ine(RsJ Q MGNR, sJ#O
onsole."ead!ine(#O
N
%hile it ma+ not $e all that helpful to convert a "ectangle into a SJuare )ithin the same scope, assume
+ou have a function that has $een protot+ped to take SJuare t+pes.
$$ T2is met2od re@uires a S@uare ty!e.
private static void ,ra)SJuare(SJuare sJ#
M
sJ.,ra)(#O
R.V.COLLEGE OF ENGINEERING Page @B=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
Using +our e/plicit conversion operation, +ou can safel+ pass in SJuare t+pes for processing6
static void Main(stringVW args#
M
...
$$ Convert 4ectangle to S@uare to invo3e met2od.
,ra)SJuare((SJuare#rect#O
N
=.A@ 1e"ining m!licit Conversion 4outines
No) )e )ill discuss implicit conversion. onsider follo)ing situation6
static void Main(stringVW args#
M
...
$$ (ttem!t to ma3e an im!licit cast
SJuare s@O
s@.!ength Q E@O
"ectangle rect= Q s@O
N
's +ou might e/pect, this code )ill not compile, given that +ou have not provided an implicit conversion
routine for the "ectangle t+pe. No) here is the catch6 it is illegal to define e/plicit and implicit
conversion functions on the same t+pe, if the+ do not differ $+ their return t+pe or parameter set. This
might seem like a limitationO ho)ever, the second catch is that )hen a t+pe defines an implicit conversion
routine, it is legal for the caller to make use of the e'plicit cast s+nta/L To clear things up, let9s add an
implicit conversion routine to the "ectangle structure using the & implicit ke+)ord (note that the
R.V.COLLEGE OF ENGINEERING Page @B@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
follo)ing code assumes the )idth of the resulting "ectangle is computed $+ multipl+ing the side of the
SJuare $+ =#6
pu$lic struct "ectangle
M
...
pu$lic static implicit operator "ectangle(SJuare s#
M
"ectangle rO
r.;eight Q s.!engthO
r.%idth Q s.!ength K =O
return rO
N
N
%ith this update, +ou are no) a$le to convert $et)een t+pes as follo)s6
static void Main(stringVW args#
M
...
$$ m!licit cast O:>
SJuare s@O
s@.!engthQ E@O
"ectangle rect= Q s@O
onsole.%rite!ine(Rrect= Q MGNR, rect=#O
,ra)SJuare(s@#O
R.V.COLLEGE OF ENGINEERING Page @BA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
$$ E;!licit cast synta; still O:>
SJuare sAO
sA.!ength Q @O
"ectangle rect@ Q ("ectangle#sAO
onsole.%rite!ine(Rrect@ Q MGNR, rect@#O
...
N
'gain, $e a)are that it is permissi$le to define e/plicit and implicit conversion routines for the same t+pe
as long as their signatures differ. Thus, +ou could update the SJuare as follo)s6
pu$lic struct SJuare
M
...
$$ Can call as: S@uare s@' Y 5S@uare6L.C or as:
$$ S@uare s@' Y L.C
pu$lic static implicit operator SJuare(int side!ength#
M
SJuare ne)SJO
ne)SJ.!ength Q side!engthO
return ne)SJO
N
$$ Must call as: int side Y 5int6myS@uareC
pu$lic static e/plicit operator int (SJuare s#
M
return s.!engthO
R.V.COLLEGE OF ENGINEERING Page @BB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
N
=.AA Summary
The purpose of this unit )as to round out +our understanding of the & programming !anguage. %e
$egan $+ e/amining a small set of lesser kno)n ke+)ords (like si8eof, checked, unsafe etc.# and during
the process came to learn ho) to )ork )ith ra) pointer t+pes. Then )e investigated various advanced
t+pe construction techniJues (inde/er, overloading and custom conversion#. 's +ou have seen, each of
these constructs can $e triggered from languages other than &, directl+ or indirectl+.
=.AB :ey0ords
The ke+)ords like c)ec0ed, unc)ec0ed, unsafe, stac0alloc, fi'ed, volatile, si$eof and loc0.
(verflo)
Pinning
*nde/er
(perator overloading
./plicit and *mplicit conversions
=.AC E;ercises
1. ./plain the purpose of c)ec0ed ke+)ord )ith an e/ample.
=. %hat do +ou mean $+ unc)ec0edP *llustrate )ith an e/ample.
@. !ist out the situations )here )e need unsafe code.
A. *llustrate the usage of unsafe ke+)ord )ith an e/ample.
B. ;o) do +ou make use of K and U operators )hile handling pointers in &P
C. %rite the functions for s)apping t)o num$ers in $oth safe mode and unsafe mode.
D. ./plain the purpose of fi'ed ke+)ord )ith an e/ample.
E. ,efine an inde/er. %rite a program to illustrate inde/er.
F. %rite a program to depict the overloading of operators H and 4.
R.V.COLLEGE OF ENGINEERING Page @BC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
1G. ./plain the usage of the ke+)ord e'plicit )ith an e/ample.
11. %rite a code segment to illustrate the )orking of implicit conversion.
Module 9
Unit &
CONTENTS:
1.C1 ($7ectives
@.= *ntroduction
@.@ 'n (vervie) of .N.T 'ssem$lies
@.A ore Benefits of 'ssem$lies
@.B Building a Single 0ile Test 'ssem$l+
@.C ./ploring the Manifest
@.D Building a Multifile 'ssem$l+
@.E Summar+
@.1G :e+)ords
@.11 ./ercises
@.1 Objectives
't the end of this lesson, the students )ill understand the follo)ing tasks in detail6
R.V.COLLEGE OF ENGINEERING Page @BD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
The concept of .N.T assem$lies
The $asics of single file and multifile assem$lies
The logical and ph+sical vie)s of assem$lies
The $enefits of using assem$lies
' single file test assem$l+
The core of manifest and *! instructions
'n e/ample for multifile assem$l+ and its construction
@.@A ntroduction
.ach of the applications developed in the previous modules are along the lines of traditional stand-alone
applications, given that all programming logic in contained )ithin a single K.e/e. (ne ma7or aspect of
.N.T is the notion of $inar+ reuse. .N.T provides the a$ilit+ to access t+pes located in e/ternal $inaries
in a language4independent manner. ;o)ever, the .N.T platform provides far greater language
integration. 0or e/ample, the .N.T platform supports cross4language inheritance (e.g., a 2isual Basic
.N.T class deriving from a & class#. To understand ho) this is achieved reJuires a deeper
understanding of assem$lies. *n this unit, +ou understand the logical and ph+sical la+out of an assem$l+.
@.@B (n Overvie0 o" .NET (ssemblies
'n assem$l+ is a versioned, self4descri$ing $inar+ (K.dll or K.e/e# containing some collection of t+pes
(classes, interfaces, structures etc.# and optional resources (images, string ta$les etc.#. ' .N.T
$inar+?assem$l+ consists of five ma7or elements6
' standard %indo)s file header (or %in@= header#
' !" header that marks the file as a managed module
*! code
T+pe metadata
The assem$l+ manifest
R.V.COLLEGE OF ENGINEERING Page @BE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
The %in@= header is 7ust a$ove identical to that of an unmanaged $inar+ and is simpl+ used to identif+
that the module is usa$le $+ the %indo)s operating s+stem. This header also identifies the t+pe of
application to $e launched. The !" header is a $lock of information that all .N.T files must support to
$e loaded $+ the !". This header defines numerous flags that ena$le the runtime to understand the
la+out of the managed file.
*! code is a platform and PU agnostic. 't runtime, the internal *! is compiled to platform and PU
specific instructions. The t+pe metadata completel+ descri$es each t+pe defined )ithin the current
assem$l+ as )ell as the set of eternal t+pes referenced $+ this assem$l+. The manifest documents each
module )ithin the assem$l+, esta$lishes the version of the assem$l+ and also documents an+ e/ternal
assem$lies referenced $+ the current assem$l+. 1iven all these elements, a .N.T assem$l+ is a
completel+ self4descri$ing entit+.
Single *ile and Multi"ile (ssemblies
'n assem$l+ can $e composed of multiple modules. ' module is a generic name for a valid .N.T file.
Thus, an assem$l+ can $e vie)ed as a unit of versioning and deplo+ment (termed as logical ,!!#. *n
most situations, an assem$l+ is composed of a single module. *n this case, there is a one4to4one
correspondence $et)een the (logical# assem$l+ and the underl+ing (ph+sical# $inar+ as sho)n in the
follo)ing diagram.
R.V.COLLEGE OF ENGINEERING Page @BF
Manifest
T+pe Metadata
*! ode
((ptional# "esources
( Single *ile (ssembly
Test.dll
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
%hen +ou create an assem$l+ that is composed of multiple files, +ou gain a more efficient )a+ to
do)nload content. 0or e/ample, assume +ou have a remote client tat is referencing a multifile assem$l+
composed of three modules, one of )hich is automaticall+ installed )ith the client. *f the client
references another of the remote modules, the .N.T runtime )ill do)nload the file on demand. *f each
module is large in si8e, then multifile assem$l+ )ill help to more e/tent.
Note that, multifile assem$lies are not literall+ linked together into a ne) (larger# file. "ather, multifile
assem$lies are logicall+ related $+ information contained in the corresponding manifest. Multifile
assem$lies contain a single manifest that ma+ $e placed in a sand4alone file, $ut is more t+picall+ $undled
directl+ into the primar+ module. The follo)ing diagram depicts a multifile assem$l+.
R.V.COLLEGE OF ENGINEERING Page @CG
Manifest ("eferences
other related files#
T+pe Metadata
*! ode
T+pe Metadata
*! ode
T+pe Metadata
*! ode
ompan+!ogo.$mp
Test.dll
Bar.netmodule
Zaa8.netmodule
( Multi"ile (ssembly
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
T0o +ie0s o" an (ssembly: P2ysical and #ogical
's +ou $egin to )ork )ith .N.T $inaries, it can $e helpful to regard an assem$l+ ($oth single file and
multifile# as having t)o conceptual vie)s. %hen +ou $uild an assem$l+, +ou are interested in the
p)ysical vie). *n this case, the assem$l+ can $e reali8ed as some num$er of files that contain +our custom
t+pes and resources as sho)n $elo)6
R.V.COLLEGE OF ENGINEERING Page @C1
Test.dll
Bar.netmodule Manifest
"esource 0iles
P2ysical +ie0 o" an (ssembly
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
's an assem$l+ consumer, +ou are t+picall+ interested in a logical vie) of the assem$l+ as sho)n $elo).
*n this case, +ou can understand an assem$l+ as a versioned collection of pu$lic t+pes that +ou can use in
+our current application.

@.@C Core ,ene"its o" (ssemblies
The assem$l+ format of files has some $enefits as e/plained $elo)6
(ssemblies Promote Code 4euse: 's +ou have $een $uilding +our console applications over the
previous chapters, it ma+ have seemed that all of the applications9 functionalit+ )as contained
)ithin the e/ecuta$le assem$l+ +ou )ere constructing. *n realit+, +our applications )ere
leveraging numerous t+pes contained )ithin the al)a+s accessi$le .N.T code li$rar+,
mscorli$.dll (recall that the & compiler references mscorli$.dll automaticall+#, as )ell as
S+stem.%indo)s.0orms.dll. 's +ou ma+ kno), a code library (also termed a class library# is a
K.dll that contains t+pes intended to $e used $+ e/ternal applications. %hen +ou are creating
e/ecuta$le assem$lies, +ou )ill no dou$t $e leveraging numerous s+stem4supplied and custom
code li$raries as +ou create the application at hand. ,o $e a)are, ho)ever, that a code li$rar+
need not take a K.dll file e/tension. *t is perfectl+ possi$le for an e/ecuta$le assem$l+ to make use
of t+pes defined )ithin an e/ternal e/ecuta$le file. *n this light, a referenced K.e/e can also $e
considered a 3code li$rar+.5 "egardless of ho) a code li$rar+ is packaged, the .N.T platform
allo)s +ou to reuse t+pes in a language4independent manner. 0or e/ample, +ou could create a
code li$rar+ in & and reuse that li$rar+ in an+ other .N.T programming language. *t is possi$le
R.V.COLLEGE OF ENGINEERING Page @C=
lasses
*nterfaces "esources
.numerations
#ogical +ie0 o" an (ssembly
,elegates
Structures
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
to not onl+ allocate t+pes across languages, $ut derive from them as )ell. ' $ase class defined in
& could $e e/tended $+ a class authored in 2isual Basic .N.T. *nterfaces defined in Pascal
.N.T can $e implemented $+ structures defined in &, and so forth. The point is that )hen +ou
$egin to $reak apart a single monolithic e/ecuta$le into numerous .N.T assem$lies, +ou achieve
a language-neutral form of code reuse.
(ssemblies Establis2 a Ty!e ,oundary: *n the module =, +ou learned a$out the formalities
$ehind .N.T namespaces. "ecall that a t+pe9s fully &ualified name is composed $+ prefi/ing the
t+pe9s namespace (e.g., S+stem# to its name (e.g., onsole#. Strictl+ speaking ho)ever, the
assem$l+ in )hich a t+pe resides further esta$lishes a t+pe9s identit+. 0or e/ample, if +ou have
t)o uniJuel+ named assem$lies (sa+, M+ars.dll and -ourars.dll# that $oth define a namespace
(ar!i$rar+# containing a class named Sportsar, the+ are considered uniJue t+pes in the .N.T
universe.
(ssemblies (re +ersionable Units: .N.T assem$lies are assigned a four4part numerical version
num$er of the form Xma/orY.XminorY. XbuildY.XrevisionY (if +ou do not e/plicitl+ provide a
version num$er using the V'ssem$l+2ersionW attri$ute, the assem$l+ is automaticall+ assigned a
version of G.G.G.G#. This num$er, in con7unction )ith an optional public 0ey value, allo)s
multiple versions of the same assem$l+ to coe/ist in harmon+ on a single machine. 0ormall+
speaking, assem$lies that provide pu$lic ke+ information are termed strongly named. Using a
strong name, the !" is a$le to ensure that the correct version of an assem$l+ is loaded on $ehalf
of the calling client.
(ssemblies (re Sel"81escribing: 'ssem$lies are regarded as self-describing in part $ecause
the+ record ever+ e/ternal assem$l+ it must have access to in order to function correctl+. Thus, if
+our assem$l+ reJuires S+stem.%indo)s. 0orms.dll and S+stem.,ra)ing.dll, the+ )ill $e
documented in the assem$l+9s manifest. "ecall that a manifest is a $lo$ of metadata that descri$es
the assem$l+ itself (name, version, e/ternal assem$lies, etc.#. *n addition to manifest data, an
assem$l+ contains metadata that descri$es the composition (mem$er names, implemented
interfaces, $ase classes, constructors and so forth# of ever+ contained t+pe. 1iven that an
assem$l+ is documented in such vivid detail, the !" does not consult the %in@= s+stem registr+
R.V.COLLEGE OF ENGINEERING Page @C@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
to resolve its location (Juite the radical departure from Microsoft9s legac+ (M programming
model#. The !" makes use of an entirel+ ne) scheme to resolve the location of e/ternal code
li$raries.
(ssemblies (re Con"igurable: 'ssem$lies can $e deplo+ed as 3private5 or 3shared.5 Private
assem$lies reside in the same director+ (or possi$l+ a su$director+# as the client application
making use of them. Shared assem$lies, on the other hand, are li$raries intended to $e consumed
$+ numerous applications on a single machine and are deplo+ed to a specific director+ termed the
.lobal Assembly #ac)e (.A##. "egardless of ho) +ou deplo+ +our assem$lies, +ou are free to
author >M!4$ased configuration files. Using these configuration files, the !" can $e instructed
to 3pro$e5 for assem$lies under a specific location, load a specific version of a referenced
assem$l+ for a particular client, or consult an ar$itrar+ director+ on +our local machine, +our
net)ork location, or a )e$4$ased U"!.
(ssemblies 1e"ine a Security Conte;t: 'n assem$l+ ma+ also contain securit+ details. Under
the .N.T platform, securit+ measures are scoped at the assem$l+ level. 0or e/ample, if
'ssem$l+' )ishes to use a class contained )ithin 'ssem$l+B, then 'ssem$l+B is the entit+ that
chooses to provide access (or not#. The securit+ constrains defined $+ an assem$l+ are e/plicitl+
listed )ithin its manifest. %hile a treatment of .N.T securit+ measures is outside the mission of
this te/t, simpl+ $e a)are that access to an assem$l+9s contents is verified using assem$l+
metadata
.
(ssemblies Enable Side8by8Side E;ecution: Perhaps the $iggest advantage of the .N.T
assem$l+ is the a$ilit+ to install and load multiple versions of the same assem$l+ on a single
machine. *n this )a+, clients are isolated from other incompati$le versions of the same assem$l+.
0urther more, it is possi$le to control )hich version of a (shared# assem$l+ should $e loaded
using application configuration files. These files are little more than a simple te/t file descri$ing
(via >M! s+nta/# the version, and specific location, of the assem$l+ to $e loaded on $ehalf of the
calling application.
R.V.COLLEGE OF ENGINEERING Page @CA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
@.@D ,uilding a Single *ile Test (ssembly
No), +ou have a $etter understanding of the $enefits provided $+ .N.T assem$lies, let9s $uild a minimal
and complete code li$rar+ using &. Ph+sicall+, this )ill $e a single file assem$l+ named ar!i$rar+.
!ogicall+, this $inar+ )ill contain a handful of pu$lic t+pes for consumption $+ other .N.T $inaries.
The design of our automo$ile li$rar+ $egins )ith an a$stract $ase class named ar that defines a num$er
of protected data mem$ers e/posed through custom properties. This class has a single a$stract method
named Tur$oBoost(# and makes use of a single enumeration (.ngineState#. ;ere is the initial definition
of the ar!i$rar+ namespace.
using S+stemO
namespace ar!i$rar+
M
$$ 4e!resents t2e state o" t2e engine.
pu$lic enum .ngineState
M
engine'live, engine,ead
N
$$ T2e abstract base class in t2e 2ierarc2y.
pu$lic a$stract class ar
M
protected string petNameO
protected short currSpeedO
R.V.COLLEGE OF ENGINEERING Page @CB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
protected short ma/SpeedO
protected .ngineState egnState Q .ngineState.engine'liveO
pu$lic a$stract void Tur$oBoost(#O
pu$lic ar(#MN
pu$lic ar(string name, short ma/, short curr#
M
petName Q nameO
ma/Speed Q ma/O
currSpeed Q currO
N
pu$lic string PetName
M
get M return petNameO N
set M petName Q valueO N
N
pu$lic short urrSpeed
M
get M return currSpeedO N
set M currSpeed Q valueO N
N
pu$lic short Ma/Speed
M
get M return ma/SpeedO N
R.V.COLLEGE OF ENGINEERING Page @CC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
pu$lic .ngineState .ngineState
M
get M return egnStateO N
N
N
N
No) assume that +ou have t)o direct descendents of the ar t+pe named Mini2an and Sportsar. .ach
overrides the a$stract Tur$oBoost(# method in an appropriate manner.
using S+stemO
using S+stem.%indo)s.0ormsO ??needed for MessageBo/ definition
namespace ar!i$rar+
M
pu$lic class Sportsar 6 ar
M
pu$lic Sportsar(#M N
pu$lic Sportsar(string name, short ma/, short curr#6 $ase (name,
ma/, curr#M N
pu$lic override void Tur$oBoost(#
M
MessageBo/.Sho)(R"amming speedLR, R0aster is $etter...R#O
R.V.COLLEGE OF ENGINEERING Page @CD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
N
pu$lic class Mini2an 6 ar
M
pu$lic Mini2an(#M N
pu$lic Mini2an(string name, short ma/, short curr#6 $ase (name,
ma/, curr#M N
pu$lic override void Tur$oBoost(#
M
$$ Minivans 2ave !oor turbo ca!abilities>
egnState Q .ngineState.engine,eadO
MessageBo/.Sho)(RTime to call '''R, R-our car is deadR#O
N
N
N
@.@E E;!loring t2e Mani"est
'fter creating a single file code li$rar+, the ne/t task )ill $e understanding assem$l+ construction. "ecall
that ever+ assem$l+ contains an associated manifest. The manifest contains $its of metadata that specif+
the name and version of the assem$l+, as )ell as a listing of all internal and e/ternal modules that
compose the assem$l+ as a )hole.
R.V.COLLEGE OF ENGINEERING Page @CE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
'dditionall+, a manifest ma+ contain cultural information (used for internationali8ation#, a corresponding
strong name (reJuired $+ shared assem$lies# and optional resource information. The follo)ing ta$le
descri$es some of the ke+ $its of functionalit+ lurking )ithin an assem$l+ manifest.
Mani"est8Centric
n"ormation
Meaning
'ssem$l+ Name ' te/t string specif+ing the assem$l+9s name.
2ersion Num$er ' ma7or and minor version num$er, and a revision and
$uild num$er.
Strong name information *n part, the strong name of an assem$l+ consists of a
pu$lic ke+ maintained $+ the pu$lisher of the assem$l+.
!ist of all modules in the
assem$l+
' hash of each module contained in the assem$l+ (in the
case of a single file assem$l+, there )ill onl+ $e a single
module listing#.
*nformation on referenced
assem$lies
' list of other assem$lies that are statisticall+ referenced
$+ the assem$l+.
.N.T a)are compilers (such as csc.e/e# automaticall+ create a manifest at compile time. *! instructions
are created )ithin the assem$l+ manifest. The follo)ing ta$le lists the core *! tokens created for a
manifest.
Mani"est Tag Meaning
R.V.COLLEGE OF ENGINEERING Page @CF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
.assem$l+ Marks the assem$l+ declaration, indicating that the file is an
assem$l+.
.file Marks additional files in a multifile assem$l+.
.class e/tern lasses e/ported $+ the assem$l+ $ut declared in another module
(onl+ used )ith a multifile assem$l+#.
.manifestres *ndicates the manifest resources, if an+.
.module Module declaration, indicating that the file is a module (i.e. a
.N.T $inar+ )ith no assem$l+ level manifest# and not the primar+
assem$l+.
.assem$l+ e/tern The assem$l+ reference indicates another assem$l+ containing
items referenced $+ this module.
.pu$licke+ ontains the actual $+tes of the pu$lic ke+.
.pu$licke+token ontains a token of the actual pu$lic ke+.
@.@F ,uilding a Multi"ile (ssembly
No) that )e have e/plored the internals of a single file assem$l+, let9s turn our attention to the process of
$uilding a multifile assem$l+. "ecall that a multifile assem$l+ )ill contain a particular K.dll or K.e/e file
that contains the assem$l+ manifest (often termed as the primary module-. 'dditionall+, multifile
R.V.COLLEGE OF ENGINEERING Page @DG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
assem$lies contain an+ num$er of K.netmodule files that are loaded on demand )hen referenced $+ an
e/ternal client. ,o $e a)are that the use of K.netmodule is simpl+ a naming convention. *f +ou )ish, +our
au/iliar+ modules could simpl+ take a K.dll file e/tension.
The 2isual Studio.N.T does not support a pro7ect )orkspace t+pe that allo)s +ou to $uild stand4alone
K.netmodule files. Therefore, +ou need to drop do)n to the level of the ra) csc.e/e compiler and specif+
the correct flags manuall+.
To keep things simple, let9s $uild some rather $asic t+pes contained )ithin a multifile assem$l+ named
'ir2ehicles. The primar+ airvehicles.dll module )ill contain *! and metadata for a single class t+pe
named ;elicopter. The related manifest (also contained in airvehicles.dll# catalogues and additional
K.netmodule file named ufos.netmodule, )hich contains another class t+pe named U0(. 'lthough $oth
class t+pes are ph+sicall+ contained in separate $inaries, +ou )ill group them into a unified namespace
named 'ir2ehicles. 0inall+, $oth classes are created using &.
To $egin, open notepad.e/e and create a trivial class definition name U0( )ithin a file named ufo.cs6
using S+stemO
namespace 'ir2ehicles
M
pu$lic class U0(
M
pu$lic void '$duct;uman(#
M
onsole.%rite!ine(3"esistance is futile5#O
N
R.V.COLLEGE OF ENGINEERING Page @D1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
N
N
To compile this class into a .N.T module, open a command prompt and issue the follo)ing command to
the & compiler6
csc.e/e ?t6module ufo.cs
*f +ou no) look in the folder containing the ufo.cs file, +ou should see a ne) file named ufo.netmodule.
Ne/t, create a ne) file named helicopter.cs6
using S+stemO
namespace 'ir2ehicles
M
pu$lic class ;elicopter
M
pu$lic void Take(ff(#
M
onsole.%rite!ine(3;elicopter taking offLL5#O
N
N
N
1iven that 'ir2ehicles.dll is the primar+ module of this multifile assem$l+, +ou )ill need to specif+ the
?t6li$rar+ flag. ;o)ever, as +ou also )ant to encode the ufo.netmodule $inar+ into the assem$l+ manifest,
+ou must also specif+ the ?addmodule flag. The follo)ing command does the trick6
R.V.COLLEGE OF ENGINEERING Page @D=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
csc ?t6li$rar+ ?addmodule6ufo.netmodule ?out6airvehicles.dll helicopter.cs
't this point, +our director+ should contain the primar+ arivehicles.dll module as )ell as the secondar+
ufo.netmodule $inaries.
@.AG Summary
This chapter drilled into the details $ehind the innocent4looking .N.T dlls and e/es located on +our
development machine. -ou $egan the 7ourne+ $+ e/amining the core concepts of the assem$l+6 !"
headers, metadata, manifests and *!. 's illustrated, .N.T supports the notion of cross4language
inheritance.
-ou have seen the concept and )orking of single file assem$l+ and multifile assem$lies. 'lso, +ou have
understood the core of manifest and *! instructions.
@.A1 :ey0ords
0ile ;eader
Module
*! (ommon *ntermediate !anguage#
Metadata
Manifest
Ph+sical 2ie) of 'ssem$l+
!ogical 2ie) of 'ssem$l+
R.V.COLLEGE OF ENGINEERING Page @D@
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
ode !i$rar+ ?lass !i$rar+
!anguage4Neutral 0orm
0ull+ Zualified Name
Pu$lic :e+ 2alue
Strongl+ named assem$l+
1lo$al 'ssem$l+ ache (1'#
Primar+ module
@.A= E;ercises
1. %hat are the ma7or elements of an assem$l+P ./plain.
=. %ith a neat diagram, e/plain the concepts of single file and multifile assem$lies.
@. %hat do +ou mean $+ logical and ph+sical vie)s of an assem$l+P ./plain.
A. Bring out the core $enefits of assem$lies.
B. %rite a & code to illustrate single file assem$l+ and e/plain the same.
C. !ist out the information contained $+ the assem$l+ manifest.
D. !ist out the core *! tokens created for a manifest.
E. ;o) do +ou $uild a multifile assem$l+P ./plain.

Module 9
Unit 9
CONTENTS:
1.C= ($7ectives
A.= *ntroduction
R.V.COLLEGE OF ENGINEERING Page @DA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
A.@ Understanding Private 'ssem$lies
A.A Pro$ing for Private 'ssem$lies (The Basics#
A.B Private 'ssem$lies and >M! onfiguration 0iles
A.C Pro$ing for Private 'ssem$lies (The ,etails#
A.D Understanding Shared 'ssem$l+
A.E Understanding Strong Names
A.F Building a Shared 'ssem$l+
A.1G Understanding ,ela+ed Signing
A.11 *nstalling?"emoving Shared 'ssem$l+
A.1= Using a Shared 'ssem$l+
A.1@ Summar+
A.1A :e+)ords
A.1B ./ercises
D.1 Objectives
't the end of this lesson, the students )ill understand6
The meaning of private assem$lies and >M! configuration
The concept of pro$ing
Shared assem$lies and its detailed stud+
Strong Names and signing
A.@A ntroduction
R.V.COLLEGE OF ENGINEERING Page @DB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
*n the previous unit, +ou have understood the concept of assem$lies. (nce +ou understand the logical and
ph+sical la+out of an assem$l+, +ou learn the distinction $et)een private and shared assem$lies as )ell as
single file and multifile assem$lies. ;ere, +ou e/amine e/actl+ ho) .N.T runtime resolves the location of
an assem$l+ and come to understand the role of the 1lo$al 'ssem$l+ ache (1'# and application
configuration files (K.config#. 's +ou )ill see, K.config files ma+ $e used $+ a client application to
interact )ith the assem$l+ $inding process.
A.@B Understanding Private (ssemblies
0ormall+ speaking, ever+ assem$l+ is deplo+ed as private or s)ared. .ach varia$le has the same
underl+ing structure (i.e., some num$er of modules and an associated manifest#. 0urthermore, each flavor
of assem$l+ provides the same kind of services (access to some num$er of pu$lic t+pes#. The real
differences $et)een a private and shared assem$l+ $oil do)n to naming conventions, versioning policies
and deplo+ment issues.
Private assem$lies are a collection of modules that is onl+ used $+ the application )ith )hich it has $een
deplo+ed. 0or e/ample, ar!i$rar+.dll seen in previous unit is a private assem$l+. %hen +ou create and
deplo+ a private assem$l+, the assumption is that the collection of t+pes is onl+ used $+ the owning
application and not shared )ith other applications on the s+stem.
Private assem$lies are reJuired to $e located )ithin the same director+ as the client application (termed
the application directory- or a su$director+ thereof. 0or e/ample, )hen +ou set a reference to the
ar!i$rar+.dll assem$l+, the 2isual Studio .N.T *,. responded $+ making a full cop+ of the assem$l+
that )as placed in +our pro7ect9s application director+. This is the default $ehavior, as private assem$lies
are assumed to $e the deplo+ment option of choice.
The resolution and loading of the private ar!i$rar+.dll happens $+ virtue of the fact that the assem$l+ is
placed in the application director+. Uninstalling (or replicating# an application that makes e/clusive use
R.V.COLLEGE OF ENGINEERING Page @DC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
of private assem$lies is a no4$rainer6 simpl+ delete (or cop+# the application folder. Unlike )ith (M
applications, +ou do not need to )orr+ a$out do8ens of orphaned registr+ settings. More important, +ou
do not need to )orr+ that the removal of private assem$lies )ill $reak an+ other applications on the
machine.
The full identit+ of a private assem$l+ consists of the friendl+ name and numerical version, $oth of )hich
are recorded in the assem$l+ manifest. The friendly name simpl+ is the name of the module that contains
the assem$l+9s manifest minus the file e/tension. 0or e/ample, if +ou e/amine the manifest of the
ar!i$rar+.dll assem$l+, +ou find the follo)ing (+our version )ill no dou$t differ#6
.assem$l+ ar!i$rar+
M
...
.ver 16G6ABA6@G1GA
N
1iven the isolated nature of a private assem$l+, it should make sense that the !" does not $other to
make use of the version num$er )hen resolving its location. The assumption is that private assem$lies do
not need to have an+ ela$orate version checking, as the client application is the onl+ entit+ that 3kno)s5
of its e/istence. 1iven this, it is (ver+# possi$le for a single machine to have multiple copies of the same
private assem$l+ in various application directories.
A.@C Probing "or Private (ssemblies5T2e ,asics6
The .N.T runtime resolves the location of a private assem$l+ using a techniJue termed probing, )hich is
much less invasive than it sounds. Pro$ing is the process of mapping an e/ternal assem$l+ reference (i.e.
V.assem$l+ e/ternW# to the correct corresponding $inar+ file. 0or e/ample, )hen the runtime reads the
follo)ing line from the Sharparlient manifest6
R.V.COLLEGE OF ENGINEERING Page @DD
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
.assembly e;tern ar!i$rar+
M]]N
a search is made in the application director+ for a file named ar!i$rar+.dll. *f a K.dll $inar+ cannot $e
located, an attempt is made to locate an K.e/e version. *f neither if these files can $e located in the
application director+, the runtime thro)s an e/ception. ;o)ever, >M! configuration files (K.config# can
$e used to instruct the runtime to pro$e in other locations $e+ond the application director+.
A.@D Private (ssemblies and MM# Con"iguration *iles
%hile it is possi$le to deplo+ a .N.T application $+ simpl+ cop+ing all reJuired assem$lies to a single
folder on the user9s hard drive, +ou )ill most likel+ )ish to define a num$er of su$directories to group
related content. 0or e/ample, assume +ou have an application director+ named 6[M+'pp that contains
Sharparlient.e/e. Under this folder might $e a su$folder named M+!i$raries that contains
ar!i$rar+.dll.
"egardless of the intended relationship $et)een these t)o directories, the !" )ill not pro$e the
M+!i$raries su$director+ unless +ou suppl+ a configuration file. onfiguration files contain various >M!
elements that allo) +ou to influence the pro$ing process. B+ 3la),5 configuration files must have the
same name as the launching application and take a K.config file e/tension, and the+ must $e deplo+ed in
the client9s application director+. Thus, if +ou )ish to create a configuration file for Sharparlient.e/e,
it must $e named Sharparlient.e/e.config.
To illustrate the process, create a ne) director+ on +our drive named M+'pp using %indo)s ./plorer.
Ne/t, cop+ Sharparlient.e/e and ar!i$rar+.dll to this ne) folder, and run the program $+ dou$le4
clicking the e/ecuta$le. -our program should run successfull+ at this point (remem$er, the assem$lies are
not registeredL#. Ne/t, create a ne) su$director+ under 6[M+'pp named M+!i$raries, and move
ar!i$rar+.dll to this location.
R.V.COLLEGE OF ENGINEERING Page @DE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Tr+ to run +our client program again. Because the !" could not locate 3ar!i$rar+5 directl+ )ithin the
application director+, +ou are presented )ith a rather nast+ unhandled 0ileNot0ound e/ception. To rectif+
the situation, create a ne) configuration file named Sharparlient.e/e.config and save it in the same
folder containing the Sharparlient.e/e application, )hich in this e/ample )ould $e 6[M+'pp. (pen
this file and enter the follo)ing content e/actl+ as sho)n ($e a)are that >M! is case sensitiveL#6
XconfigurationY
XruntimeY
Xassem$l+Binding /mlnsQRurn6schemas4microsoft4com6asm.v1RY
Xpro$ing !rivatePat2QRM+!i$rariesR?Y
X?assem$l+BindingY
X?runtimeY
X?configurationY
.N.T K.config files al)a+s open )ith a root element named XconfigurationY. The nested XruntimeY
element ma+ specif+ an Xassem$l+BindingY element, )hich nests a further element named Xpro$ingY.
The privatePath attri$ute is the ke+ point in this e/ample, as it is used to specif+ the su$directories
relative to the application director+ )here the !" should pro$e.
,o note that the Xpro$ingY element does not specif+ w)ic) assem$l+ is located under a given
su$director+. *n other )ords, +ou cannot sa+, 3ar!i$rar+ is located under the M+!i$raries su$director+,
$ut MathUtils is located under Bin su$director+.5 The Xpro$ingY element simpl+ instructs the !" to
investigate all specified su$directories for the reJuested assem$l+ until the first match is encountered.
Multiple su$directories can $e assigned to the privatePath attri$ute using a semicolon4delimited list. -ou
have no need to do so at this time, $ut here is an e/ample that informs the !" to consult the
M+!i$raries and M+!i$raries[Tests client su$directories6
R.V.COLLEGE OF ENGINEERING Page @DF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Xpro$ing !rivatePat2QRM+!i$rariesO M+!i$raries[TestsR?Y
(nce +ou9ve finished creating Sharparlient.e/e.config, run the client $+ dou$le4clicking the
e/ecuta$le in %indo)s ./plorer. -ou should find that Sharparlient.e/e e/ecutes )ithout a hitch (if
this is not the case, dou$le4check it for t+pos#.
Ne/t, for testing purposes, change the name of +our configuration file (in one )a+ or another# and attempt
to run the program once again. The client application should no) fail. "emem$er that K.config files must
$e prefi/ed )ith the same name as the related client application. B+ )a+ of a final test, open +our
configuration file for editing and capitali8e an+ of the >M! elements. (nce the file is saved, +our client
should fail to run once again (as >M! is case sensitive#.
A.@E Probing "or Private (ssemblies 5T2e 1etails6
To )rap up our discussion of private assem$lies, let9s formali8e the specific steps involved in $inding to a
private assem$l+ at runtime. 0irst, a reJuest to load an assem$l+ ma+ $e either e'plicit or implicit. 'n
implicit load reJuest occurs )henever the manifest makes a direct reference to some e/ternal assem$l+.
The e/ternal references are marked )ith V.assem$l+ e/ternW token6
??an implicit load reJuest
.assembly e;tern Car#ibrary
M
]].
N
R.V.COLLEGE OF ENGINEERING Page @EG
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
'n e/plicit load reJuest occurs programmaticall+ using the !oad(# or !oad0rom(# method of the
S+stem."eflection.'ssem$l+ class t+pe, t+picall+ for the purposes of late $inding and d+namic invocation
of t+pe mem$ers. The !oad(# method allo)s +ou to specif+ the name, version, pu$lic ke+ token and
culture information s+ntacticall+. -ou can see an e/ample of an e/plicit load reJuest in the follo)ing
code6
$$ (n e;!licit load re@uest.
'ssem$l+ asm Q 'ssem$l+.!oad(Rar!i$rar+R#O
ollectivel+, the name, version, pu$lic ke+ token and cultural information is termed as assembly
reference (or simpl+ 'sm"ef#. The entit+ in charge of locating the correct assem$l+ $ased on an 'sm"ef
is termed the assem$l+ resolver, )hich is a facilit+ of the !". *f the resolver determines the 'sm"ef
refers to a private assem$l+ (i.e. no pu$lic ke+ token is specified#, the follo)ing steps are follo)ed6
1. 0irst, the assem$l+ resolver attempts to locate the assem$l+ in the client9s application
director+ (looking for a K.dll file on the first pass, follo)ed $+ an K.e/e file#.
=. *f the 'sm"ef cannot $e resolved in looking in the application director+, the assem$l+
resolver )ill attempt to locate a configuration file in the application director+. *f a
configuration file e/ists, the runtime )ill attempt to locate the private assem$l+ using the
Xpro$ingY element.
@. *f the assem$l+ cannot $e found )ithin the application director+ (or a specified su$director+#,
the search stops here and a 0ileNot0ound e/ception is raised.
'gain, the location of a private assem$l+ is fairl+ simple to resolve.
A.@F Understanding S2ared (ssemblies
R.V.COLLEGE OF ENGINEERING Page @E1
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
No) that +ou understand ho) to deplo+ and configure a private assem$l+, +ou can $egin to e/amine the
role of a s)ared assembly. !ike a private assem$l+, a shared assem$l+ is a collection of t+pes and
(optional# resources. The most o$vious difference $et)een shared and private assem$lies is the fact that a
single cop+ of a shared assem$l+ can $e used $+ several applications on a single machine.
onsider all the applications created in this te/t that reJuired +ou to set a reference to S+stem.
%indo)s.0orms.dll. *f +ou )ere to look in the application director+ of each of these clients, +ou )ould
not find a private cop+ of this .N.T assem$l+. The reason is that S+stem.%indo)s.0orms.dll has $een
deplo+ed as a shared assem$l+. learl+, if +ou need to create a machine4)ide class li$rar+, this is the )a+
to go. 's suggested in the previous paragraph, a shared assem$l+ is not deplo+ed )ithin the same
director+ as the application making use of it. "ather, shared assem$lies are installed into the 1lo$al
'ssem$l+ ache (1'#. The 1' is located under a su$director+ of +our %indo)s director+ named
'ssem$l+ (e.g., 6[%indo)s['ssem$l+#.
A.AG Understanding Strong Names
Before +ou can deplo+ an assem$l+ to the 1', +ou must assign it a strong name, )hich is used to
uniJuel+ identif+ the pu$lisher of a given .N.T $inar+. Understand that a 3pu$lisher5 could $e an
individual programmer, a department )ithin a given compan+, or an entire compan+ at large.
*n some )a+s, a strong name is the modern da+ .N.T eJuivalent of the (M glo$all+ uniJue identifier
(1U*,# identification scheme. *f +ou have a (M $ackground, +ou ma+ recall that 'pp*,s are 1U*,s
that identif+ a particular (M application. Unlike (M 1U*, values ()hich are nothing more than 1=E4
$it num$ers#, strong names are $ased (in part# on t)o cr+ptographicall+ related ke+s (termed the public
0ey and the private 0ey#, )hich are much more uniJue and resistant to tampering than a simple 1U*,.
R.V.COLLEGE OF ENGINEERING Page @E=
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
0ormall+, a strong name is composed of a set of related data, much of )hich is specified using assem$l+4
level attri$utes6
The friendl+ name of the assem$l+ ()hich +ou recall is the name of the assem$l+ minus the file
e/tension#
The version num$er of the assem$l+ (assigned using the V'ssem$l+2ersionW attri$ute#
The pu$lic ke+ value (assigned using the V'ssem$l+:e+0ileW attri$ute#
'n optional culture identit+ value for locali8ation purposes (assigned using the
V'ssem$l+ultureW attri$ute#
'n em$edded digital signature created using a hash of the assem$l+9s contents and the private
ke+ value
To provide a strong name for an assem$l+, +our first step is to generate pu$lic?private ke+ data using
the .N.T 0rame)ork =.G S,:9s sn.e/e utilit+ ()hich +ou9ll do momentaril+#. The sn.e/e utilit+ responds
$+ generating a file (t+picall+ ending )ith the K.snk VStrong Name :e+W file e/tension# that contains data
for t)o distinct $ut mathematicall+ related ke+s, the 3pu$lic5 ke+ and the 3private5 ke+. (nce the &
compiler is made a)are of the location for +our K.snk file, it )ill record the full pu$lic ke+ value in the
assem$l+ manifest using the .pu$licke+ token at the time of compilation.
The & compiler )ill also generate a hash code $ased on the contents of the entire assem$l+ (*! code,
metadata, and so forth#. ' )as) code is a numerical value that is uniJue for a fi/ed input. Thus, if +ou
modif+ an+ aspect of a .N.T assem$l+ (even a single character in a string literal# the compiler +ields a
uniJue hash code. This hash code is com$ined )ith the private ke+ data )ithin the K.snk file to +ield a
digital signature em$edded )ithin the assem$l+9s !" header data. The process of strongl+ naming an
assem$l+ is illustrated in the follo)ing figure6
R.V.COLLEGE OF ENGINEERING Page @E@
Manifest )ith Pu$lic :e+
T+pe Metadata
*!
,igital Signature
ar!i$rar+.dll
'ssem$l+
;ash ode
,igital
Signature
Private
:e+ ,ata
+ =
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Understand that the actual private ke+ data is not listed an+)here )ithin the manifest, $ut is used onl+ to
digitall+ sign the contents of the assem$l+ (in con7unction )ith the generated hash code#. 'gain, the
)hole idea of making use of pu$lic?private ke+ cr+ptograph+ is to ensure that no t)o companies,
departments, or individuals have the same identit+ in the .N.T universe. *n an+ case, once the process of
assigning a strong name is complete, the assem$l+ ma+ $e installed into the 1'.
A.A1 ,uilding a S2ared (ssembly
To illustrate the process of assigning a strong name to an assem$l+, let us consider an e/ample. 'ssume
+ou have created a ne) & lass !i$rar+ named Shared'ssem$l+, )hich contains the follo)ing class
definition6
pu$lic class 2%Mini2an
M
private $ool /QfalseO
R.V.COLLEGE OF ENGINEERING Page @EA
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
pu$lic 2%Mini2an(#
M
MessageBo/.Sho)(3Using 2ersion =.G5, 3Shared ar5#O
N
pu$lic void Pla+Tune(#
M
MessageBo/.Sho)(3%hat a long drive ]5#O
N
pu$lic $ool Busted
M
get M return /ON
set M /QvalueON
N
N
To generate the ke+ file, +ou need to make use of the sn.e/e (strong name# utilit+. 'lthough this tool has
numerous command line options, no), +ou have to use 34k5 flag, )hich instructs the tools to generate a
ne) K.snk file that contains the pu$lic?private ke+ information.
The ne/t step is to inform the & compiler e/actl+ )here the K.snk file is located to record the pu$lic ke+
in the assem$l+ manifest. %hen +ou create a ne) & pro7ect )orkspace, +ou )ill notice that one of +our
initial pro7ect files is named 3'ssem$l+*nfo.cs5. This file contains a num$er of attri$utes that descri$e
the assem$l+ itself. (ne attri$ute that ma+ appear )ithin this file is named 'ssem$l+:e+0ile. Simpl+
update the initial empt+ value )ith a string specif+ing the location of +our K.snk file, for e/ample6
R.V.COLLEGE OF ENGINEERING Page @EB
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Vassem$l+6 (ssembly:ey*ile(\ 36[M+:e+[m+:e+.snk5#W
1iven that the version of a shared assem$l+ is of prime importance, let us specif+ a fi/ed numerical value.
*n the same 'ssem$l+*nfo.cs file, +ou )ill find another attri$ute named 'ssem$l+2ersion. *nitiall+ the
value is set of 31.G.K56
Vassem$l+6 (ssembly+ersion (31.G.K5#W
.ver+ ne) & pro7ects $egins life versioned at 1.G.K. "ecall that a .N.T version num$er is composed of
the four parts (Xma7orY.XminorY.X$uildY.XrevisionY#. Until +ou sa+ other)ise, 2S.N.T automaticall+
increments the $uild and revision num$ers as part of each compilation. To enforce a fi/ed value for the
assem$l+9s $uild version, simpl+ update accordingl+6
Vassem$l+6 'ssem$l+2ersion(31.G.G.G5#W
Using these t)o assem$l+4level attri$utes, the & compiler no) merges the necessar+ information into
the corresponding manifest to esta$lish +ou strong name, )hich can $e seen using ildasm.e/e.
A.A= Understanding 1elayed Signing
%hen +ou are $uilding +our o)n custom .N.T assem$lies, +ou are a$le to assign a strong name using
+our o)n personal K.snk file. ;o)ever, given the sensitive nature of a pu$lic?private ke+ file, don9t $e too
surprised if +our compan+?department refuses to give +ou access to the master K.snk file. This is an
o$vious pro$lem, given that )e (as developers# )ill often need to install an assem$l+ into the 1' for
testing purposes. To allo) this sort of testing ()hile not distri$uting the true K.snk file#, +ou are a$le to
make use of delayed signing. %e have no need to do so for the current ar!i$rar+.dllO ho)ever, here is an
overvie) of the process. ,ela+ed signing $egins $+ the trusted individual holding the K.snk file e/tracting
the pu$lic ke+ value from the pu$lic?private K.snk file using the 4p command4line flag of sn.e/e, to
produce a ne) file that onl+ contains the pu$lic ke+ value6
R.V.COLLEGE OF ENGINEERING Page @EC
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
sn 4p m+:e+.snk testPu$lic:e+.snk
't this point, the testPu$lic:e+.snk file can $e distri$uted to individual developers for the creation and
testing of strongl+ named assem$lies. To inform the & compiler that the assem$l+ in Juestion is making
use of dela+ed signing, the developer must make sure to set the value of the 'ssem$l+,ela+Sign attri$ute
to true in addition to specif+ing the pseudo4ke+ file as the parameter to the 'ssem$l+:e+0ile attri$ute.
;ere are the relevant updates to the pro7ect9s 'ssem$l+*nfo.cs file6
Vassem$l+6 (ssembly1elaySign(true#W
Vassem$l+6 'ssem$l+:e+0ile(\R6[M+:e+[testPublic:ey.sn3#W
(nce an assem$l+ has ena$led dela+ed signing, the ne/t step is to disa$le the signature verification
process that happens automaticall+ )hen an assem$l+ is deplo+ed to the 1'. To do so, specif+ the 4vr
flag (using sn.e/e# to skip the verification process on the current machine6
sn.e/e 4vr M+'ssem$l+.dll
(nce all testing has $een performed, the assem$l+ in Juestion can $e shipped to the trusted individual
)ho holds the 3true5 pu$lic?private ke+ file to resign the $inar+ to provide the correct digital signature.
'gain, sn.e/e provides the necessar+ $ehavior, this time using the 4r flag6
sn.e/e 4r M+'ssem$l+.dll 6[M+:e+[m+:e+.snk
To ena$le the signature verification process, the final step is to appl+ the 4vu flag6
sn.e/e 4vu M+'ssem$l+.dll
R.V.COLLEGE OF ENGINEERING Page @ED
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
Understand, of course, that if +ou (or +our compan+# onl+ $uild assem$lies intended for internal use, +ou
ma+ never need to $other )ith the process of dela+ed signing. ;o)ever, if +ou are in the $usiness of
$uilding .N.T assem$lies that ma+ $e purchased $+ e/ternal parties, the a$ilit+ to dela+ signing keep
things safe and sane for all involved.
A.A@ nstalling$4emoving S2ared (ssembly
The final step is to install Shared'ssem$l+.dll into the 1'. The simplest )a+ to install a shared
assem$l+ into the 1' is to drag4and4drop the K.dll onto the active )indo) using the %indo)s ./plorer.
'lso, the .N.T S,: provides a command line utilit+ named gacutil.e/e (the ?i flag is used to install the
$inar+.
(nce an assem$l+ has $een installed into the 1', +ou ma+ right4click a given assem$l+ icon to pull up
a propert+ page fro the $inar+, as )ell as delete the item from the 1' altogether (the 1U* eJuivalent of
suppl+ing the ?u flag )hen using gacutil.e/e#.
A.AA Using a S2ared (ssembly

No) let us make use of our shared assem$l+. reate a ne) & onsole 'pplication named
Shared'ssem$l+lient. !ike an+ e/ternal assem$l+, +ou )ill need to set a reference to the
Shared'ssem$l+ $inar+ using the 'dd "eference dialog. Understand, ho)ever that +ou do not navigate
to the 1' director+ )hen referencing shared $inaries. The 1' is a runtime entit+ that is not intended
to $e accessed directl+ during the development c+cle. "ather, navigate to the [,e$ug folder of the
Shared'ssem$l+ pro7ect using the Bro)se $utton. 't this point, e/ercise +ou 2%Mini2an as6
pu$lic class Shared'smlient
M
pu$lic static void Main(strinVW args#
R.V.COLLEGE OF ENGINEERING Page @EE
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
M
2%Mini2an vQ ne) 2%Mini2an(#O
v.Pla+Tune(#O
N
N
(nce +ou have run +our application, check out the client9s application director+ using the %indo)s
./plorer. "ecall, than )hen +ou reference a private assem$l+, the *,. automaticall+ creates a local cop+
of the assem$l+ for use $+ the client application. ;o)ever, )hen +ou reference an assem$l+ that contains
a pu$lic ke+ value, 2S.N.T )ill not generate a local cop+, given the assumption that assem$lies
supporting a pu$lic ke+ are t+picall+ shared and hence placed in the 1'.
A.AB Summary
's +ou have seen, assem$lies ma+ $e private or shared, given that private assem$lies are the default.
%hen +ou )ish to configure a shared assem$l+, +ou are making an e/plicit choice and need to generate a
corresponding strong name. Both private and shared assem$lies can $e configured declarativel+ using a
client side K.config file or alternativel+, a pu$lisher polic+ K.dll. This unit )rapped up $+ Juickl+
e/amining a set of related assem$l+4centric details6 the machine.config file, the .N.T configuration
untilit+ to simplif+ the process of $uilding >M! configuration files etc.
A.AC :ey0ords
1lo$al 'ssem$l+ ache (1'#
Private 'ssem$l+
'pplication ,irector+
0riendl+ Name
Pro$ing
onfiguration 0iles
./plicit and implicit load reJuest
R.V.COLLEGE OF ENGINEERING Page @EF
TOPICS IN ENTEPRISE ARCHITECTURE II, 5TH MCA
(10MCA53)
'ssem$l+ "eference
'ssem$l+ "esolver
Pu$lic :e+ Token
Shared 'ssem$l+
Strong names
1lo$all+ UniJue *dentifier (1U*,#
r+ptographicall+ related ke+s (pu$lic ke+ and private ke+#
,igital Signature
;ash ode
,ela+ed Signing
A.AD E;ercises
1. ./plain the concept of private assem$lies.
=. ,efine pro$ing.
@. ;o) do +ou make use of >M! configuration files to handle private assem$liesP ./plain )ith a code
segment.
A. ,efine implicit load reJuest )ith s+nta/.
B. %hen an e/plicit load reJuest occursP ./plain )ith the s+nta/.
C. !ist out the steps taken $+ resolver to identif+ a pu$lic ke+ token.
D. ./plain the concept of shared assem$lies.
E. %hat do +ou mean $+ strong namesP ./plain.
F. !ist out the entities that formulate a strong name.
1G. ./plain the process of strongl+ naming an assem$l+ )ith a diagram.
11. ;o) do +ou $uild a shared assem$l+P ./plain )ith a code segment.
1=. %hat is the need for dela+ed signingP ./plain.
1@. %ith the help of attri$utes used, e/plain the procedure for dela+ed signing.
1A. Briefl+ e/plain the procedure for using a shared assem$l+ )ith an e/ample.
R.V.COLLEGE OF ENGINEERING Page @FG

You might also like