Anda di halaman 1dari 47

.

NET Story
May2014
1 .NET Tutorial
(shibasissengupta.blogspot.com)
.NET Tutorial (shibasissengupta.blogspot.com) 2
ASP.NET

Asp.NET is successor of Microsoft's Actie serer pages (ASP) technology.

ASP.NET is a serer!si"e #eb application frame$or% "esigne" for


#eb "eelopment to pro"uce "ynamic #eb pages. &t $as "eelope" by
Microsoft to allo$ programmers to buil" "ynamic $eb sites' $eb applications
an" $eb serices.

ASP.NET is built on the (ommon )anguage *untime (()*)' allo$ing


programmers to $rite ASP.NET co"e using any supporte" .NET language
+ate ,ersion (omments
-an' 2..2 /..
April' 2..0 /./
No' 2..1 2..
No' 2..2 0..
No' 2..3 0.1
Aug' 2..4 0.1 sp/
April' 2./. 5.. Parallel e6tensions an"
other .NET 5 features
intro"uce"
Aug' 2./2 5.1 *elease" $ith ,S 2./2
.NET Tutorial (shibasissengupta.blogspot.com) 0
(ommon )anguage *untime ! ()*

The (ommon )anguage *untime (()*) is the irtual machine


component of Microsoft's .NET frame$or% an" is responsible for
managing the e6ecution of .NET programs.

&n a process %no$n as 7ust!in!time compilation' the compile" co"e is


conerte" into machine instructions that' in turn' are e6ecute" by the
computer's (P8

The ()* proi"es a""itional serices inclu"ing memory management'


type safety' e6ception han"ling'garbage collection an"
threa" management

()* is common to all ersions of the .NET frame$or%


()* ,ersion .NET ,ersion
/.. /..
/./ /./
2.. 2..' 0..' 0.1
5 5' 5.1
.NET Tutorial
(shibasissengupta.blogspot.com)
4
(ommon )anguage &nfrastructure (()&) 9 (ommon &nterme"iate )anguage ((&))

The (ommon )anguage &nfrastructure (()&) is an open specification


"eelope" by Microsoft

&n August 2...' Microsoft' :e$lett!Pac%ar"' &ntel' an" others $or%e" to


stan"ar"i;e ()&.

To implement the ()& stan"ar" re<uires conformance to one of the


supporte" an" "efine" profiles of the stan"ar"

The .NET =rame$or% is Microsoft's original commercial implementation


of the ()&

.NET (ompact =rame$or% is Microsoft's commercial implementation of


the ()& for portable "eices an" >bo6 02..

()& )anguages are computer programming languages that are use" to


pro"uce libraries an" programs that conform to the
(ommon )anguage &nfrastructure (()&) specifications

Most ()& languages compile entirely to the


(ommon &nterme"iate )anguage ((&))' an interme"iate language that
can be e6ecute" using an implementation of ()& such as the
(ommon )anguage *untime (()*' a part of the Microsoft
.NET =rame$or%)' Mono' or Portable.NET

(ommon ()& compliant languages are !

(?

A? (()& implementation of A"a)

(obra

=?

&ron*uby

&ronPython
.NET Tutorial (shibasissengupta.blogspot.com) 1
@etting Starte"

AA Namespace +eclaration
using SystemB

AA Program start class
class #elcome(SS
C
AA Main begins program e6ecution.
static oi" Main()
C
AA #rite to console
(onsole.#rite)ine(E#elcome to the (? TutorialFE)B
G
G
Namespaces are (? e<uialent of -aa pac%ages.
(ollection of namespaceAs are "istribute" generally as "ll. &n -aa $orl"' it is similar to 7ar files.
.NET Tutorial (shibasissengupta.blogspot.com) 2
,alue Types' *eference Types' aliases an" "ifference from -aa

&n particular' (? proi"es t$o typesHclass an" struct' $hich are almost the same e6cept that one is a reference type $hile
the other is a alue type

Put simply' structs are cut!"o$n classes.&magine classes that "onIt support inheritance or finali;ers' an" you hae the cut!
"o$n ersionJ the struct

Structs arealue types' $hile classes arereference types' an" the runtime "eals $ith the t$o in "ifferent $ays

#hen a alue!type instance is create"' a single space in memory is allocate" to store the alue.Primitie types such
asint'float'boolan"charare also alue types' an" $or% in the same $ay (Not StringAstring).#hen the runtime "eals
$ith a alue type' it's "ealing "irectly $ith its un"erlying "ata an" this can be ery efficient' particularly $ith primitie
types.

#ith reference types' ho$eer' an ob7ect is create" in memory' an" then han"le" through a separate referenceHrather li%e
a pointer
:o$ to chec% $hich type it is

(onsole.#rite)ine(typeof(int).&s,alueType)B AA "isplays ETrueK

#e $ill "iscuss shortly $hy string isnIt a alue type li%e integer
.NET Tutorial (shibasissengupta.blogspot.com) 3
,alue Types' *eference Types' aliases an" "ifference from -aa(cont"..)
#ith reference types' ho$eer' an ob7ect is create" in memory' an" then han"le" through a separate referenceHrather
li%e a pointer.SupposePointis a struct' an"=ormis a class.#e can instantiate each as follo$sJ
Point p/ Lne$Point()BAA Point is a MstructM
=orm f/ Lne$=orm()BAA =orm is a MclassM
&n the first case' one space in memory is allocate" forp/' $heras in the secon" case' t$o spaces are allocate"J one for
a=ormob7ect an" another for its reference (f/).&t's clearer $hen $e go about it the long $ayJ
=orm f/BAA Allocate the reference
f/ Lne$=orm()BAA Allocate the ob7ect
&f $e copy the ob7ects to ne$ ariablesJ
Point p2 L p/B
=orm f2 L f/B
p2' being a struct' becomes an in"epen"entcopyofp/' $ith its o$n separate fiel"s.Nut in the case off2' all $eIe copie"
is areference' $ith the result that bothf/an"f2point to the same ob7ect.
.NET Tutorial (shibasissengupta.blogspot.com) 4
,alue Types' *eference Types' aliases an" "ifference from -aa(cont"..)
The (ommon )anguage *untime allocates memory for ob7ects in t$o placesJ thestac%an" theheap.The stac% is a
simple first!in last!out memory structure' an" is highly efficient.#hen a metho" is ino%e"' the ()* boo%mar%s the top
of the stac%.The metho" thenpushes"ata onto the stac% as it e6ecutes.#hen the metho" completes' the ()* 7ust
resets the stac% to its preious boo%mar%HKpoppingO all the metho"Is memory allocations is one simple operationF
&n contrast' theheapcan be picture" as a ran"om 7umble of ob7ects.&ts a"antage is that it allo$s ob7ects to be allocate"
or "eallocate" in a ran"om or"er.The heap re<uires the oerhea" of amemory manageran"garbage collectorto %eep
things in or"er.
#hy string AString isnIt a alue typeP

Mainly reason is PerformanceJ Strings can be at times large an" stac% memory allocation being less (many times at /MN
only) Q it can create space an" performance issue. So its han"le" ia heap memory li%e reference types.

Een after being a reference type' (? allo$s string to be use" li%e a alue type. Nut in -aa' string comparison li%e the
belo$ one $ill compare the references an" $ill return false.

string s L EhelloEB

string t L EhelloEB

bool b L (s LL t)B $ill return true


.NET Tutorial (shibasissengupta.blogspot.com) R
,alue Types' *eference Types' aliases an" "ifference from -aa(cont"..)
NoteJ apart from ob7ect an" string' all aliases are alue types.
(ommonly As%e" Suestion Q #hat to use stringAStringP
Noth being same itIs a matter of personal choice. &n fact'
()* al$ays conerts string to System.String internally.
Alias Pointing To
ob7ect System.Tb7ect
string System.String
bool System.Noolean
byte System.Nyte
sbyte System.SNyte
short System.Short
ushort System.8short
int System.&nt02
uint System.8&nt02
long System.&nt25
ulong System.8&nt25
float System.Single
"ouble System.+ouble
"ecimal System.+ecimal
char System.(har
.NET Tutorial (shibasissengupta.blogspot.com) /.
Types
Type Si;e (&n bits)
"ecimal /24
4
byte 4
short /2
ushort /2
int 02
uint 02
long 25
ulong 25
char /2
float 02
"ouble 25
"ecimal /24
Escape Se<uence Meaning
U'
Single <uote
UO +ouble <uote
UU Nac%slash
Uo Null' not the same as (? null alue
Ua Nell
Ub Nac%space
Uf =orm fee"
Un Ne$ )ine
Ur (arriage *eturn
Ut :ori;ontal Tab
U ,ertical Tab
.NET Tutorial (shibasissengupta.blogspot.com) //
8nary Tperators
using SystemB

class 8nary
C
public static oi" Main()
C
int unary L .B
int pre&ncrementB
int pre+ecrementB
int post&ncrementB
int post+ecrementB
int positieB
int negatieB
sbyte bitNotB
bool logNotB

pre&ncrement L VVunaryB
(onsole.#rite)ine(Epre!&ncrementJ C.GE' pre&ncrement)B

pre+ecrement L !!unaryB
(onsole.#rite)ine(Epre!+ecrementJ C.GE' pre+ecrement)B

post+ecrement L unary!!B
(onsole.#rite)ine(EPost!+ecrementJ C.GE' post+ecrement)B

post&ncrement L unaryVVB
(onsole.#rite)ine(EPost!&ncrementJ C.GE' post&ncrement)B

(onsole.#rite)ine(E=inal ,alue of 8naryJ C.GE' unary)BGG
TutputJ

pre!&ncrementJ /

pre!+ecrement .

Post!+ecrementJ .

Post!&ncrementJ !/

=inal ,alue of 8naryJ .


.NET Tutorial (shibasissengupta.blogspot.com) /2
(ontrol Statements

using SystemB

class S$itchSelect

public static oi" Main()

string my&nputB

int my&ntB

beginJ

(onsole.#rite(EPlease enter a number bet$een / an" 0J E)B

my&nput L (onsole.*ea")ine()B

my&nt L &nt02.Parse(my&nput)B

AA s$itch $ith integer type

s$itch (my&nt)

case /J

(onsole.#rite)ine(EWour number is C.G.E' my&nt)B

brea%B

case 2J

(onsole.#rite)ine(EWour number is C.G.E' my&nt)B

brea%B

case 0J

(onsole.#rite)ine(EWour number is C.G.E' my&nt)B

brea%B

"efaultJ

(onsole.#rite)ine(EWour number C.G is not bet$een / an" 0.E' my&nt)B

brea%B

"eci"eJ

(onsole.#rite(EType UEcontinueUE to go on or UE<uitUE to stopJ E)B

my&nput L (onsole.*ea")ine()B

AA s$itch $ith string type

s$itch (my&nput)

case EcontinueEJ

goto beginB

case E<uitEJ

(onsole.#rite)ine(ENye.E)B

brea%B

"efaultJ

(onsole.#rite)ine(EWour input C.G is incorrect.E' my&nput)B

goto "eci"eB

G
.NET Tutorial (shibasissengupta.blogspot.com) /0
Neste" Namespace
AA Namespace +eclaration
using SystemB
namespace csharpXtutorial
C
AA Program start class
class Namespace(SS
C
AA Main begins program e6ecution.
public static oi" Main()
C
AA #rite to console
(onsole.#rite)ine(EThis is the ne$ (?
Namespace.E)B
G
G
G
AA Namespace +eclaration
using SystemB
namespace csharpXtutorial
C
namespace tutorial
C
AA Program start class
class Namespace(SS
C
AA Main begins program e6ecution.
public static oi" Main()
C
AA #rite to console
(onsole.#rite)ine(EThis is the ne$ (?
Tutorial Namespace.E)B
G
G
G
G
.NET Tutorial (shibasissengupta.blogspot.com) /5
Three pillars of Tb7ect Triente" Programming

EncapsulationJ Encapsulation inoles a single ob7ect that


contains both its "ata an" behaiors an" can hi"e $hat it
$ants from other ob7ects. &n real programming $orl" it is
achiee" by classes' access mo"ifiers etc.

&nheritance J &nheritance allo$s the concept of creating a


basic functionality $hich can be inherite" in many places
as $ell as enhance" as re<uire".

PolymorphismJ &s probably the har"est of the three


concepts an" $ill be "iscusse" in "etail in later sections.
.NET Tutorial (shibasissengupta.blogspot.com) 15
(lasses
using SystemB
AA helper class
class Tutput(lass
C
public string myStringB
AA (onstructor
public Tutput(lass(string inputString)
C
myString L inputStringB
G
AA &nstance Metho"
public oi" printString()
C
(onsole.#rite)ine(EC.GE' myString)B
G
public static String testStatic()
C
(onsole.#rite)ine(KThis is a static callsO)B
AAThe follo$ing line $ill not complie Q this refers to an instance at runtime $hich might
not be aailable
this.myStringLOStatic 8p"ateOB
Ne$ Tutput(lass.myStringLOAnother static up"ateOB AA This $ill $or%
G
AA +estructor
YTutput(lass()
C
AA Some resource cleanup routines
G
G
class E6ample(lass
C
AA Main begins program e6ecution.
public static oi" Main()
C
AA &nstance of Tutput(lass
Tutput(lass out(l L ne$ Tutput(lass(EThis is printe" by the output class.E)B
AA (all Tutput class' metho"
out(l.printString()B
AAStatic (all
Tutput(lass.testStatic()B
G
G
.NET Tutorial
(shibasissengupta.blogspot.com)
16
(lasses ((ont"..)

+esigining classes reflects the re<uirements

&n a bottom!up "esign approach many +N layer ob7ects can be


mappe" to single classes or clubbe" together as a class as per the
re<uirements.

e.g. +epartment Table an" Employee Table is lin%e" as each


employee is part of a "epartment. Tne $ay to effectiely map this
relationship to class leel is "esign a +epartment (lass an Employee
(lass an" hae a property in the +epartment class $hich can hol" a
collection of employee class ob7ects.
public (lass +epartment
C
String "ept&"B
Sring "eptNameB
String "ept:ea"Emp&"B
+ictionary ZString'Employee[ emp)istB
G
public (lass Employee
C
Public String emp&"B
Public String empNameB
Public String "ept&"B
Public String reportsTo&"B
G
.NET Tutorial
(shibasissengupta.blogspot.com)
17
Access Mo"ifiers

Access mofi"ers support a ma7or pillar of ob7ect oriente"


programming! encapsulation.
Mo"ifier +escription
public There are no restrictions on accessing public
members.
priate Access is limite" to $ithin the class
"efinition. This is the "efault access mo"ifier
type if none is formally specifie"
protecte" Access is limite" to $ithin the class
"efinition an" any class that inherits from
the class
internal Access is limite" e6clusiely to classes
"efine" $ithin the current pro7ect assembly
protecte" internal Access is limite" to the current assembly an"
types "erie" from the containing class. All
members in current pro7ect an" all members
in "erie" class can access the ariables
The "efault access for eerything in (? is Ethe most restricte" access you coul" "eclare for
that memberE.
So for e6ampleJ
namespace My(ompanyC
class Tuter
C
oi" =oo() CG
class &nner CG
GG
is e<uialent to
namespace My(ompanyC
internal class Tuter
C
priate oi" =oo() CG
priate class &nner CG
GG
.NET Tutorial (shibasissengupta.blogspot.com) /4
Access Mo"ifiers Q priate (lass

+efault access leel of a class in (? is internal

Wou can not "eclare a root leel class as priate in a na mespace

A root leel class in a namespace can only be public or internal


("efault)

The follo$ing is allo$e"


.NET Tutorial (shibasissengupta.blogspot.com) /R
(lasses Q Properties (another e6ample of encapsulation)
Tra"itional @etterASettersJ
using SystemB
public class (ustomer
C priate int mXi" L !/B
public int @et&+() C return mXi"B G
public oi" Set&+(int i") C mXi" L i"B G
priate string mXname L string.EmptyB
public string @etName() C return mXnameB G
public oi" SetName(string name) C mXname L nameB G G
public class (ustomerManager#ithAccessorMetho"sC
public static oi" Main()
C
(ustomer cust L ne$ (ustomer()B
cust.Set&+(/)B
cust.SetName(ENe$ (ustE)B
(onsole.#rite)ine(
E&+J C.G' NameJ C/GE'
cust.@et&+()' cust.@etName())B GG
Ne$ #ayJ
using SystemB
public class (ustomer C
priate int mXi" L !/B
public int &+ C get C return mXi"B G set C mXi" L alueB G G
priate string mXname L string.EmptyB
public string Name C get C return mXnameB G set C mXname L alueB G G G
public class (ustomerManager#ithPropertiesC
public static oi" Main() C
(ustomer cust L ne$ (ustomer()B
cust.&+ L /B
cust.Name L ENe$ (ustEB
(onsole.#rite)ine(
E&+J C.G' NameJ C/GE'
cust.&+'
cust.Name)B GG
Properties can be ma"e rea"!only. This is accomplishe" by haing only a get accessor in
the property implementation
.NET Tutorial (shibasissengupta.blogspot.com) 2.
(lasses ! &nheritance
using SystemB
public class Parent
C
string parentStringB
public Parent()
C
(onsole.#rite)ine(EParent (onstructor.E)B
G
public Parent(string myString)
C
parentString L myStringB
(onsole.#rite)ine(parentString)B
G
public oi" print()
C
(onsole.#rite)ine(E&'m a Parent (lass.E)B
G
G
public class (hil" J Parent
C
public (hil"() J base(E=rom +erie"E)
C
(onsole.#rite)ine(E(hil" (onstructor.E)B
G
public ne$ oi" print()
C
base.print()B
(onsole.#rite)ine(E&'m a (hil" (lass.E)B
G
public static oi" Main()
C
(hil" chil" L ne$ (hil"()B
chil".print()B
((Parent)chil").print()B
G
G
.NET Tutorial (shibasissengupta.blogspot.com) 2/
(lasses Q &nheritance ((ont"..)
TutputJ
=rom +erie"
(hil" (onstructor.
&'m a Parent (lass.
&'m a (hil" (lass.
&'m a Parent (lass.
+erie" classes can communicate $ith base classes "uring instantiation. The
colon' EJE' an" %ey$or" base call the base class constructor $ith the
matching parameter list. &f the co"e ha" not appen"e" base(E=rom
+erie"E) to the +erie" constructor' the co"e $oul" hae automatically
calle" Parent(). The first line of output sho$s the base class constructor
being calle" $ith the string E=rom +erie"E.
Sometimes you may $ant to create your o$n implementation of a metho" that
e6ists in a base class. The (hil" class "oes this by "eclaring its o$n
print() metho". The (hil" print() metho" hi"es the Parent print()
metho". The effect is the Parent print() metho" $ill not be calle"' unless
$e "o something special to ma%e sure it is calle".
&nsi"e the (hil" print() metho"' $e e6plicitly call the Parent print() metho".
This is "one by prefi6ing the metho" name $ith Ebase.E. 8sing the base
%ey$or"' you can access any of a base class public or protecte" class
members. The output from the (hil" print() metho" is on output lines 0
an" 5.
Another $ay to access base class members is through an e6plicit cast. This is "one in the last
statement of the (hil" class Main() metho". *emember that a "erie" class is a
speciali;ation of its base class. This fact allo$s us to perform a cast on the "erie"
class' ma%ing it an instance of its base class. The last line of output sho$s the Parent
print() metho" $as in"ee" e6ecute".
.NET Tutorial (shibasissengupta.blogspot.com) 22
(lasses Q &nheritance ((ont"..) ! Multiple ,s Multi!)eel

&n tra"itional concepts of TTP t$o forms of inheritance are tal%e"


about!

Multiple inheritenceJ #here one class can inherit from


multiple base classes.

Multi! )eel inheritenceJ #here once class can inherit


from only one base class.

A clear nee" of implementing multiple inheritence remains


"ebatable sub7ect oer the years.

(? only allo$s a $ea% form of multiple inheritence. All classes


$ithout an e6plicit base class is still the base class of the Tb7ect
class. Tther$ise' multiple inheritence can be implemente" using
interfaces.

Microsoft's blog <uotes on $hy multiple inheritence is generally not


allo$e" !
httpJAAblogs.ms"n.comAbAcsharpfa<AarchieA2..5A.0A.3A41122.asp6

There are ne$ $ays of implementing multiple! inheritence in (? 5..


on$ar"s !
httpJAA$$$.canerten.comAmultiple!inheritance!in!c!using!"ynamic!featuresA
.NET Tutorial (shibasissengupta.blogspot.com) 20
(lasses ! Polymorphism
Polymorphism is often referre" to as the thir" pillar of ob7ect!oriente"
programming' after encapsulation an" inheritance.Polymorphism is a
@ree% $or" that means Emany!shape"E.
using SystemB
public class +ra$ingTb7ect
C
public irtual oi" +ra$()
C
(onsole.#rite)ine(E&'m 7ust a generic "ra$ing ob7ect.E)BGG
using SystemB
public class )ine J +ra$ingTb7ect
C
public oerri"e oi" +ra$()
C
(onsole.#rite)ine(E&'m a )ine.E)BGG
public class (ircle J +ra$ingTb7ect
C
public oerri"e oi" +ra$()
C
(onsole.#rite)ine(E&'m a (ircle.E)BGG
public class S<uare J +ra$ingTb7ect
C
public oerri"e oi" +ra$()
C
(onsole.#rite)ine(E&'m a S<uare.E)BGG
using SystemB
public class +ra$+emo
C
public static int Main( )
C
+ra$ingTb7ect\] "Tb7 L ne$ +ra$ingTb7ect\5]B
"Tb7\.] L ne$ )ine()B
"Tb7\/] L ne$ (ircle()B
"Tb7\2] L ne$ S<uare()B
"Tb7\0] L ne$ +ra$ingTb7ect()B
foreach (+ra$ingTb7ect "ra$Tb7 in "Tb7)
C
"ra$Tb7.+ra$()B
G
return .B
GG
.NET Tutorial (shibasissengupta.blogspot.com) 25
Ne$ ,s Terri"e
(ase / J Nase (lass
public oi" +o&t()B
(ase / J &nherite" class
public ne$ oi" +o&t()B
(ase 2 J Nase (lass
public irtual oi" +o&t()B
(ase 2 J &nherite" class
public oerri"e oi" +o&t()B
irtualJ in"icates that a function may be oerri"en by an inheritor
oerri"eJ oerri"es the functionality of a irtual function in a base class'
proi"ing "ifferent functionality.
ne$J hi"es the original function ($hich "oesn't hae to be irtual)' proi"ing
"ifferent functionality. This shoul" only be use" $here it is absolutely
necessary
&f you're using real polymorphism you shoul" al$ays use oerri"e. The only
time $e can use ne$ on metho"s is $hen the inherite" implementation
has nothing to "o $ith the base implementation.
.NET Tutorial (shibasissengupta.blogspot.com) 21
&n"e6ers
&n"e6ers allo$ your class to be use" 7ust li%e an array. Tn the insi"e of a class' you manage a
collection of alues any $ay you $ant. These ob7ects coul" be a finite set of class
members' another array' or some comple6 "ata structure. *egar"less of the internal
implementation of the class' its "ata can be obtaine" consistently through the use of
in"e6ers.
using SystemB
AAA Zsummary[
AAA A simple in"e6er e6ample.
AAA ZAsummary[
class &nt&n"e6er
C
priate string\] my+ataB
public &nt&n"e6er(int si;e)
C
my+ata L ne$ string\si;e]B
for (int iL.B i Z si;eB iVV)
C
my+ata\i] L EemptyEB
G
G
public string this\int pos]
C
get
C
return my+ata\pos]B
G
set
C
my+ata\pos] L alueB
G
G
static oi" Main(string\] args)
C
int si;e L /.B
&nt&n"e6er my&n" L ne$ &nt&n"e6er(si;e)B
my&n"\R] L ESome ,alueEB
my&n"\0] L EAnother ,alueEB
my&n"\1] L EAny ,alueEB
(onsole.#rite)ine(EUn&n"e6er TutputUnE)B
for (int iL.B i Z si;eB iVV)
C
(onsole.#rite)ine(Emy&n"\C.G]J C/GE' i' my&n"\i])B
G
G
G
.NET Tutorial (shibasissengupta.blogspot.com) 22
Arrays
&nitiali;ing ArraysJ
int\] numbers L ne$ int\1] C/' 2' 0' 5' 1GB
string\] names L ne$ string\0] CEMattE' E-oanneE' E*obertEGB
Wou can omit the si;e of the array' li%e thisJ
int\] numbers L ne$ int\] C/' 2' 0' 5' 1GB
string\] names L ne$ string\] CEMattE' E-oanneE' E*obertEGB
Wou can also omit the ne$ operator if an initiali;er is proi"e"' li%e thisJ
int\] numbers L C/' 2' 0' 5' 1GB
string\] names L CEMattE' E-oanneE' E*obertEGB
Arrays Are Tb7ectsJ
&n (?' arrays are actually ob7ects. System.Array is the abstract base type of all
array types. Wou can use the properties' an" other class members' that
System.Array has. An e6ample of this $oul" be using the )ength
property to get the length of an array.
int\] numbers L C/' 2' 0' 5' 1GB
int )engthTfNumbers L numbers.)engthB
The System.Array class proi"es many other useful metho"sAproperties' such
as metho"s for sorting' searching' an" copying arrays.
8sing foreach on ArraysJ
int\] numbers L C5' 1' 2' /' 2' 0' !2' !/' .GB
foreach (int i in numbers)
C
System.(onsole.#rite)ine(i)B
G
.NET Tutorial (shibasissengupta.blogspot.com) 23
(ollections
=or many applications' you $ant to create an" manage groups of relate"
ob7ects. There are t$o $ays to group ob7ectsJ by creating arrays of
ob7ects' an" by creating collections of ob7ects
Arrays are most useful for creating an" $or%ing $ith a fi6e" number of
strongly!type" ob7ects
(ollections proi"e a more fle6ible $ay to $or% $ith groups of ob7ects.
8nli%e arrays' the group of ob7ects you $or% $ith can gro$ an" shrin%
"ynamically as the nee"s of the application change.
=or some collections' you can assign a %ey to any ob7ect that you put into
the collection so that you can <uic%ly retriee the ob7ect by using the %ey
&f your collection contains elements of only one "ata type' you can use
one of the classes in the System.(ollections.@eneric namespace.
System.(ollection (lasses
The classes in the System.(ollections namespace "o not store elements as specifically
type" ob7ects' but as ob7ects of type Tb7ect.
#heneer possible' you shoul" use the generic collections in the
System.(ollections.@eneric namespace or the System.(ollections.(oncurrent
namespace instea" of the legacy types in the System.(ollections namespace.
The follo$ing table lists some of the fre<uently use" classes in the System.(ollections
namespaceJ
(lass +escription
Array)ist
*epresents an array of ob7ects $hose si;e
is "ynamically increase" as re<uire"
:ashtable
*epresents a collection of %eyAalue pairs
that are organi;e" base" on the hash
co"e of the %ey
Sueue
*epresents a first in' first out (=&=T)
collection of ob7ects
Stac%
*epresents a last in' first out ()&=T)
collection of ob7ects
.NET Tutorial (shibasissengupta.blogspot.com) 24
No6ing an" 8nbo6ing
No6ing is the process of conerting a alue type to the type ob7ect or to any
interface type implemente" by this alue type. #hen the ()* bo6es a
alue type' it $raps the alue insi"e a System.Tb7ect an" stores it on the
manage" heap. 8nbo6ing e6tracts the alue type from the ob7ect. No6ing
is implicitB unbo6ing is e6plicit. The concept of bo6ing an" unbo6ing
un"erlies the (? unifie" ie$ of the type system in $hich a alue of any
type can be treate" as an ob7ect.
&n the follo$ing e6ample' the integer ariable i is bo6e" an" assigne" to ob7ect
o.
int i L /20B
AA The follo$ing line bo6es i.
ob7ect o L iB
The ob7ect o can then be unbo6e" an" assigne" to integer ariable iJ
o L /20B
i L (int)oB AA unbo6ing
&n relation to simple assignments' bo6ing an" unbo6ing are computationally
e6pensie processes. #hen a alue type is bo6e"' a ne$ ob7ect must be
allocate" an" constructe". To a lesser "egree' the cast re<uire" for
unbo6ing is also e6pensie computationally
No6ing 9 8nbo6ing in (ollectionsJ
int i L /.B
Array)ist arrlst L ne$ Array)ist()B
arrlst.A""(i)B AA No6ing occurs automatically
int 7 L (int)arrlst\.]B AA 8nbo6ing occurs
.NET Tutorial (shibasissengupta.blogspot.com) 2R
@enerics
The follo$ing bloc% of -aa co"e illustrates a problem that e6ists $hen not
using generics. =irst' it "eclares an Array)ist of type Tb7ect. Then' it a""s
a String to the Array)ist. =inally' it attempts to retriee the a""e" String
an" cast it to an &nteger.
)ist L ne$ )ist()B
.a""(EtestE)B AAbo6ing happens here
&nteger i L (&nteger).get(.)B AA *un time error
Although the co"e compiles $ithout error' it thro$s a runtime e6ception
(&nali"(astE6ception in (? an" 7aa.lang.(lass(astE6ception in -aa)
$hen e6ecuting the thir" line of co"e. This type of problem can be
aoi"e" by using generics an" is the primary motiation for using
generics.
8sing generics' the aboe co"e fragment can be re$ritten as follo$sJ
)istZString[ L ne$ )istZString[()B
.a""(EtestE)B
&nteger i L .get(.)B AA (type error) (ompile time error

System.(ollections.@eneric (lasses
Wou can create a generic collection by using one of the classes in the
System.(ollections.@eneric namespace. A generic collection is useful $hen
eery item in the collection has the same "ata type.
The follo$ing table lists some of the fre<uently use" classes of the
System.(ollections.@eneric namespaceJ
(lass +escription
+ictionaryZT^ey' T,alue[ *epresents a collection of %eyAalue pairs
that are organi;e" base" on the %ey.
)istZT[ *epresents a list of ob7ects that can be
accesse" by in"e6. Proi"es metho"s to
search' sort' an" mo"ify lists.
SueueZT[ *epresents a first in' first out (=&=T)
collection of ob7ects
Sorte")istZT^ey' T,alue[ *epresents a collection of %eyAalue pairs
that are sorte" by %ey base" on the
associate" implementation
Stac%ZT[ *epresents a last in' first out ()&=T)
collection of ob7ects.
.NET Tutorial (shibasissengupta.blogspot.com) 0.
@enerics ((ont"..)
No bo6ing A8nbo6ing *e<uire" in @enericsJ
)istZint[ list/ L ne$ )istZint[()B
list/.A""(0)B AA No bo6ing
&nterger iLlist/.get(.)B AA No unbo6ing
No6ing "oesn't happen here because the array that bac%s the )ist is T\]' not
ob7ect\]. Therefore' the runtime %no$s your items are integers an"
"oesn't nee" to bo6 them.
.NET Tutorial (shibasissengupta.blogspot.com) 0/
&nterface

An interface loo%s li%e a (lass but has no implementation

The only thing it contains are "eclarations

No fiel"s can be "efine" in an interface

&nherite" by (lassAStructs $hich must proi"e an implementation for each


interface metho"

&nterface "efines a contract

&f $e a"" a ne$ metho" to an &nterface then $e hae to trac% "o$n all the
implementations of the interface an" "efine implementation for the ne$
metho".

&nterface naming conention is to start $ith '&'


public interface &Employee C
String &+ C getB setB G
String =irstName C getB setB G
String )astName C getB setB G
String A""()B
String +elete()B G
public class EmpXfulltime2 J &Employee C
protecte" String i"B
protecte" String lnameB
protecte" String fnameB
public EmpXfulltime2() C AA AA TT+TJ A"" constructor logic here AA G
public String &+ C get C return i"B G set C i" L alueB G G
public String =irstName C get C return fnameB G set C fname L alueB G G
public String )astName C get C return lnameB G set C lname L alueB G G
public String A""() C return E=ulltime Employee E V fname V E a""e".EB G
public String +elete() C return E=ulltime Employee E V fname V E "elete".EB G G
priate oi" &nterfaceE6ampleX(lic%(ob7ect sen"er' System.EentArgs e) C
try C &Employee empB
EmpXfulltime2 emp/ L ne$ EmpXfulltime2()B
emp L emp/B emp.&+ L E2205EB
emp.=irstNameL E*ahmanE B emp.)astName L EMahmoo"iE B AAcall a"" metho" o" the
ob7ect MessageNo6.Sho$(emp.A""().ToString())B AAcall the (alculate#age metho"
MessageNo6.Sho$(emp.(alculate#age().ToString())B G
catch(E6ception e6) C MessageNo6.Sho$(e6.Message)B G G
.NET Tutorial (shibasissengupta.blogspot.com) 02
Abstract (lass

An Abstract class $ithout any implementation 7ust loo%s li%e an &nterface

An abstract class is a special %in" of class that cannot be instantiate"

&t only allo$s other classes to inherit from it but cannot be instantiate"

#hen $e create an abstract class' $e are creating a base class that might hae
one or more complete" metho"s but at least one or more metho"s are left
uncomplete" an" "eclare" abstract
public abstract class Employee C AA$e can hae fiel"s an" properties AAin the Abstract class
protecte" String i"B
protecte" String lnameB
protecte" String fnameB
public abstract String &+ C getB setB G
public abstract String =irstName C getB setB G
public abstract String )astName C getB setB G
public String A""() C return EEmployee E V i" V E E V lname V E E V fname V E a""e"EB G
public String 8p"ate() C return EEmployee E V i" V E E V lname V E E V fname V E up"ate"EB G
public abstract String (alculate#age()BG
public class EmpX=ulltime J Employee
C AAuses all the properties of the AAAbstract class therefore no AAproperties or fiel"s hereF
public EmpX=ulltime() C G
public oerri"e String &+ C get C return i"B G set C i" L alueB G G
public oerri"e String =irstName C get C return fnameB G set C fname L alueB G G
public oerri"e String )astName C get C return lnameB G set C lname L alueB G G
AAcommon metho"s that are AAimplemente" in the abstract class
public ne$ String 8p"ate() C return base.8p"ate()B G
public oerri"e String (alculate#age() C return E=ull time employee E V base.fname V E is
calculate" E V Eusing the Abstract class...EB G
priate oi" cm"AbstractE6ampleX(lic%(ob7ect sen"er' System.EentArgs e)
C Employee empB
emp L ne$ EmpX=ulltime()B
emp.&+ L E2255EB emp.=irstNameL EMariaE B emp.)astName L E*obinliusE B
MessageNo6.Sho$(emp.A""().ToString())B AAcall the (alculate#age metho"
MessageNo6.Sho$(emp.(alculate#age().ToString())B G
.NET Tutorial (shibasissengupta.blogspot.com) 00
&nterface ,s Abstract (lass
As al$ays there is a tra"e!off' an interface gies you free"om $ith regar"
to the base class' an abstract class gies you the free"om to a"" ne$
metho"s later. Q Erich @amma
Wou canIt go an" change an &nterface $ithout haing to change a lot of
other things in your co"e' so the only $ay to aoi" this $oul" be to
create a $hole ne$ &nterface' $hich might not al$ays be a goo" thing.
Abstract classes shoul" primarily be use" for ob7ects that are closely
relate"' $hereas interfaces are better at proi"ing common functionality
for unrelate" classes.
An abstract class' in contrast to interface' proi"es more structure. &t
usually "efines some "efault implementations an" proi"es some tools
useful for a full implementation. The catch is' co"e using it must use your
class as the base.&n -aA(?a' a class can inherit from only one base class.
=eature &nterface Abstract (lass
Multiple inheritance A class may inherit seeral
interfaces.
A class may inherit only
one abstract class
+efault implementation An interface cannot
proi"e any co"e' 7ust the
signature
An abstract class can
proi"e complete' "efault
co"e an"Aor 7ust the "etails
that hae to be oerri""en
Access Mo"fiers An interface cannot hae
access mo"ifiers for the
subs' functions' properties
etc eerything is assume"
as public
An abstract class can
contain access mo"ifiers
for the subs' functions'
properties
(ore ,S Peripheral &nterfaces are use" to
"efine the peripheral
abilities of a class. &n other
$or"s both :uman an"
,ehicle can inherit from a
&Moable interface.
An abstract class "efines
the core i"entity of a class
an" there it is use" for
ob7ects of the same type.
Spee" *e<uires more time to fin"
the actual metho" in the
correspon"ing classes
=ast
.NET Tutorial (shibasissengupta.blogspot.com) 05
+elegates
&n (ommon )anguage &nfrastructure (()&)' a "elegate is a form of type!
safe function pointer usually use" in an obserer pattern as a means
telling $hich metho" to call $hen an eent is triggere"
+elegate is a type $hich hol"s the metho"(s) reference in an ob7ect
8se" to call a metho" asynchronously
+eclarationJ
public "elegate typeXofX"elegate "elegateXname()
public "elegate int my"elegate(int "elar/'int "elar2)
public "elegate "ouble +elegateXPro"(int a'int b)B
class (lass/ C
static "ouble fnXPro"alues(int al/'int al2) C return al/Mal2B G
static oi" Main(string\] args) C
AA(reating the +elegate &nstance
+elegateXPro" "elTb7 L ne$ +elegateXPro"(fnXPro"alues)B
(onsole.#rite(EPlease Enter ,aluesE)B
int / L &nt02.Parse((onsole.*ea")ine())B
int 2 L &nt02.Parse((onsole.*ea")ine())B AAuse a "elegate for processing
"ouble res L "elTb7(/'2)B
(onsole.#rite)ine (E*esult JEVres)B
(onsole.*ea")ine()B G G
.NET Tutorial (shibasissengupta.blogspot.com) 01
Eents
To"ay's graphical user interface (@8&) programming mo"el uses eent!
"rien programming. A mo"ern program presents the user interface an"
$aits for the user to ta%e an action. The user might ta%e many "ifferent
actions' such as choosing among menu selections' pushing buttons'
up"ating te6t fiel"s' clic%ing icons' an" so forth. Each action causes an
eent to be raise". Tther eents can be raise" $ithout "irect user action'
such as eents that correspon" to timer tic%s of the internal cloc%' email
being receie"' file!copy operations completing' an" so forth.
An eent is the encapsulation of the i"ea that Esomething happene"E to
$hich the program must respon". Eents an" "elegates are tightly
couple" concepts because fle6ible eent han"ling re<uires that the
response to the eent be "ispatche" to the appropriate eent han"ler. An
eent han"ler is typically implemente" in (? ia a "elegate
Publishing an" Subscribing (Tbserer +esign Pattern)
&n (?' any ob7ect can publish a set of eents to $hich other classes can
subscribe. =or e6ample' a button might notify any number of intereste"
obserers $hen it is clic%e". The button is calle" the publisher because
the button publishes the (lic% eent an" the other classes are the
subscribers because they subscribe to the (lic% eent.
Note that the publishing class "oes not %no$ or care $ho (if anyone)
subscribesB it 7ust raises the eent. #ho respon"s to that eent' an" ho$
they respon"' is not the concern of the publishing class.
The publisher an" the subscribers are "ecouple" by the "elegate. The
publisher can change the reason of raising the eent an" the subscribers
can change the $ay they respon".
Eents an" +elegates (#or%ing together)
Eents in (? are implemente" $ith "elegates
The publishing class "efines a "elegate. The subscribing class "oes t$o
thingsJ first' it creates a metho" that matches the signature of the
"elegate' an" then it creates an instance of that "elegate type
#hen the eent is raise"' the subscribing class's metho"s are ino%e"
through the "elegate.
A metho" that han"les an eent is calle" an eent han"ler. Wou can
"eclare your eent han"lers
Ny conention' eent han"lers in the .NET =rame$or% al$ays return
oi" an" ta%e t$o parameters. The first parameter is the EsourceE of the
eent (that is' the publishing ob7ect). The secon" parameter is an ob7ect
"erie" from EentArgs. Wour eent han"lers $ill nee" to follo$ this
"esign pattern
.NET Tutorial (shibasissengupta.blogspot.com) 02
Eents ((ont"..)
using SystemB
using System.(ollections.@enericB
using System.)in<B
using System.Te6tB
using System.Threa"ingB
namespace E6ampleX/3X0X X X X+elegatesXan"XEentsC
public class Time&nfoEentArgs J EentArgs
C
public int hourB
public int minuteB
public int secon"B
public Time&nfoEentArgs(int hour' int minute' int secon")
C
this.hour L hourB
this.minute L minuteB
this.secon" L secon"B
G
G
AA The publisherJ the class that other classes
AA $ill obsere. This class publishes one "elegateJ
AA Secon"(hange".
public class (loc%
C
priate int hourB
priate int minuteB
priate int secon"B
AA the "elegate the subscribers must implement
public "elegate oi" Secon"(hange:an"ler(ob7ect cloc%'
Time&nfoEentArgs time&nformation)B
AA an instance of the "elegate $ith eent %ey$or" a""e"
public eent Secon"(hange:an"ler Secon"(hange"B
Eents ((ont"..)
AA set the cloc% running
AA it $ill raise an eent for each ne$ secon"
public oi" *un( )
C
for (B B )
C AA sleep /. millisecon"s
Threa".Sleep(/..)B
AA get the current time
System.+ateTime "t L System.+ateTime.No$B
AA if the secon" has change"
AA notify the subscribers
if ("t.Secon" FL secon")
C
AA create the Time&nfoEentArgs ob7ect
AA to pass to the subscriber
Time&nfoEentArgs time&nformation L
ne$ Time&nfoEentArgs("t.:our' "t.Minute' "t.Secon")B

AA if anyone has subscribe"' notify them
if (Secon"(hange" FL null)
C
Secon"(hange"(this' time&nformation)B
G
G
AA up"ate the state
this.secon" L "t.Secon"B
this.minute L "t.MinuteB
this.hour L "t.:ourB
G
G
G
.NET Tutorial
(shibasissengupta.blogspot.com)
37
Eents ((ont"..)
AA A subscriberJ +isplay(loc% subscribes to the
AA cloc%'s eents. The 7ob of +isplay(loc% is
AA to "isplay the current time
public class +isplay(loc%
C AA gien a cloc%' subscribe to
AA its Secon"(hange:an"ler eent
public oi" Subscribe((loc% the(loc%)
C the(loc%.Secon"(hange" VL
ne$ (loc%.Secon"(hange:an"ler(Time:as(hange")B
G
AA the metho" that implements the
AA "elegate" functionality
public oi" Time:as(hange"(ob7ect (loc%' Time&nfotheEentArgs ti)
C
(onsole.#rite)ine(E(urrent TimeJ C.GJC/GJC2GE'
ti.hour.ToString( )' ti.minute.ToString( )' ti.secon".ToString( ))B
G
G
AA a secon" subscriber $hose 7ob is to $rite to a file
public class )og(urrentTime
C
public oi" Subscribe((loc% the(loc%)
C the(loc%.Secon"(hange" VL
ne$ (loc%.Secon"(hange:an"ler(#rite)ogEntry)B
G
AA this metho" shoul" $rite to a file
AA $e $rite to the console to see the effect
AA this ob7ect %eeps no state
public oi" #rite)ogEntry(ob7ect the(loc%' Time&nfoEentArgs ti)
C
(onsole.#rite)ine(E)ogging to fileJ C.GJC/GJC2GE'
ti.hour.ToString( )' ti.minute.ToString( )' ti.secon".ToString( ))B
G
G
.NET Tutorial
(shibasissengupta.blogspot.com)
38
public class Tester
C
public oi" *un( )
C
AA create a ne$ cloc%
(loc% the(loc% L ne$ (loc%( )B
AA create the "isplay an" tell it to
AA subscribe to the cloc% 7ust create"
+isplay(loc% "c L ne$ +isplay(loc%( )B
"c.Subscribe(the(loc%)B
AA create a )og ob7ect an" tell it
AA to subscribe to the cloc%
)og(urrentTime lct L ne$ )og(urrentTime( )B
lct.Subscribe(the(loc%)B
AA @et the cloc% starte"
the(loc%.*un( )B
G
G
#hat is the eent %ey$or" is not use"P
The eent %ey$or" in"icates to the compiler that the "elegate can be
ino%e" only by the "efining class' an" that other classes can subscribe
to an" unsubscribe from the "elegate using only the appropriate VL an"
!L operators' respectiely
The follo$ing co"e $ill be possible if the eent %ey$or" is not use" Q
public oi" Subscribe((loc% the(loc%)
C
the(loc%.Secon"(hange" L
ne$ (loc%.Secon"(hange:an"ler(#rite)ogEntry)B
G
This assignment $ill replace the multicast "elegate. Also' other classes can
"irectly ino%e the eent $hich is not inten"e".
.NET Tutorial
(shibasissengupta.blogspot.com)
3
E6ception :an"ling
using SystemB
using System.&TB
class =inally+emo
C
static oi" Main(string\] args)
C
=ileStream outStream L nullB
=ileStream inStream L nullB
try
C
outStream L =ile.Tpen#rite(E+estination=ile.t6tE)B
inStream L =ile.Tpen*ea"(ENogus&nput=ile.t6tE)B
G
catch(E6ception e6)
C
(onsole.#rite)ine(e6.ToString())B
G
finally
C
if (outStream FL null)
C
outStream.(lose()B
(onsole.#rite)ine(EoutStream close".E)B
G
if (inStream FL null)
C
inStream.(lose()B
(onsole.#rite)ine(EinStream close".E)BGGGG
E6ception :an"ling Nest Practices
Try to $rite co"e to aoi" e6ception as much possible. e.g.
&nstea" of $riting !
int test&ntL&nt02.Parse&nt(testString)B
int test&ntL&nt02.TryParse(testString'out test&nt)B
8se tryAcatch bloc%s aroun" co"e that can potentially generate an e6ception' an" use
a finally bloc% to clean up resources' if necessary
&n catch bloc%s' al$ays or"er e6ceptions from the most specific to the least specific
Thro$ e6ceptions instea" of returning an error co"e
&n most cases' use the pre"efine" .NET =rame$or% e6ception types. &ntro"uce a ne$
e6ception class only $hen a pre"efine" one "oesn't apply
Thro$ an &nali"TperationE6ception e6ception if a property set or metho" call is not
appropriate gien the ob7ect's current state
Thro$ an ArgumentE6ception e6ception or a class "erie" from ArgumentE6ception
if inali" parameters are passe"
=or most apps' "erie custom e6ceptions from the E6ception class. +eriing from the
ApplicationE6ception class "oesn't a"" significant alue
En" e6ception class names $ith the $or" EE6ceptionE. =or e6ampleJ
public class My=ileNot=oun"E6ception J E6ception
C
G
.NET Tutorial 4! .NET Tutorial
(shibasissengupta.blogspot.com)
+esign Patterns
&n soft$are engineering' a "esign pattern is a general reusable solution to a
commonly occurring problem $ithin a gien conte6t
A "esign pattern is not a finishe" "esign that can be transforme" "irectly into source
or machine co"e. &t is a "escription or template for ho$ to sole a problem that can
be use" in many "ifferent situations
+esign patterns gaine" popularity in computer science after the boo%
+esign PatternsJ Elements of *eusable Tb7ect!Triente" Soft$are $as publishe" in
/RR5 by the so!calle" E@ang of =ourE (@amma et al.)' $hich is fre<uently abbreiate"
as E@T=O
+esign patterns $ere mainly groupe" into the follo$ing categories !
(reation PatternsJ +esign patters that "eal $ith ob7ect creation
mechanisms.(reational "esign patterns are further categori;e" into Tb7ect!
creational patterns an" (lass!creational patterns.&n greater "etails' Tb7ect!
creational patterns "efer part of its ob7ect creation to another ob7ect' $hile
(lass!creational patterns "efer its ob7ect creation to subclasses. =ie $ell
%no$n creation patterns are !
Abstract =actory pattern
Nuil"er pattern
=actory Metho" Pattern
Prototype Pattern
Singleton Pattern
Structural PatternsJ Structrual patterns are meant to ease the "esign by i"entifying a simple
$ay to reali;e relationships bet$een entities. E6amples !
A"apter Pattern
Aggregate Pattern
Nri"ge Pattern
Nehaioural +esign PatternsJ These patterns i"entify common communication patterns
bet$een ob7ects. Ny "oing so' these patterns increase fle6ibility in carrying out this
communication. E6amples !
(hain of *esponsibility
(omman" Pattern
Tbserer Pattern
Sche"ules Tas% Pattern
&terator Pattern
Protocol Stac%
.NET Tutorial 41 .NET Tutorial
(shibasissengupta.blogspot.com)
=actory Pattern
The factory pattern metho" is a popularly use" "esign pattern an" it is ery useful to restrict
clients from %no$ing the actual business logic metho"s' it is useful to create a "ecouple"
system' an" it is useful to eliminate ob7ect creation in a client enironment.
=or e6ample $e hae a scenario $here base" on user input $e nee" to call particular class
metho"s. & hae a customer input screen. :e enters his choice $hether they $ant to buy a
bi%e or a car. Normally $e get input from the user an" base" on that $ill create an ob7ect in
the client class an" call those metho"s li%e belo$.
&f (choice LL K(arO)
C
AA call car class an" itIs metho"s
(ar c L ne$ car()B
c.buy()B
G
&f (choice LL Kbi%eO)
C
AA call bi%e class an" itIs metho"s
Ni%e b L ne$ Ni%e()B
b.buy()
G
&n case in future if there is any other ehicle a""e" then $e nee" to change the client
functionality. #orse' if there are many client classes using these classes all of them might
neee" to be up"ate".
public interface &(hoice C string Nuy()B G
A ne$ class $ill be a""e" an" this class $e $ill be calle" factory class. This class sits bet$een
the client class an" the business class an" base" on user choice it $ill return the respectie
class ob7ect through the interface.
AA AA =actory (lass AA
public class =actory(hoice C
static public &(hoice get(hoiceTb7(string c(hoice) C
&(hoice ob7(hoiceLnullB
if (c(hoice.To)o$er() LL EcarE) C ob7(hoice L ne$ cls(ar()B G
else if (c(hoice.To)o$er() LL Ebi%eE) C ob7(hoice L ne$ clsNi%e()B G
else C ob7(hoice L ne$ &nali"(hoice()B G return ob7(hoiceB G G
AANusiness classes Ni%eAA
public class clsNi%eJ&(hoice
C ?region &(hoice Members public string Nuy() C return (EWou choose Ni%eE)B G ?en"region G
AANusiness (lass (ar
public class cls(arJ&(hoice C &(hoice Members public string Nuy() C return (EWou choose
(arE)B G G
=rom the client class call the factory class ob7ect an" it $ill return the interface ob7ect.
Through the interface ob7ect $e $ill call the respectie metho"
AA(lient class
&(hoice ob7&noiceB
ob7&noice L =actory(lass.=actory(hoice.get(hoiceTb7(t6t(hoice.Te6t.Trim())B
MessageNo6.Sho$(ob7&noice.Nuy())B
&n future if $e nee" to a"" a ne$ ehicle then there is no nee" to change the client class'
simply return that ob7ect using the factory class.
.NET Tutorial 4" .NET Tutorial
(shibasissengupta.blogspot.com)
Singleton Pattern
Singleton Patterns are implemente" $hen there is a nee" for only instance of a class
throughout the application.
(ommonly use" in )ogging' shareable serices etc. Multiple logger instances can slo$ "o$n
the system performance Q using singleton pattern in these case is a perfect e6ample.
public seale" class Nusiness*ulesManager
C
priate Nusiness*ulesManager()CG
public static Nusiness*ulesManager @et&nstance
C
get
C
return Nusiness*ulesManager&mpl.instanceB
G
G
public oi" +isplay*ules()
C
(onsole.#rite)ine(ESingle instance ob7ectE)B
G
priate class Nusiness*ulesManager&mpl
C
static Nusiness*ulesManager&mpl()
CG
internal static rea"only Nusiness*ulesManager instance L ne$ Nusiness*ulesManager()BGG
priate static oi" Singleton()
C
Nusiness*ulesManager business*ulesManager L Nusiness*ulesManager.@et&nstanceB
business*ulesManager.+isplay*ules()B
(onsole.*ea"^ey()B
G
The class is mar%e" as seale" $hich means that inheritance is not allo$e" for it
a priate neste" class is use" to proi"e access to the instance that must only e6ist once in the
application.
This neste" class has a static "efault constructor an" an internal static rea"!only instance of
the ob7ect. Tnly the container class has access to the instance
.NET Tutorial 43 .NET Tutorial
(shibasissengupta.blogspot.com)
A"apter Pattern
The A"apter +esign Pattern allo$s you to ma%e an e6isting class $or% $ith other e6isting
class libraries $ithout changing the co"e of the e6isting class.
Say' there is an Employee (lass $hich implements the &employee interface. The organi;ation
tree is constructe" using this Employee class. Wou are then gien the (onsultant class an"
you nee" to plug this (onsultant class into the organi;ation tree. The (onsultant class is the
A"aptee.
The $ay to "o this is by creating the a"apter class name" the EmployeeA"apter.
using System.(ollections.@enericB
class Program C
static oi" Main(string\] args) C
)istZiemployee[ list L ne$ )istZiemployee[()B
list.A""(ne$ Employee(ETomE))B
list.A""(ne$ Employee(E-erryE))B
list.A""(ne$ EmployeeA"apter(ne$ (onsultant(ENrunoE)))B
AAMMM (o"e belo$ from the e6isting library "oes not nee" to be change" MMM
Sho$:appiness(list)B G

AAMMM (o"e belo$ from the e6isting library "oes not nee" to be change" MMM
static oi" Sho$:appiness()istZiemployee[ list) C foreach (&Employee i in list)
i.Sho$:appiness()B G G
AAfrom the e6isting library' "oes not nee" to be change"
public interface &Employee C oi" Sho$:appiness()B G
public class Employee J &Employee C
priate string nameB
public Employee(string name) C this.name L nameB G
oi" &Employee.Sho$:appiness() C (onsole.#rite)ine(EEmployee E V this.name V E sho$e"
happinessE)B G G
AAe6isting class "oes not nee" to be change"
public class (onsultant
C priate string nameB
public (onsultant(string name) C this.name L nameB G
protecte" oi" Sho$Smile() C (onsole.#rite)ine(E(onsultant E V this.name V E sho$e"
smileE)B G G
public class EmployeeA"apter J &Employee C
(onsultant XconsultantB
public EmployeeA"apter((onsultant consultant) C Xconsultant L consultantB G
oi" &Employee.Sho$:appiness()
C consultant.Sho$Smile()B AAcall the a"aptee (onsultant class G G
.NET Tutorial 44 .NET Tutorial
(shibasissengupta.blogspot.com)
Tbserer Pattern
Many a times' $e nee" one part of our application up"ate" $ith the status of
some other part of the application. Tne $ay to "o this is to hae the receier
part repeate"ly chec% the sen"er for up"ates' but this approach has t$o main
problems. =irst' it ta%es up a lot of (P8 time to chec% the ne$ status an"
secon"' "epen"ing on the interal $e are chec%ing for change $e might not get
the up"ates Eimme"iatelyE.
This problem has one easy solution i.e. Tbserer Pattern.
Eents an" "elegates uses the oberserer pattern in (?
Accor"ing to MS+N M,( is a fun"amental "esign pattern for the separation
of user interface logic from business logic.
.NET Tutorial 45 .NET Tutorial
(shibasissengupta.blogspot.com)
&terator Pattern
Proi"es a $ay to access the elements of an aggregate ob7ect se<uentially
$ithout e6posing its un"erlying representation
EEnumerate"E means to count off the members of a setAcollectionAcategory one
by one (usually in or"er' usually by name).
An enumerable then is an ob7ect that can step through a series of other ob7ects
one by one.
Wou use the iterator pattern most li%ely in your eery "ay $or% maybe $ithout
being a$are ofJ
)istZstring[ all L ne$ )istZstring[() C EyouE' EmeE' EeeryoneE GB
...
foreach(string $ho in all)
C
(onsole.#rite)ine(E$hoJ C.GFE' $ho)B
G
Nehin" the scenes' the foreach loop translates into !
using (ar it L all.@etEnumerator())
$hile (it.MoeNe6t())
C
string $ho L it.(urrentB ...G
A class that can be use" in a foreach loop must proi"e a &EnumeratorZT[
@etEnumerator() C ... G metho". The metho" name is resere" for that purpose.
Some classes may also proi"e the non!generic &Enumerator @etEnumerator() C
... G metho". This is from the ol"er "ays $here there $ere no generics yet.
So' the core of the (? implementation of the &terator Pattern is the
@etEnumerator() metho"
#hat is an &teratorP
An iterator proi"es a means to iterate (i.e. loop) oer some items. The
se<uence of elements is gien by the implementations of the
&EnumeratorA&EnumeratorZT[ interfacesJ
namespace System.(ollections
C
public interface &Enumerator
C
ob7ect (urrent C getB G
bool MoeNe6t()B
oi" *eset()B
G
G
.NET Tutorial 46 .NET Tutorial
(shibasissengupta.blogspot.com)
&terator Pattern ((ont"..)
namespace System.(ollections.@eneric
C
public interface &EnumeratorZout T[ J &+isposable' &Enumerator
C
T (urrent C getB G
G
G
The pattern is basically gien by MoeNe6t() an" (urrent. The semantics is
that one has to first call MoeNe6t() to get to the first element. &f MoeNe6t()
returns false' then there is no more element. (urrent returns the current
element. Wou are not suppose" to call (urrent if the precee"ing MoeNe6t()
returne" false.
The MoeNe6t() gies the ne6t element in the se<uence of elements ! $hat
eer that se<uence is' e.g. from first to last' or sorte" by some criteria' or
ran"om' etc.
#e %no$ no$ ho$ to apply the iterator pattern (e.g. in a foreach loop) an"
that this is possible for all classes that proi"e the aboe mentione"
@etEnumerator() metho" (the iterator).
.NET Tutorial 47 .NET Tutorial
(shibasissengupta.blogspot.com)