S T A R T IN G O U T W IT H
V is u a l C # ®
F o u r t h
E d i t i o n
T o n y G a d d is
H a y w o o d C o m m u n it y C o lle g e
Bo sto n
C o lu m b u s In d ia n a p o lis N e w Y o r k
S a n F r a n c is c o
Ho b o k en
Amsterd am Cap e To wn
Du b ai Lo n d o n
M a d r id
M ila n
M u n ic h
P a r is M o n tr e a l T o r o n to
D e lh i M e x ic o C ity S a o P a u lo
S y d n e y H o n g K o n g S e o u l S in g a p o r e T a ip e i T o k y o
E d ito r ia l D ir e c to r : M a r c ia H o r to n
A c q u is itio n s E d ito r : M a tt G o ld s te in
E d ito r ia l A s s is ta n t: K r is ty A la u r a
V P o f M a r k e tin g : C h r is ty L e s k o
D ir e c to r o f F ie ld M a r k e tin g : T im G a llig a n
P r o d u c t M a r k e tin g M a n a g e r : B r a m v a n K e m p e n
F ie ld M a r k e tin g M a n a g e r : D e m e tr iu s H a ll
M a r k e tin g A s s is ta n t: J o n B r y a n t
D ir e c to r o f P r o d u c t M a n a g e m e n t: E r in G r e g g
T e a m L e a d P r o d u c t M a n a g e m e n t: S c o tt D is a n n o
P r o g r a m M a n a g e r : C a r o le S n y d e r
P r o d u c tio n P r o je c t M a n a g e r : C a m ille T r e n ta c o s te
P r o c u r e m e n t M a n a g e r : M a r y F is c h e r
S e n io r S p e c ia lis t, P r o g r a m P la n n in g a n d
S u p p o r t: M a u r a Z a ld iv a r -G a r c ia
M a n a g e r , R ig h ts M a n a g e m e n t: R a c h e l Y o u d e lm a n
S e n io r P r o je c t M a n a g e r , R ig h ts
M a n a g e m e n t: W illia m O p a lu c h
C o v e r A r t: C r e a tiv e C r o p /D ig ita lV is io n /G e tty Im a g e s ;
K o v a le v a _ k a /F o to lia
C o v e r D e s ig n : J o y c e W e lls
C o p y r ig h t © 2 0 1 7 , 2 0 1 4 , 2 0 1 2 b y P e a r s o n E d u c a tio n , In c . o r its a ffilia te s . A ll R ig h ts R e s e r v e d . P r in te d in th e U n ite d S ta te s o f
A m e r ic a . T h is p u b lic a tio n is p r o te c te d b y c o p y r ig h t, a n d p e r m is s io n s h o u ld b e o b ta in e d fr o m th e p u b lis h e r p r io r to a n y
p r o h ib ite d r e p r o d u c tio n , s to r a g e in a r e tr ie v a l s y s te m , o r tr a n s m is s io n in a n y fo r m o r b y a n y m e a n s , e le c tr o n ic , m e c h a n ic a l,
p h o to c o p y in g , r e c o r d in g , o r o th e r w is e . F o r in fo r m a tio n r e g a r d in g p e r m is s io n s , r e q u e s t fo r m s a n d th e a p p r o p r ia te c o n ta c ts
w ith in th e P e a r s o n E d u c a tio n G lo b a l R ig h ts & P e r m is s io n s d e p a r tm e n t, p le a s e v is it w w w .p e a r s o n e d .c o m /p e r m is s io n s .
A c k n o w le d g e m e n ts o f th ir d p a r ty c o n te n t a p p e a r th e s a m e p a g e a s th e c o n te n t, w h ic h c o n s titu te s a n e x te n s io n o f th is c o p y r ig h t
p a g e . U n le s s o th e r w is e in d ic a te d h e r e in , a n y th ir d -p a r ty tr a d e m a r k s th a t m a y a p p e a r in th is w o r k a r e th e p r o p e r ty o f th e ir
r e s p e c tiv e o w n e r s a n d a n y r e fe r e n c e s to th ir d -p a r ty tr a d e m a r k s , lo g o s o r o th e r tr a d e d r e s s a r e fo r d e m o n s tr a tiv e o r d e s c r ip tiv e
p u r p o s e s o n ly . S u c h r e fe r e n c e s a r e n o t in te n d e d to im p ly a n y s p o n s o r s h ip , e n d o r s e m e n t, a u th o r iz a tio n , o r p r o m o tio n o f
P e a r s o n ’s p r o d u c ts b y th e o w n e r s o f s u c h m a r k s , o r a n y r e la tio n s h ip b e tw e e n th e o w n e r a n d P e a r s o n E d u c a tio n , In c . o r its
a ffilia te s , a u th o r s , lic e n s e e s o r d is tr ib u to r s .
T h e p r o g r a m s a n d a p p lic a tio n s p r e s e n te d in th is b o o k h a v e b e e n in c lu d e d fo r th e ir in s tr u c tio n a l v a lu e . T h e y h a v e b e e n te s te d
w ith c a r e , b u t a r e n o t g u a r a n te e d fo r a n y p a r tic u la r p u r p o s e . T h e p u b lis h e r d o e s n o t o ffe r a n y w a r r a n tie s o r r e p r e s e n ta tio n s ,
n o r d o e s it a c c e p t a n y lia b ilitie s w ith r e s p e c t to th e p r o g r a m s o r a p p lic a tio n s .
L ib r a r y o f C o n g r e s s C a ta lo g in g -in -P u b lic a tio n D a ta
N a m e s : G a d d is , T o n y .
T itle : S ta r tin g o u t w ith V is u a l C # / T o n y G a d d is , H a y w o o d C o m m u n ity C o lle g e .
D e s c r ip tio n : F o u r th e d itio n . | B o s to n : P e a r s o n , 2 0 1 7 . | In c lu d e s in d e x .
Id e n tifie r s : L C C N 2 0 1 5 0 4 8 6 8 5 | IS B N 9 7 8 0 1 3 4 3 8 2 6 0 9 | IS B N 0 1 3 4 3 8 2 6 0 9
S u b je c ts : L C S H : C # (C o m p u te r p r o g r a m la n g u a g e ) | V is u a l p r o g r a m m in g la n g u a g e s
(C o m p u te r s c ie n c e )
C la s s ific a tio n : L C C Q A 7 6 .7 3 .C 1 5 4 G 3 3 2 0 1 7 | D D C 0 0 5 .1 3 /3 — d c 2 3 L C r e c o r d a v a ila b le a t
h ttp ://lc c n .lo c .g o v /2 0 1 5 0 4 8 6 8 5
1 0 9 8 7 6 5 4 3 2 1
ISBN 1 0 :
0 -1 3 -4 3 8 2 6 0 -9
ISBN 1 3 : 9 7 8 -0 -1 3 -4 3 8 2 6 0 -9
L o c a tio n s o f V id e o N o t e s
w w w .p e a r s o n h ig h e r e d .c o m / c s -r e s o u r c e s
C h a p t e r 1
VideoNot e
T u t o r ia l 1 - 1 : S t a r t in g V is u a l S t u d io a n d S e t t in g
U p t h e E n v ir o n m e n t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T u t o r ia l 1 - 2 : S t a r t in g a N e w V is u a l C # P r o je c t . . . . . . . . . . . . . .
T u t o r ia l 1 - 3 : S a v in g a n d C lo s in g a P r o je c t . . . . . . . . . . . . . . . . .
T u t o r ia l 1 - 4 : O p e n in g a n E x is t in g P r o je c t . . . . . . . . . . . . . . . . . .
T u t o r ia l 1 - 5 : G e t t in g F a m ilia r w it h t h e V is u a l
S t u d io E n v ir o n m e n t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2 8
3 0
3 2
4 0
4 1
C h a p t e r 2
T u t o r i a l 2 - 1 : C r e a t i n g t h e G U I f o r t h e Hello World A p p l i c a t i o n . . . 6 1
T u t o r i a l 2 - 2 : W r i t i n g C o d e f o r t h e Hello World A p p l i c a t i o n . . . . 7 5
T u t o r i a l 2 - 3 : C r e a t i n g t h e La ngua ge Tra nsla tor A p p l i c a t i o n . . . . 8 6
T u t o r i a l 2 - 4 : C r e a t i n g t h e Fla gs A p p l i c a t i o n . . . . . . . . . . . . . . . . 9 4
T u t o r i a l 2 - 5 : C r e a t i n g t h e Ca rd Flip A p p l i c a t i o n . . . . . . . . . . . . . 9 8
S o lv in g t h e C lic k a b le N u m b e r Im a g e s P r o b le m . . . . . . . . . . . . 1 1 3
C h a p t e r 3
T u t o r i a l 3 - 1 : T h e Birth Da te String A p p l i c a t i o n . . . . . . . . . . . . . 1 2 6
T u t o r ia l 3 - 2 : C a lc u la t in g F u e l E c o n o m y . . . . . . . . . . . . . . . . . . 1 4 6
T u t o r i a l 3 - 3 : C r e a t i n g t h e Sa le Price Ca lcula tor A p p l i c a t i o n
w it h C u r r e n c y F o r m a t t in g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 5 2
T u t o r i a l 3 - 4 : C r e a t i n g t h e Test Avera ge A p p l i c a t i o n w i t h
E x c e p t io n H a n d lin g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 6 0
T u t o r i a l 3 - 5 : C r e a t i n g t h e Cha nge Counter A p p l i c a t i o n . . . . . . 1 6 9
T u t o r ia l 3 - 6 : S in g le - s t e p p in g t h r o u g h a n A p p lic a t io n ’ s C o d e
a t R u n t im e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 8 5
S o lv in g t h e T ip , T a x , a n d T o t a l P r o b le m . . . . . . . . . . . . . . . . . . 1 9 5
C h a p t e r 4
T u t o r i a l 4 - 1 : C o m p l e t i n g t h e Test Score Avera ge A p p l i c a t i o n . . 2 0 4
T u t o r i a l 4 - 2 : C o m p l e t i n g t h e Payroll with Overtime A p p l i c a t i o n . 2 1 0
T u t o r i a l 4 - 3 : C o m p l e t i n g t h e Loa n Qua lifier A p p l i c a t i o n . . . . . 2 1 6
T u t o r ia l 4 - 4 : C a lc u la t in g F u e l E c o n o m y . . . . . . . . . . . . . . . . . . 2 3 9
T u t o r i a l 4 - 5 : C r e a t i n g t h e Color Theme A p p l i c a t i o n . . . . . . . . . 2 4 8
T u t o r i a l 4 - 6 : C r e a t i n g t h e Time Zone A p p l i c a t i o n . . . . . . . . . . . 2 5 5
S o lv in g t h e M a s s a n d W e ig h t P r o b le m . . . . . . . . . . . . . . . . . . . 2 6 4
C h a p t e r 5
T u t o r ia l 5 - 1 : U s in g a L o o p t o C a lc u la t e a n A c c o u n t B a la n c e . . . 2 7 5
T u t o r i a l 5 - 2 : E n h a n c i n g t h e Ending Ba la nce A p p l i c a t i o n . . . . . 2 7 8
T u t o r i a l 5 - 3 : U s i n g t h e for L o o p . . . . . . . . . . . . . . . . . . . . . . . . 2 8 8
T u t o r ia l 5 - 4 : W r it in g D a t a t o a T e x t F ile . . . . . . . . . . . . . . . . . . 2 9 9
T u t o r ia l 5 - 5 : A p p e n d in g D a t a t o t h e F r ie n d .t x t F ile . . . . . . . . . 3 0 4
T u t o r ia l 5 - 6 : U s in g a L o o p t o R e a d t o t h e E n d o f a F ile . . . . . . . 3 1 2
T u t o r ia l 5 - 7 : C a lc u la t in g a R u n n in g T o t a l . . . . . . . . . . . . . . . . . 3 1 6
T u t o r ia l 5 - 8 : S im u la t in g C o in T o s s e s . . . . . . . . . . . . . . . . . . . . 3 2 6
T u t o r ia l 5 - 9 : C r e a t in g a L o a d E v e n t H a n d le r . . . . . . . . . . . . . . . 3 3 1
S o lv in g t h e C e ls iu s t o F a h r e n h e it T a b le P r o b le m . . . . . . . . . . . 3 3 8
iii
iv
L o c a t io n s o f V id e o N o t e s
C h a p t e r 6
T u t o r ia l 6 - 1 : C r e a t in g a n d C a llin g M e t h o d s . . . . . . . . . . . . . . . 3 4 7
T u t o r ia l 6 - 2 : P a s s in g a n A r g u m e n t t o a M e t h o d . . . . . . . . . . . . 3 5 4
T u t o r ia l 6 - 3 : U s in g a n O u t p u t P a r a m e t e r . . . . . . . . . . . . . . . . . 3 6 5
T u t o r ia l 6 - 4 : W r it in g a V a lu e - R e t u r n in g M e t h o d . . . . . . . . . . . 3 7 4
T u t o r ia l 6 - 5 : M o d u la r iz in g In p u t V a lid a t io n w it h a
B o o le a n M e th o d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 7 7
T u t o r i a l 6 - 6 : P r a c t i c i n g t h e Step Into C o m m a n d . . . . . . . . . . . . 3 8 3
T u t o r i a l 6 - 7 : P r a c t i c i n g t h e Step Over C o m m a n d . . . . . . . . . . . 3 8 4
T u t o r i a l 6 - 8 : P r a c t i c i n g t h e Step Out C o m m a n d . . . . . . . . . . . . 3 8 5
S o lv in g t h e K in e t ic E n e r g y P r o b le m . . . . . . . . . . . . . . . . . . . . . 3 9 0
C h a p t e r 7
T u t o r ia l 7 - 1 : U s in g a n A r r a y t o H o ld a L is t o f R a n d o m
L o tte ry N u m b e rs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 0 5
T u t o r ia l 7 - 2 : P r o c e s s in g a n A r r a y . . . . . . . . . . . . . . . . . . . . . . . 4 3 0
T u t o r i a l 7 - 3 : C o m p l e t i n g t h e Sea ting Cha rt A p p l i c a t i o n . . . . . . 4 4 5
T u t o r i a l 7 - 4 : C o m p l e t i n g t h e Test Score List A p p l i c a t i o n . . . . . . 4 5 8
S o lv in g t h e T o t a l S a le s P r o b le m . . . . . . . . . . . . . . . . . . . . . . . . 4 6 8
C h a p t e r 8
T u t o r i a l 8 - 1 : C o m p l e t i n g t h e Pa ssword Va lida tion A p p l i c a t i o n . 4 7 7
T u t o r i a l 8 - 2 : C o m p l e t i n g t h e Telephone Forma t A p p l i c a t i o n . . 4 9 0
T u t o r i a l 8 - 3 : C o m p l e t i n g t h e Telephone Unforma t A p p l i c a t i o n . 4 9 4
T u t o r i a l 8 - 4 : C o m p l e t i n g t h e CSV Rea der A p p l i c a t i o n . . . . . . . 5 0 0
T u t o r i a l 8 - 5 : C o m p l e t i n g t h e Phonebook A p p l i c a t i o n . . . . . . . . 5 1 5
T u t o r i a l 8 - 6 : C o m p l e t i n g t h e Color Spectrum A p p l i c a t i o n . . . . 5 2 3
T u t o r i a l 8 - 7 : C o m p l e t i n g t h e Ra ndom Ca rd A p p l i c a t i o n . . . . . 5 3 0
S o lv in g t h e S u m o f N u m b e r s in a S t r in g P r o b le m . . . . . . . . . . 5 3 7
C h a p t e r 9
T u t o r i a l 9 - 1 : C r e a t i n g a n d U s i n g t h e Coin C l a s s . . . . . . . . . . . . 5 4 8
T u t o r i a l 9 - 2 : C r e a t i n g a n d U s i n g t h e CellPhone C l a s s . . . . . . . 5 5 6
T u t o r i a l 9 - 3 : C r e a t i n g a n d U s i n g t h e BankAccount C l a s s . . . . . 5 6 3
T u t o r i a l 9 - 4 : C o m p l e t i n g t h e Cell Phone Inventory A p p l i c a t i o n . 5 7 1
T u t o r ia l 9 - 5 : C r e a t in g a n A p p lic a t io n w it h T w o F o r m s . . . . . . 5 8 8
T u t o r ia l 9 - 6 : A c c e s s in g a C o n t r o l o n a D iffe r e n t F o r m . . . . . . . 5 9 3
S o lv in g t h e P e t C la s s P r o b le m . . . . . . . . . . . . . . . . . . . . . . . . . . 6 0 2
C h a p t e r 1 0
T u t o r i a l 1 0 - 1 : C r e a t i n g a n d T e s t i n g t h e SavingsAccount a n d
CDAccount C l a s s e s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1 5
T u t o r i a l 1 0 - 2 : C o m p l e t i n g t h e Polymorphism A p p l i c a t i o n . . . . 6 2 8
T u t o r i a l 1 0 - 3 : C o m p l e t i n g t h e Computer Science Student
A p p lic a t io n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 3 5
S o lv in g t h e E m p lo y e e a n d P r o d u c t io n W o r k e r
C la s s e s P r o b le m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 4 3
C h a p t e r 1 1
T u t o r i a l 1 1 - 1 : S t a r t i n g t h e Phone Book A p p l i c a t i o n a n d
C r e a t in g t h e P h o n e lis t .m d f D a t a b a s e . . . . . . . . . . . . . . . . . . . . 6 5 1
T u t o r i a l 1 1 - 2 : C o m p l e t i n g t h e Phone Book A p p l i c a t i o n . . . . . . 6 5 9
T u t o r i a l 1 1 - 3 : C r e a t i n g t h e Products A p p l i c a t i o n a n d
U s in g a D e t a ils V ie w . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 6 8
T u t o r i a l 1 1 - 4 : C r e a t i n g t h e Product Lookup A p p l i c a t i o n . . . . . . 6 7 9
T u t o r i a l 1 1 - 5 : C r e a t i n g t h e Multiform Products A p p l i c a t i o n . . . 6 8 2
T u t o r i a l 1 1 - 6 : C r e a t i n g t h e Product Queries A p p l i c a t i o n . . . . . . 6 9 4
T u t o r i a l 1 1 - 7 : C r e a t i n g t h e Product Queries A p p l i c a t i o n . . . . . . 7 0 3
T u t o r i a l 1 1 - 8 : C r e a t i n g t h e Product Sea rch A p p l i c a t i o n . . . . . . 7 0 7
S o lv in g t h e P e r s o n n e l D a t a b a s e P r o b le m . . . . . . . . . . . . . . . . . 7 1 7
B r ie f C o n te n ts
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
1
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
5 1
C h a p te r 3
P r o c e s s in g D a t a
1 1 7
C h a p te r 4
M a k in g D e c is io n s
1 9 9
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
2 6 9
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
3 4 1
C h a p te r 7
A r r a y s a n d L is t s
3 9 5
C h a p te r 8
M o r e A b o u t P r o c e s s in g D a t a
4 7 1
C h a p te r 9
C la s s e s a n d M u lt ifo r m P r o je c t s
5 4 1
C h a p te r 1 0
In h e r it a n c e a n d P o ly m o r p h is m
6 0 5
C h a p te r 1 1
D a t a b a s e s
6 4 5
A p p e n d ix A
C # P r im it iv e D a t a T y p e s
7 1 9
A p p e n d ix B
A d d it io n a l U s e r In t e r fa c e C o n t r o ls
7 2 1
A p p e n d ix C
A S C II/ U n ic o d e C h a r a c t e r s
7 4 1
A p p e n d ix D
A n s w e r s t o C h e c k p o in t Q u e s t io n s
7 4 3
In d e x
7 6 3
v
C o n te n ts
P r e fa c e
x i
A t t e n t io n S t u d e n t s
C h a p te r 1
x v ii
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
1
In t r o d u c t io n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
H a rd w a re a n d S o ftw a re . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
H o w C o m p u te rs S to re D a ta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
H o w a P ro g ra m W o rk s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1
G r a p h ic a l U s e r In t e r fa c e s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 8
O b je c ts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1
T h e P r o g r a m D e v e lo p m e n t P r o c e s s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 3
G e t t in g S t a r t e d w it h t h e V is u a l S t u d io E n v ir o n m e n t . . . . . . . . . . . . . . . . . . 2 7
T U T O R IA L 1 -1 : S t a r t in g V is u a l S t u d io a n d S e t t in g U p t h e E n v ir o n m e n t . . . . . . . . . . 2 8
T U T O R IA L 1 -2 : S t a r t in g a N e w V is u a l C # P r o je c t . . . . . . . . . . . . . . . . . . . . . . . . . . 3 0
T U T O R IA L 1 -3 : S a v in g a n d C lo s in g a P r o je c t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2
T U T O R IA L 1 -4 : O p e n in g a n E x is t in g P r o je c t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 0
T U T O R IA L 1 -5 : G e t t in g F a m ilia r w it h t h e V is u a l S t u d io E n v ir o n m e n t . . . . . . . . . . . 4 1
1 .1
1 .2
1 .3
1 .4
1 .5
1 .6
1 .7
1 .8
Key Terms 4 3
C h a p te r 2
• Review Q uestions 44 • Programming Problems 49
In t r o d u c t io n t o V is u a l C #
5 1
G e t t in g S t a r t e d w it h F o r m s a n d C o n t r o ls . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1
C r e a t in g t h e G U I fo r Y o u r F ir s t V is u a l C # A p p lic a t io n :
T h e Hello World A p p l i c a t i o n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 0
T U T O R I A L 2 - 1 : C r e a t i n g t h e G U I f o r t h e H ello World A p p l i c a t i o n . . . . . . . . . . . . . 6 1
2 .3
In t r o d u c t io n t o C # C o d e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 5
2 .4
W r i t i n g C o d e f o r t h e Hello World A p p l i c a t i o n . . . . . . . . . . . . . . . . . . . . . . . . 7 5
T U T O R I A L 2 - 2 : W r i t i n g C o d e f o r t h e H ello World A p p l i c a t i o n . . . . . . . . . . . . . . . . 7 5
2 .5
L a b e l C o n tr o ls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 8
T U T O R I A L 2 - 3 : C r e a t i n g t h e L anguage Translator A p p l i c a t i o n . . . . . . . . . . . . . . . . 8 6
2 .6
M a k in g S e n s e o f In t e lliS e n s e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 9
2 .7
P ic t u r e B o x C o n t r o ls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 0
T U T O R I A L 2 - 4 : C r e a t i n g t h e Flags A p p l i c a t i o n . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 4
T U T O R I A L 2 - 5 : C r e a t i n g t h e Card Flip A p p l i c a t i o n . . . . . . . . . . . . . . . . . . . . . . . . . 9 8
2 .8
C o m m e n t s , B la n k L in e s , a n d In d e n t a t io n . . . . . . . . . . . . . . . . . . . . . . . . . . 1 0 2
2 .9
W r it in g t h e C o d e t o C lo s e a n A p p lic a t io n ’ s F o r m . . . . . . . . . . . . . . . . . . . . 1 0 4
2 .1 0 D e a lin g w it h S y n t a x E r r o r s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 0 5
2 .1
2 .2
Key Terms 1 0 7
vi
• Review Q uestions 1 0 7
• Programming Problems 1 1 2
C o n te n ts
C h a p te r 3
P r o c e s s in g D a t a
1 1 7
3 .1
3 .2
R e a d in g In p u t w it h T e x t B o x C o n t r o ls . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A F ir s t L o o k a t V a r ia b le s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 3 - 1 : T h e Birth D ate String A p p l i c a t i o n . . . . . . . . . . . . . . . . . . . . . . . . .
3 .3
N u m e r ic D a t a T y p e s a n d V a r ia b le s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3 .4
P e r fo r m in g C a lc u la t io n s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3 .5
In p u t t in g a n d O u t p u t t in g N u m e r ic V a lu e s . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R IA L 3 -2 : C a lc u la t in g F u e l E c o n o m y . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3 .6
F o r m a t t i n g N u m b e r s w i t h t h e ToString M e t h o d . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 3 - 3 : C r e a t i n g t h e Sale Price Calculator A p p l i c a t i o n w i t h
C u r r e n c y F o r m a ttin g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3 .7
S im p le E x c e p t io n H a n d lin g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 3 - 4 : C r e a t i n g t h e Test Average A p p l i c a t i o n w i t h
E x c e p tio n H a n d lin g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3 .8
U s in g N a m e d C o n s t a n t s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3 .9
D e c la r in g V a r ia b le s a s F ie ld s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 3 - 5 : C r e a t i n g t h e Change Counter A p p l i c a t i o n . . . . . . . . . . . . . . . . . . .
3 . 1 0 U s i n g t h e Math C l a s s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3 .1 1 M o r e G U I D e t a ils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3 .1 2 U s in g t h e D e b u g g e r t o L o c a t e L o g ic E r r o r s . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R IA L 3 -6 S in g le - s t e p p in g t h r o u g h a n A p p lic a t io n ’s C o d e
a t R u n tim e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Key Terms 1 9 0
C h a p te r 4
• Review Q uestions 1 9 0
M a k in g D e c is io n s
1 5 2
1 5 6
1 6 0
1 6 4
1 6 5
1 6 9
1 7 3
1 7 5
1 8 4
1 8 5
• Programming Problems 1 9 5
1 9 9
D e c i s i o n S t r u c t u r e s a n d t h e if S t a t e m e n t . . . . . . . . . . . . . . . . . . . . . . . . .
C o m p l e t i n g t h e Test Score Average A p p l i c a t i o n . . . . . . . . . . . . . .
4 .2
T h e if-else S t a t e m e n t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 4 - 2 : C o m p l e t i n g t h e Payroll with O vertime A p p l i c a t i o n . . . . . . . . . . .
4 .3
N e s t e d D e c is io n S t r u c t u r e s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 4 - 3 : C o m p l e t i n g t h e L oan Q ualifier A p p l i c a t i o n . . . . . . . . . . . . . . . . .
4 .4
L o g ic a l O p e r a t o r s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4 .5
bool V a r i a b l e s a n d F l a g s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4 .6
C o m p a r in g S t r in g s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4 .7
P r e v e n t i n g D a t a C o n v e r s i o n E x c e p t i o n s w i t h t h e TryParse
M e th o d s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R IA L 4 -4 : C a lc u la t in g F u e l E c o n o m y . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4 .8
In p u t V a lid a t io n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4 .9
R a d io B u t t o n s a n d C h e c k B o x e s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 4 - 5 : C r e a t i n g t h e Color Theme A p p l i c a t i o n . . . . . . . . . . . . . . . . . . . . .
4 . 1 0 T h e switch S t a t e m e n t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4 .1 1 In t r o d u c t io n t o L is t B o x e s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 4 - 6 : C r e a t i n g t h e Time Z one A p p l i c a t i o n . . . . . . . . . . . . . . . . . . . . . . .
4 .1
T U T O R IA L 4 -1 :
Key Terms 2 5 9
1 1 7
1 2 0
1 2 6
1 3 1
1 3 6
1 4 1
1 4 6
1 4 9
• Review Q uestions 2 5 9
• Programming Problems 2 6 3
1 9 9
2 0 4
2 0 8
2 1 0
2 1 4
2 1 6
2 2 5
2 3 0
2 3 0
2 3 4
2 3 9
2 4 2
2 4 3
2 4 8
2 5 0
2 5 3
2 5 5
vi i
vi i i
C o n te n ts
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
2 6 9
M o r e a b o u t L is t B o x e s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 6 9
T h e while L o o p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 7 1
T U T O R IA L 5 -1 : U s in g a L o o p t o C a lc u la t e a n A c c o u n t B a la n c e . . . . . . . . . . . . . . . 2 7 5
T U T O R I A L 5 - 2 : E n h a n c i n g t h e Ending Balance A p p l i c a t i o n . . . . . . . . . . . . . . . . . . 2 7 8
5 .3
T he ++ and −− operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 8 2
5.4 The for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 8 3
T U T O R I A L 5 - 3 : U s i n g t h e for L o o p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 8 8
5.5 The do-while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 9 1
5.6 Using Files for Data Storage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 9 3
T U T O R IA L 5 -4 : W r it in g D a t a t o a T e x t F ile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 9 9
T U T O R IA L 5 -5 : A p p e n d in g D a t a t o t h e F r ie n d .t x t F ile . . . . . . . . . . . . . . . . . . . . . . 3 0 4
T U T O R IA L 5 -6 : U s in g a L o o p t o R e a d t o t h e E n d o f a F ile . . . . . . . . . . . . . . . . . . . 3 1 2
T U T O R IA L 5 -7 : C a lc u la t in g a R u n n in g T o t a l . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1 6
5.7 The OpenFileDialog and SaveFileDialog Controls. . . . . . . . . . . . . . . . . . . . 3 1 9
5.8 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2 4
T U T O R IA L 5 -8 : S im u la t in g C o in T o s s e s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2 6
5.9 The Load Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 3 0
T U T O R IA L 5 -9 : C r e a t in g a L o a d E v e n t H a n d le r . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 3 1
5 .1
5 .2
Key Terms 3 3 4
Chapter 6
• Review Q uestions 3 3 4
• Programming Problems 3 3 7
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
3 4 1
6.1 Introduction to Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 4 1
6.2 void Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 4 3
T U T O R IA L 6 -1 : C r e a t in g a n d C a llin g M e t h o d s . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 4 7
6.3 Passing Arguments to Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 5 1
T U T O R IA L 6 -2 : P a s s in g a n A r g u m e n t t o a M e t h o d . . . . . . . . . . . . . . . . . . . . . . . . 3 5 4
6.4 Passing Arguments by Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 6 2
T U T O R IA L 6 -3 : U s in g a n O u t p u t P a r a m e t e r . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 6 5
6.5 Value-Returning Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 6 9
T U T O R IA L 6 -4 : W r it in g a V a lu e - R e t u r n in g M e t h o d . . . . . . . . . . . . . . . . . . . . . . . . 3 7 4
T U T O R IA L 6 -5 : M o d u la r iz in g I n p u t V a lid a t io n w it h a B o o le a n M e t h o d . . . . . . . . 3 7 7
6.6 Debugging Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 8 2
T U T O R I A L 6 - 6 : P r a c t i c i n g t h e Step I nto C o m m a n d . . . . . . . . . . . . . . . . . . . . . . . . 3 8 3
T U T O R I A L 6 - 7 : P r a c t i c i n g t h e Step O ver C o m m a n d . . . . . . . . . . . . . . . . . . . . . . . 3 8 4
T U T O R I A L 6 - 8 : P r a c t i c i n g t h e Step O ut C o m m a n d . . . . . . . . . . . . . . . . . . . . . . . . 3 8 5
Key Terms 3 8 7
Chapter 7
• Review Q uestions 3 8 7
A r r a y s a n d L is t s
• Programming Problems 3 9 0
3 9 5
7.1 Value Types and Reference Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 9 5
7.2 Array Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 9 8
T U T O R IA L 7 -1 : U s in g a n A r r a y t o H o ld a L is t o f R a n d o m L o t t e r y N u m b e r s . . . . . 4 0 5
7.3 Working w ith Files and Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1 0
7.4 Passing Arrays as Arguments to Methods . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1 3
7.5 Some Useful Array Algorithms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2 0
T U T O R IA L 7 -2 : P r o c e s s in g a n A r r a y . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 3 0
7.6 Advanced Algorithms for Sorting and Searching Arrays . . . . . . . . . . . . . . . 4 3 5
C o n te n ts
7 .7
T w o - D im e n s io n a l A r r a y s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
C o m p l e t i n g t h e Seating Chart A p p l i c a t i o n . . . . . . . . . . . . . . . . . .
7 .8
Ja g g e d A r r a y s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7 .9
T h e List C o l l e c t i o n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 7 - 4 : C o m p l e t i n g t h e Test Score L ist A p p l i c a t i o n . . . . . . . . . . . . . . . . .
T U T O R IA L 7 -3 :
Key Terms 4 6 4
C h a p te r 8
• Review Q uestions 4 6 4
• Programming Problems 4 6 8
M o r e A b o u t P r o c e s s in g D a t a
4 7 1
8 .1
8 .2
In t r o d u c t io n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
S t r in g a n d C h a r a c t e r P r o c e s s in g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 8 - 1 : C o m p l e t i n g t h e Password Validation A p p l i c a t i o n . . . . . . . . . . . . .
T U T O R I A L 8 - 2 : C o m p l e t i n g t h e Telephone Format A p p l i c a t i o n . . . . . . . . . . . . . . .
T U T O R I A L 8 - 3 : C o m p l e t i n g t h e Telephone Unformat A p p l i c a t i o n . . . . . . . . . . . . .
T U T O R I A L 8 - 4 : C o m p l e t i n g t h e CSV Reader A p p l i c a t i o n . . . . . . . . . . . . . . . . . . .
8 .3
S tru c tu re s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 8 - 5 : C o m p l e t i n g t h e Phonebook A p p l i c a t i o n . . . . . . . . . . . . . . . . . . . .
8 .4
E n u m e ra te d T y p e s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 8 - 6 : C o m p l e t i n g t h e Color Spectrum A p p l i c a t i o n . . . . . . . . . . . . . . . . .
8 .5
T h e Im a g e L is t C o n t r o l . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 8 - 7 : C o m p l e t i n g t h e Random Card A p p l i c a t i o n . . . . . . . . . . . . . . . . . .
Key Terms 5 3 3
C h a p te r 9
• Review Q uestions 5 3 3
5 4 1
9 .1
In t r o d u c t io n t o C la s s e s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 9 - 1 : C r e a t i n g a n d U s i n g t h e Coin C l a s s . . . . . . . . . . . . . . . . . . . . . . . .
9 .2
P r o p e r t ie s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 9 - 2 : C r e a t i n g a n d U s i n g t h e CellPhone C l a s s . . . . . . . . . . . . . . . . . . .
9 .3
P a r a m e t e r iz e d C o n s t r u c t o r s a n d O v e r lo a d in g . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 9 - 3 : C r e a t i n g a n d U s i n g t h e BankAccount C l a s s . . . . . . . . . . . . . . . . .
9 .4
S t o r i n g C l a s s T y p e O b j e c t s i n A r r a y s a n d Lists . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 9 - 4 : C o m p l e t i n g t h e Cell Phone I nventory A p p l i c a t i o n . . . . . . . . . . . .
9 .5
F in d in g t h e C la s s e s a n d T h e ir R e s p o n s ib ilit ie s in a P r o b le m . . . . . . . . . . . .
9 .6
C r e a t in g M u lt ip le F o r m s in a P r o je c t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R IA L 9 -5 : C r e a t in g a n A p p lic a t io n w it h T w o F o r m s . . . . . . . . . . . . . . . . . . .
T U T O R IA L 9 -6 : A c c e s s in g a C o n t r o l o n a D if f e r e n t F o r m . . . . . . . . . . . . . . . . . . .
C h a p te r 1 0
• Review Q uestions 5 9 8
4 7 1
4 7 1
4 7 7
4 9 0
4 9 4
5 0 0
5 0 5
5 1 5
5 2 0
5 2 3
5 2 8
5 3 0
• Programming Problems 5 3 7
C la s s e s a n d M u lt ifo r m P r o je c t s
Key Terms 5 9 8
4 4 2
4 4 5
4 5 1
4 5 2
4 5 8
5 4 1
5 4 8
5 5 3
5 5 6
5 6 3
5 6 3
5 6 9
5 7 1
5 7 5
5 8 4
5 8 8
5 9 3
• Programming Problems 6 0 2
In h e r it a n c e a n d P o ly m o r p h is m
6 0 5
1 0 .1 In h e r it a n c e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
C r e a t i n g a n d T e s t i n g t h e SavingsAccount a n d
CDAccount C l a s s e s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1 0 .2 P o ly m o r p h is m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 1 0 - 2 : C o m p l e t i n g t h e Polymorphism A p p l i c a t i o n . . . . . . . . . . . . . . . . .
1 0 .3 A b s tr a c t C la s s e s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 1 0 - 3 : C o m p l e t i n g t h e Computer Science Student A p p l i c a t i o n . . . . . . . .
6 0 5
T U T O R IA L 1 0 -1 :
Key Terms 6 4 0
• Review Q uestions 6 4 0
• Programming Problems 6 4 3
6 1 5
6 2 3
6 2 8
6 3 3
6 3 5
ix
x
C o n te n ts
C h a p te r 1 1
D a t a b a s e s
6 4 5
1 1 .1 In t r o d u c t io n t o D a t a b a s e M a n a g e m e n t S y s t e m s . . . . . . . . . . . . . . . . . . . .
1 1 .2 T a b le s , R o w s , a n d C o lu m n s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1 1 .3 C r e a t in g a D a t a b a s e in V is u a l S t u d io . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 1 1 - 1 : S t a r t i n g t h e Phone Book A p p l i c a t i o n a n d C r e a t i n g
th e P h o n e lis t.m d f D a ta b a s e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1 1 .4 T h e D a t a G r id V ie w C o n t r o l. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 1 1 - 2 : C o m p l e t i n g t h e Phone Book A p p l i c a t i o n . . . . . . . . . . . . . . . . . .
1 1 .5 C o n n e c t in g t o a n E x is t in g D a t a b a s e a n d U s in g D e t a ils V ie w C o n t r o ls . . . .
T U T O R I A L 1 1 - 3 : C r e a t i n g t h e Products A p p l i c a t i o n a n d U s i n g a D e t a i l s V i e w . . .
1 1 .6 M o r e A b o u t D a ta -B o u n d C o n tr o ls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 1 1 - 4 : C r e a t i n g t h e Product L ookup A p p l i c a t i o n . . . . . . . . . . . . . . . . . .
T U T O R I A L 1 1 - 5 : C r e a t i n g t h e M ultiform Products A p p l i c a t i o n . . . . . . . . . . . . . . .
1 1 . 7 S e l e c t i n g D a t a w i t h t h e S Q L Select S t a t e m e n t . . . . . . . . . . . . . . . . . . . . .
T U T O R I A L 1 1 - 6 : C r e a t i n g t h e Product Q ueries A p p l i c a t i o n . . . . . . . . . . . . . . . . . .
T U T O R I A L 1 1 - 7 : C r e a t i n g t h e Product Q ueries A p p l i c a t i o n . . . . . . . . . . . . . . . . . .
T U T O R I A L 1 1 - 8 : C r e a t i n g t h e Product Search A p p l i c a t i o n . . . . . . . . . . . . . . . . . . .
Key Terms 7 1 3
• Review Q uestions 7 1 3
6 4 5
6 4 7
6 5 0
6 5 1
6 5 9
6 5 9
6 6 6
6 6 8
6 7 6
6 7 9
6 8 2
6 8 8
6 9 4
7 0 3
7 0 7
• Programming Problems 7 1 7
A p p e n d ix A
C # P r im it iv e D a t a T y p e s . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7 1 9
A p p e n d ix B
A d d it io n a l U s e r In t e r fa c e C o n t r o ls . . . . . . . . . . . . . . . . . . .
7 2 1
A p p e n d ix C
A S C II/ U n ic o d e C h a r a c t e r s . . . . . . . . . . . . . . . . . . . . . . . . . .
7 4 1
A p p e n d ix D A n s w e r s t o C h e c k p o i n t Q u e s t i o n s . . . . . . . . . . . . . . . . . . . .
7 4 3
In d e x
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 6 3
P re fa c e
W
e l c o m e t o Starting O ut with Visual C#, F o u r t h E d i t i o n . T h i s b o o k i s i n t e n d e d
fo r a n in tr o d u c to r y p r o g r a m m in g c o u r s e a n d is id e a l fo r s tu d e n ts w ith n o
p r io r e x p e r ie n c e . S tu d e n ts w h o a r e n e w to p r o g r a m m in g w ill a p p r e c ia te th e c le a r , d o w n to -e a r th e x p la n a tio n s a n d th e d e ta ile d w a lk -th r o u g h s th a t a r e p r o v id e d b y th e h a n d s -o n
tu to r ia ls . M o r e e x p e r ie n c e d s tu d e n ts w ill a p p r e c ia te th e d e p th o f d e ta il a s th e y le a r n
a b o u t th e .N E T F r a m e w o r k , d a ta b a s e s , a n d o th e r to p ic s .
A s w i t h a l l t h e b o o k s i n t h e Starting Out With s e r i e s , t h e h a l l m a r k o f t h i s t e x t i s i t s c l e a r ,
fr ie n d ly , a n d e a s y -to -u n d e r s ta n d w r itin g . In a d d itio n , it is r ic h in e x a m p le p r o g r a m s th a t a r e
c o n c is e a n d p r a c tic a l. T h e p r o g r a m s in th is b o o k in c lu d e s h o r t e x a m p le s th a t h ig h lig h t s p e c ific
p r o g r a m m in g to p ic s , a s w e ll a s m o r e in v o lv e d e x a m p le s th a t fo c u s o n p r o b le m s o lv in g . E a c h
c h a p te r p r o v id e s n u m e r o u s h a n d s -o n tu to r ia ls th a t g u id e th e s tu d e n t th r o u g h e a c h s te p o f th e
d e v e lo p m e n t o f a n a p p lic a tio n . In a d d itio n to d e ta ile d , s te p -b y -s te p in s tr u c tio n s , th e tu to r ia ls
a ls o p r o v id e th e a p p lic a tio n ’s c o m p le te d c o d e a n d s c r e e n c a p tu r e s o f th e c o m p le te d fo r m s .
N e w t o T h is E d it io n
• C o m p le te ly u p d a te d fo r V is u a l S tu d io 2 0 1 5 — T h is b o o k w a s r e v is e d a n d te s te d
u s in g V is u a l S tu d io 2 0 1 5 C o m m u n ity E d itio n .
• N e w C o v e r a g e o f D e b u g g in g — A n e w s e c tio n o n u s in g th e V is u a l S tu d io d e b u g g e r
to lo c a te lo g ic e r r o r s h a s b e e n a d d e d to C h a p te r 3 . T h e s e c tio n in c lu d e s a h a n d s -o n
tu to r ia l th a t d e m o n s tr a te s h o w to s e t a b r e a k p o in t a n d s in g le -s te p th r o u g h a n a p p lic a tio n ’s c o d e . A n e w s e c tio n h a s a ls o b e e n a d d e d to C h a p te r 6 , d e m o n s tr a tin g h o w
to u s e th e d e b u g g e r to s te p in to , s te p o v e r , a n d s te p o u t o f m e th o d s .
• A c c e s s in g C o n tr o ls o n a D iffe r e n t F o r m — C h a p te r 9 h a s a n e w s e c tio n , w ith a
h a n d s -o n tu to r ia l, th a t d e m o n s tr a te s h o w c o d e o n o n e fo r m c a n a c c e s s a c o n tr o l
th a t e x is ts o n a d iffe r e n t fo r m .
• A u to -P r o p e r tie s — C h a p te r 9 h a s a n e w s e c tio n o n a u to -p r o p e r tie s . A n a u to -p r o p e r ty
is a p r o p e r ty th a t s im p ly s e ts a n d g e ts a v a lu e , a n d c a n b e d e c la r e d w ith o u t e x p lic itly
d e c la r in g b a c k in g fie ld s , a n d w ith o u t w r itin g th e c o d e th a t s e ts a n d g e ts th e
p r o p e r ty ’s v a lu e .
• R e a d -O n ly A u to -P r o p e r tie s — C h a p te r 9 a ls o h a s a n e w s e c tio n o n r e a d -o n ly a u to p r o p e r tie s , w h ic h c a n b e u s e d to r e a d th e p r o p e r tie s ’ v a lu e , b u t n o t s e t th e v a lu e .
A G U I-B a s e d A p p r o a c h
B e g in n in g s tu d e n ts a r e m o r e m o tiv a te d to le a r n p r o g r a m m in g w h e n th e ir a p p lic a tio n s
h a v e s o m e s o r t o f g r a p h ic a l e le m e n t, s u c h a s a g r a p h ic a l u s e r in te r fa c e (G U I). S tu d e n ts
u s in g th is b o o k w ill le a r n to c r e a te G U I-b a s e d , e v e n t-d r iv e n , V is u a l C # a p p lic a tio n s . T h e
V is u a l S tu d io e n v ir o n m e n t is u s e d to c r e a te fo r m s th a t a r e r ic h w ith u s e r in te r fa c e c o n tr o ls a n d g r a p h ic a l im a g e s .
L e a r n t o U s e O b je c t s E a r ly , L e a r n t o W r it e C la s s e s L a t e r
T h is b o o k e x p la in s w h a t a n o b je c t is v e r y e a r ly a n d s h o w s th e s tu d e n t h o w to c r e a te
o b je c ts fr o m c la s s e s th a t a r e p r o v id e d b y th e .N E T F r a m e w o r k . It th e n in tr o d u c e s th e
s tu d e n t to th e fu n d a m e n ta ls o f in p u t a n d o u tp u t, c o n tr o l s tr u c tu r e s , m e th o d s , a r r a y s a n d
lis ts , a n d file o p e r a tio n s . T h e n , th e s tu d e n t le a r n s to w r ite h is o r h e r o w n c la s s e s a n d
e x p lo r e s th e to p ic s o f in h e r ita n c e a n d p o ly m o r p h is m .
xi
xii
P re fa c e
B r ie f O v e r v ie w o f E a c h C h a p t e r
C h a p t e r 1 : I n t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g . T h is c h a p te r b e g in s
b y g iv in g a v e r y c o n c r e te a n d e a s y -to -u n d e r s ta n d e x p la n a tio n o f h o w c o m p u te r s w o r k ,
h o w d a ta is s to r e d a n d m a n ip u la te d , a n d w h y w e w r ite p r o g r a m s in h ig h -le v e l la n g u a g e s .
In th is c h a p te r , th e s tu d e n t le a r n s w h a t a n o b je c t is a n d s e e s s e v e r a l e x a m p le s b y s tu d y in g
th e o b je c ts th a t m a k e u p a p r o g r a m ’s G U I. T h e c h a p te r d is c u s s e s s te p s in th e p r o g r a m m in g d e v e lo p m e n t c y c le . It a ls o g iv e s a n in tr o d u c tio n to th e V is u a l S tu d io e n v ir o n m e n t.
C h a p t e r 2 : I n t r o d u c t io n t o V is u a l C # . In th is c h a p te r , th e s tu d e n t le a r n s to c r e a te
fo r m s w ith la b e ls , b u tto n s , a n d p ic tu r e b o x e s a n d le a r n s to m o d ify c o n tr o l p r o p e r tie s .
T h e s tu d e n t is in tr o d u c e d to C # c o d e a n d le a r n s th e o r g a n iz a tio n a l s tr u c tu r e o f n a m e s p a c e s , c la s s e s , a n d m e th o d s . T h e s tu d e n t le a r n s to w r ite s im p le e v e n t-d r iv e n a p p lic a tio n s
th a t r e s p o n d to b u tto n c lic k s o r p r o v id e in te r a c tio n th r o u g h c lic k a b le im a g e s . T h e im p o r ta n c e o f c o m m e n tin g c o d e is a ls o d is c u s s e d .
C h a p t e r 3 : P r o c e s s in g D a t a . T h is c h a p te r in tr o d u c e s v a r ia b le s a n d d a ta ty p e s . It
d is c u s s e s th e u s e o f lo c a l v a r ia b le s a n d v a r ia b le s d e c la r e d a s fie ld s w ith in a fo r m c la s s .
T h e s tu d e n t le a r n s to c r e a te a p p lic a tio n s th a t r e a d in p u t fr o m T e x tB o x c o n tr o ls , p e r fo r m
m a th e m a tic a l o p e r a tio n s , a n d p r o d u c e fo r m a tte d o u tp u t. T h e s tu d e n t le a r n s a b o u t th e
e x c e p tio n s th a t c a n o c c u r w h e n th e u s e r e n te r s in v a lid d a ta in to a T e x tB o x a n d le a r n s to
w r ite s im p le e x c e p tio n -h a n d lin g c o d e to d e a l w ith th o s e p r o b le m s . N a m e d c o n s ta n ts a r e
in tr o d u c e d a s a w a y o f r e p r e s e n tin g u n c h a n g in g v a lu e s a n d c r e a tin g s e lf-d o c u m e n tin g ,
m a in ta in a b le c o d e . T h e s tu d e n t a ls o le a r n s m o r e in tr ic a c ie s o f c r e a tin g g r a p h ic a l u s e r
in te r fa c e s . T h e c h a p te r c o n c lu d e s w ith a d is c u s s io n a n d tu to r ia l o n u s in g th e V is u a l S tu d io
d e b u g g e r to lo c a te lo g ic e r r o r s b y s in g le -s te p p in g th r o u g h a n a p p lic a tio n ’s c o d e .
C h a p t e r 4 : M a k in g D e c is io n s . In th is c h a p te r , th e s tu d e n t le a r n s a b o u t r e la tio n a l
o p e r a to r s a n d B o o le a n e x p r e s s io n s a n d is s h o w n h o w to c o n tr o l th e flo w o f a p r o g r a m
w i t h d e c i s i o n s t r u c t u r e s . T h e if, if-else, a n d if-else-if s t a t e m e n t s a r e c o v e r e d . N e s t e d d e c i s i o n s t r u c t u r e s , l o g i c a l o p e r a t o r s , a n d t h e switch s t a t e m e n t a r e a l s o d i s c u s s e d . T h e s t u d e n t
l e a r n s t o u s e t h e TryParse f a m i l y o f m e t h o d s t o v a l i d a t e i n p u t a n d p r e v e n t e x c e p t i o n s .
R a d io b u tto n s , c h e c k b o x e s , a n d lis t b o x e s a r e in tr o d u c e d a s w a y s to le t th e u s e r s e le c t
ite m s in a G U I.
C h a p t e r 5 : L o o p s , F ile s , a n d R a n d o m N u m b e r s . T h is c h a p te r s h o w s th e s tu d e n t
h o w t o u s e l o o p s t o c r e a t e r e p e t i t i o n s t r u c t u r e s . T h e while l o o p , t h e for l o o p , a n d t h e dowhile l o o p a r e p r e s e n t e d . C o u n t e r s , a c c u m u l a t o r s , a n d r u n n i n g t o t a l s a r e a l s o d i s c u s s e d .
T h is c h a p te r a ls o in tr o d u c e s s e q u e n tia l file in p u t a n d o u tp u t a n d u s in g te x t file s . T h e
s tu d e n t le a r n s v a r io u s p r o g r a m m in g te c h n iq u e s fo r w r itin g d a ta to te x t file s a n d r e a d in g
th e c o n te n ts o f te s t file s . T h e c h a p te r c o n c lu d e s w ith a d is c u s s io n o f p s e u d o r a n d o m n u m b e r s , th e ir a p p lic a tio n s , a n d h o w to g e n e r a te th e m .
C h a p t e r 6 : M o d u la r iz in g Y o u r C o d e w it h M e t h o d s . In th is c h a p te r , th e s tu d e n t
f i r s t l e a r n s h o w t o w r i t e a n d c a l l void m e t h o d s a s w e l l a s v a l u e - r e t u r n i n g m e t h o d s . T h e
c h a p te r s h o w s th e b e n e fits o f u s in g m e th o d s to m o d u la r iz e p r o g r a m s a n d d is c u s s e s th e
to p -d o w n d e s ig n a p p r o a c h . T h e n , th e s tu d e n t le a r n s to p a s s a r g u m e n ts to m e th o d s . P a s s in g b y v a lu e , b y r e fe r e n c e , a n d o u tp u t p a r a m e te r s a r e d is c u s s e d . T h e c h a p te r c o n c lu d e s
w ith a d is c u s s io n a n d tu to r ia l o n d e b u g g in g m e th o d s w ith th e V is u a l S tu d io s te p -in to ,
step -o ver, an d step -o u t, co mman d s.
C h a p t e r 7 : A r r a y s a n d L is t s . A r r a y s a n d lis ts a r e r e fe r e n c e -ty p e o b je c ts in C # s o th is
c h a p te r b e g in s b y d is c u s s in g th e d iffe r e n c e b e tw e e n v a lu e ty p e a n d r e fe r e n c e ty p e o b je c ts
in th e C # la n g u a g e . T h e n , th e s tu d e n t le a r n s to c r e a te a n d w o r k w ith s in g le -d im e n s io n a l
a n d tw o -d im e n s io n a l a r r a y s . T h e s tu d e n t le a r n s to p a s s a r r a y s a s a r g u m e n ts to m e th o d s ,
tr a n s fe r d a ta b e tw e e n a r r a y s a n d file s , w o r k w ith p a r tia lly fille d a r r a y s , a n d c r e a te ja g g e d
a r r a y s . M a n y e x a m p le s o f a r r a y p r o c e s s in g a r e p r o v id e d , in c lu d in g e x a m p le s o f fin d in g
P re fa c e
th e s u m , a v e r a g e , h ig h e s t, a n d lo w e s t v a lu e s in a n a r r a y . F in a lly , th e s tu d e n t le a r n s to
c r e a t e List o b j e c t s a n d s t o r e d a t a i n t h e m .
C h a p t e r 8 : M o r e A b o u t P r o c e s s in g D a t a . T h is c h a p te r p r e s e n ts s e v e r a l d iv e r s e
to p ic s . N o w th a t th e s tu d e n t h a s s tu d ie d th e fu n d a m e n ta ls o f V is u a l C # p r o g r a m m in g , h e
o r s h e c a n u s e th e to p ic s p r e s e n te d in th is c h a p te r to p e r fo r m m o r e a d v a n c e d o p e r a tio n s .
F ir s t, v a r io u s s tr in g a n d c h a r a c te r p r o c e s s in g te c h n iq u e s a r e in tr o d u c e d . T h e n , th e s tu d e n t
le a r n s to u s e s tr u c tu r e s to e n c a p s u la te s e v e r a l v a r ia b le s in to a s in g le ite m . T h e s tu d e n t
n e x t le a r n s to c r e a te a n d u s e e n u m e r a te d ty p e s . L a s t, th e s tu d e n t le a r n s a b o u t th e Im a g e L is t c o n tr o l, a d a ta s tr u c tu r e fo r s to r in g a n d r e tr ie v in g im a g e s .
C h a p t e r 9 : C la s s e s a n d M u lt if o r m P r o je c t s . U p to th is p o in t, th e s tu d e n t h a s
e x te n s iv e ly u s e d o b je c ts th a t a r e in s ta n c e s o f .N E T F r a m e w o r k c la s s e s . In th is c h a p te r , th e
s tu d e n t le a r n s to w r ite c la s s e s to c r e a te h is o r h e r o w n o b je c ts w ith fie ld s , m e th o d s , a n d
c o n s tr u c to r s . T h e s tu d e n t le a r n s h o w to im p le m e n t v a r io u s ty p e s o f p r o p e r tie s w ith in a
c la s s , in c lu d in g a u to -p r o p e r tie s a n d r e a d -o n ly a u to -p r o p e r tie s . C r e a tin g a r r a y s o f o b je c ts
a n d s t o r i n g o b j e c t s i n a List a r e a l s o d i s c u s s e d . A p r i m e r o n f i n d i n g t h e c l a s s e s i n a p r o b le m a s w e ll a s th e ir r e s p o n s ib ilitie s is p r o v id e d . F in a lly , th e c h a p te r s h o w s th e s tu d e n t
h o w to c r e a te m u ltip le fo r m c la s s e s in a p r o je c t, in s ta n tia te th o s e c la s s e s , a n d d is p la y
th e m . A tu to r ia l is g iv e n w h e r e th e s tu d e n t c r e a te s a m u ltifo r m a p p lic a tio n in w h ic h th e
c o d e in o n e fo r m a c c e s s e s c o n tr o ls o n a n o th e r fo r m .
C h a p t e r 1 0 : I n h e r it a n c e a n d P o ly m o r p h is m . T h e s tu d y o f c la s s e s c o n tin u e s in
th is c h a p te r w ith th e s u b je c ts o f in h e r ita n c e a n d p o ly m o r p h is m . T h e to p ic s c o v e r e d
in c lu d e b a s e c la s s e s , d e r iv e d c la s s e s , h o w c o n s tr u c to r s fu n c tio n s w o r k in in h e r ita n c e ,
m e th o d o v e r r id in g , a n d p o ly m o r p h is m . A b s tr a c t c la s s e s a n d a b s tr a c t m e th o d s a r e
a ls o d is c u s s e d .
C h a p t e r 1 1 : D a t a b a s e s . T h is c h a p te r in tr o d u c e s th e s tu d e n t to b a s ic d a ta b a s e c o n c e p ts . T h e s tu d e n t fir s t le a r n s a b o u t ta b le s , r o w s , a n d c o lu m n s a n d h o w to c r e a te a n S Q L
S e r v e r d a ta b a s e in V is u a l S tu d io . T h e s tu d e n t th e n le a r n s h o w to c o n n e c t a d a ta b a s e to a
V is u a l C # a p p lic a tio n a n d d is p la y a ta b le in a D a ta G r id V ie w c o n tr o l, a D e ta ils v ie w , a n d
o th e r d a ta -b o u n d c o n tr o ls . F in a lly , th e s tu d e n t le a r n s h o w to w r ite S Q L S e le c t s ta te m e n ts
to r e tr ie v e d a ta fr o m a ta b le .
A p p e n d ix A : C # P r im it iv e D a t a T y p e s . T h is a p p e n d ix g iv e s a n o v e r v ie w o f th e
p r im itiv e d a ta ty p e s a v a ila b le in C # .
A p p e n d ix B : A d d it io n a l U s e r I n t e r f a c e C o n t r o ls . T h is a p p e n d ix s h o w s h o w to
c r e a te a v a r ie ty o f c o n tr o ls s u c h a s T o o lT ip s , c o m b o b o x e s , s c r o ll b a r s , T a b C o n tr o ls ,
W e b B r o w s e r c o n tr o ls , E r r o r P r o v id e r c o m p o n e n ts , a n d m e n u s y s te m s .
A p p e n d ix C : A S C I I / U n ic o d e C h a r a c t e r s . T h is a p p e n d ix lis ts th e A S C II (A m e r ic a n
S ta n d a r d C o d e fo r In fo r m a tio n In te r c h a n g e ) c h a r a c te r s e t, w h ic h is a ls o th e L a tin S u b s e t
o f U n ic o d e .
A p p e n d ix D : A n s w e r s t o C h e c k p o in t Q u e s t io n s . T h is a p p e n d ix p r o v id e s th e
a n s w e r s to th e C h e c k p o in t q u e s tio n s th a t a p p e a r th r o u g h o u t e a c h c h a p te r in th e b o o k .
O r g a n iz a t io n o f t h e T e x t
T h e te x t te a c h e s V is u a l C # s te p b y s te p . E a c h c h a p te r c o v e r s a m a jo r s e t o f p r o g r a m m in g
to p ic s , in tr o d u c e s c o n tr o ls a n d G U I e le m e n ts , a n d b u ild s k n o w le d g e a s th e s tu d e n t p r o g r e s s e s th r o u g h th e b o o k . A lth o u g h th e c h a p te r s c a n b e e a s ily ta u g h t in th e ir e x is tin g
s e q u e n c e , th e r e is s o m e fle x ib ility . F ig u r e P -1 s h o w s th e c h a p te r d e p e n d e n c ie s . A s s h o w n
in th e fig u r e , C h a p te r s 1 – 7 p r e s e n t th e fu n d a m e n ta ls o f V is u a l C # p r o g r a m m in g a n d
s h o u ld b e c o v e r e d in s e q u e n c e . T h e n , y o u c a n m o v e d ir e c tly to C h a p te r 8 , C h a p te r 9 , o r
C h a p te r 1 1 . C h a p te r 1 0 s h o u ld b e c o v e r e d a fte r C h a p te r 9 .
xiii
xiv
P re fa c e
F ig u r e P -1
C h a p t e r d e p e n d e n c ie s
Chapters 1 - 7 (Cover in Order)
Programming and
Visual C# Fundamentals
Depend On
Chapter 8
Chapter 9
More about
Processing Data
Classes and
Multiform Projects
Chapter 11
Databases
Depends On
Chapter 10
Inheritance and
Polymorphism
F e a t u r e s o f t h e T e x t
C o n c e p t S t a t e m e n t s . E a c h m a jo r s e c tio n o f th e te x t s ta r ts w ith a c o n c e p t s ta te m e n t.
T h is s ta te m e n t c o n c is e ly s u m m a r iz e s th e m a in p o in t o f th e s e c tio n .
T u t o r ia ls . E a c h c h a p te r h a s s e v e r a l h a n d s -o n tu to r ia ls th a t g u id e th e s tu d e n t th r o u g h th e
d e v e lo p m e n t o f a n a p p lic a tio n . E a c h tu to r ia l p r o v id e s d e ta ile d , s te p -b y -s te p in s tr u c tio n s ,
a s w e ll a s th e a p p lic a tio n ’s c o m p le te d c o d e a n d s c r e e n c a p tu r e s o f th e c o m p le te d fo r m s .
E x a m p le P r o g r a m s . E a c h c h a p te r h a s a n a b u n d a n t n u m b e r o f c o d e e x a m p le s d e s ig n e d
to h ig h lig h t th e c u r r e n t to p ic .
N o t e s . N o te s a p p e a r a t s e v e r a l p la c e s th r o u g h o u t th e te x t. T h e y a r e s h o r t e x p la n a tio n s
o f in te r e s tin g o r o fte n m is u n d e r s to o d p o in ts r e le v a n t to th e to p ic a t h a n d .
T ip s . T ip s a d v is e th e s tu d e n t o n th e b e s t te c h n iq u e s fo r a p p r o a c h in g d iffe r e n t p r o g r a m m in g o r a n im a tio n p r o b le m s .
W a r n in g s . W a r n in g s c a u tio n s tu d e n ts a b o u t p r o g r a m m in g te c h n iq u e s o r p r a c tic e s th a t
c a n le a d to m a lfu n c tio n in g p r o g r a m s o r lo s t d a ta .
C h e c k p o in t s . C h e c k p o in ts a r e q u e s tio n s p la c e d a t in te r v a ls th r o u g h o u t e a c h c h a p te r .
T h e y a r e d e s ig n e d to q u e r y th e s tu d e n t’s k n o w le d g e q u ic k ly a fte r le a r n in g a n e w to p ic .
T h e a n s w e r s to th e C h e c k p o in t q u e s tio n s c a n b e fo u n d in A p p e n d ix D .
R e v ie w Q u e s t io n s . E a c h c h a p te r p r e s e n ts a th o r o u g h a n d d iv e r s e s e t o f R e v ie w
Q u e s tio n s . T h e y in c lu d e M u ltip le C h o ic e , T r u e /F a ls e , A lg o r ith m W o r k b e n c h , a n d S h o r t
An swer.
P r o g r a m m in g P r o b le m s . E a c h c h a p te r o ffe r s a p o o l o f P r o g r a m m in g P r o b le m s
d e s ig n e d to s o lid ify th e s tu d e n t’s k n o w le d g e o f th e to p ic s c u r r e n tly b e in g s tu d ie d .
V id e o N o t e s . E a c h tu to r ia l in th e b o o k h a s a n a c c o m p a n y in g o n lin e V id e o N o te th a t c a n
b e a c c e s s e d o n th e b o o k ’s c o m p a n io n W e b s ite w w w .p e a r s o n h ig h e r e d .c o m /g a d d is .
VideoNot e
S tu d e n ts c a n fo llo w a lo n g w ith th e a u th o r a s h e o r s h e w o r k s th r o u g h e a c h tu to r ia l in th e
v id e o s . A ls o , o n e p r o g r a m m in g p r o b le m a t th e e n d o f e a c h c h a p te r h a s a n a c c o m p a n y in g
V id e o N o te th a t s h o w s th e s tu d e n t h o w to c r e a te th e s o lu tio n .
P re fa c e
S u p p le m e n t s
S t u d e n t T h e fo llo w in g s u p p le m e n ta r y m a te r ia l is a v a ila b le w ith th e b o o k :
• S o u r c e c o d e a n d file s r e q u ir e d fo r th e c h a p te r tu to r ia ls a r e a v a ila b le a t w w w .
p e a r s o n h ig h e r e d .c o m /c s -r e s o u r c e s
• A c o m p le te s e t o f o n lin e V id e o N o te s th a t ta k e th e s tu d e n t th r o u g h e a c h tu to r ia l in
th e b o o k . A ls o , o n e p r o g r a m m in g p r o b le m fr o m e a c h c h a p te r h a s a n a c c o m p a n y in g
V id e o N o te th a t h e lp s th e s tu d e n t c r e a te a s o lu tio n . Y o u m a y a c c e s s th e V id e o N o te s
b y g o in g to w w w .p e a r s o n h ig h e r e d .c o m /c s -r e s o u r c e s .
I n s t r u c t o r T h e fo llo w in g s u p p le m e n ts a r e a v a ila b le to q u a lifie d in s tr u c to r s :
•
•
•
•
•
A n s w e r s to a ll R e v ie w Q u e s tio n s in th e te x t
S o lu tio n s fo r a ll P r o g r a m m in g P r o b le m s in th e te x t
C o m p le te d v e r s io n s o f a ll tu to r ia ls
P o w e r P o in t p r e s e n ta tio n s lid e s fo r e v e r y c h a p te r
Test b an k
F o r in fo r m a tio n o n h o w to a c c e s s th e s e s u p p le m e n ts , v is it th e P e a r s o n E d u c a tio n In s tr u c to r R e s o u r c e C e n te r a t w w w .p e a r s o n h ig h e r e d .c o m /ir c .
A c k n o w le d g m e n t s
T h e r e w e r e m a n y h e lp in g h a n d s in th e d e v e lo p m e n t a n d p u b lic a tio n o f th is te x t. I w o u ld
lik e to th a n k th e fo llo w in g fa c u lty r e v ie w e r s fo r th e ir h e lp fu l s u g g e s tio n s a n d e x p e r tis e
d u r in g th e p r o d u c tio n o f th is e d itio n :
M a tth e w A lim a g h a m
Spartanburg Community College
C a r o ly n B o r n e
L ouisiana State University
Arth u r E. Carter
Radford University
S a llie B . D o d s o n
Radford University
E liz a b e th F r e ije
I ndiana University—Purdue University, I ndianapolis
Bettye J. P arh am
D aytona State College
Wen d y L. P ayn e
Gulf Coast State College
Jaso n Sh arp
Tarleton State University
Jo h n Van Assen
York Technical College
R e g in a ld W h ite
Black H awk College
D a w n R . W ic k
Southwestern Community College
xv
xvi
P re fa c e
I w o u ld a ls o lik e to th a n k m y fa m ily a n d fr ie n d s fo r th e ir lo v e a n d s u p p o r t in a ll m y p r o je c ts . I a m e x tr e m e ly fo r tu n a te to h a v e M a tt G o ld s te in a s m y e d ito r . H is s u p p o r t a n d
e n c o u r a g e m e n t m a k e it a p le a s u r e to w r ite c h a p te r s a n d m e e t d e a d lin e s . I a m a ls o fo r tu n a te to h a v e D e m e tr iu s H a ll a n d B r a m V a n K e m p e n a s M a r k e tin g M a n a g e r s . T h e ir h a r d
w o r k is tr u ly in s p ir in g , a n d th e y d o a g r e a t jo b o f g e ttin g th is b o o k o u t to th e a c a d e m ic
c o m m u n ity . T h e p r o d u c tio n te a m , le d b y C a m ille T r e n ta c o s te , w o r k e d tir e le s s ly to m a k e
th is b o o k a r e a lity . T h a n k s to y o u a ll!
A b o u t t h e A u t h o r
T o n y G a d d i s i s t h e p r i n c i p a l a u t h o r o f t h e Starting O ut With s e r i e s o f t e x t b o o k s . T o n y
h a s n e a r ly 2 0 y e a r s e x p e r ie n c e te a c h in g c o m p u te r s c ie n c e c o u r s e s a t H a y w o o d C o m m u n ity C o lle g e in N o r th C a r o lin a . H e is a h ig h ly a c c la im e d in s tr u c to r w h o w a s p r e v io u s ly
s e le c te d a s th e N o r th C a r o lin a C o m m u n ity C o lle g e T e a c h e r o f th e Y e a r a n d h a s r e c e iv e d
th e T e a c h in g E x c e lle n c e A w a r d fr o m th e N a tio n a l In s titu te fo r S ta ff a n d O r g a n iz a tio n a l
D e v e lo p m e n t.
T h e Starting O ut With s e r i e s i n c l u d e s i n t r o d u c t o r y b o o k s u s i n g t h e C + + p r o g r a m m i n g
la n g u a g e , th e J a v a ™ p r o g r a m m in g la n g u a g e , M ic r o s o ft® V is u a l B a s ic ® , M ic r o s o ft®
C # ® , P y th o n , P r o g r a m m in g L o g ic a n d D e s ig n , M IT A p p In v e n to r , a n d A lic e , a ll p u b lis h e d
b y P e a r s o n E d u c a tio n .
A tte n tio n S tu d e n ts
In s t a llin g V is u a l S t u d io
T o c o m p le te th e tu to r ia ls a n d p r o g r a m m in g p r o b le m s in th is b o o k , y o u n e e d to in s ta ll
V is u a l S tu d io 2 0 1 5 , o r a la te r v e r s io n , o n y o u r c o m p u te r . W e r e c o m m e n d th a t y o u
d o w n lo a d V is u a l S tu d io C o m m u n ity 2 0 1 5 fr o m th e fo llo w in g w e b s ite , a n d in s ta ll it o n
yo u r system:
w w w .v is u a ls tu d io .c o m
V is u a l S tu d io C o m m u n ity 2 0 1 5 is a fr e e , fu ll-fe a tu r e d d e v e lo p m e n t e n v ir o n m e n t, a n d is a
p e r fe c t c o m p a n io n fo r th is te x tb o o k .
N O T E : If y o u a r e w o r k in g in y o u r s c h o o l’s c o m p u te r la b , th e r e is a g o o d c h a n c e
th a t M ic r o s o ft V is u a l S tu d io h a s a lr e a d y b e e n in s ta lle d . If th is is th e c a s e , y o u r
in s tr u c to r w ill s h o w y o u h o w to s ta r t V is u a l S tu d io .
In s t a llin g t h e S t u d e n t S a m p le P r o g r a m F ile s
T h e S tu d e n t S a m p le P r o g r a m file s th a t a c c o m p a n y th is b o o k a r e a v a ila b le fo r d o w n lo a d
fr o m th e b o o k ’s c o m p a n io n W e b s ite a t:
w w w .p e a r s o n h ig h e r e d .c o m /c s -r e s o u r c e s
T h e s e file s a r e r e q u ir e d fo r m a n y o f th e b o o k ’s tu to r ia ls . S im p ly d o w n lo a d th e S tu d e n t
S a m p le P r o g r a m file s to a lo c a tio n o n y o u r h a r d d r iv e w h e r e y o u c a n e a s ily a c c e s s th e m .
xvi i
This page intentionally left blank
8
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
r e p r e s e n ts th e n u m b e r 1 . T h is c o r r e s p o n d s p e r fe c tly to th e b in a r y n u m b e r in g s y s te m .
In th e b in a r y n u m b e r in g s y s te m (o r b in a r y , a s it is u s u a lly c a lle d ), a ll n u m e r ic v a lu e s
a r e w r itte n a s s e q u e n c e s o f 0 s a n d 1 s . H e r e is a n e x a m p le o f a n u m b e r th a t is w r itte n
in b in a r y :
10011101
T h e p o s itio n o f e a c h d ig it in a b in a r y n u m b e r h a s a v a lu e a s s ig n e d to it. S ta r tin g w ith th e
r ig h tm o s t d ig it a n d m o v in g le ft, th e p o s itio n v a lu e s a r e 2 0 , 2 1 , 2 2 , 2 3 , a n d s o fo r th , a s
s h o w n in F ig u r e 1 -8 . F ig u r e 1 -9 s h o w s th e s a m e d ia g r a m w ith th e p o s itio n v a lu e s c a lc u la te d . S ta r tin g w ith th e r ig h tm o s t d ig it a n d m o v in g le ft, th e p o s itio n v a lu e s a r e 1 , 2 , 4 , 8 ,
an d so fo rth .
F ig u r e 1 -8
T h e v a lu e s o f b in a r y d ig it s a s p o w e r s o f 2
10011101
2
2
2
2
2
2
2
2
F ig u r e 1 -9
T h e v a lu e s o f b in a r y d ig it s
10011101
1
2
4
8
16
32
64
128
T o d e te r m in e th e v a lu e o f a b in a r y n u m b e r , y o u s im p ly a d d u p th e p o s itio n v a lu e s o f a ll
th e 1 s . F o r e x a m p le , in th e b in a r y n u m b e r 1 0 0 1 1 1 0 1 , th e p o s itio n v a lu e s o f th e 1 s a r e 1 ,
4 , 8 , 1 6 , a n d 1 2 8 . T h is is s h o w n in F ig u r e 1 -1 0 . T h e s u m o f a ll th e s e p o s itio n v a lu e s is
1 5 7 . S o , th e v a lu e o f th e b in a r y n u m b e r 1 0 0 1 1 1 0 1 is 1 5 7 .
F ig u r e 1 -1 0
D e t e r m in in g t h e v a lu e o f 1 0 0 1 1 1 0 1
10011101
1
4
8
16
128
1 + 4 + 8 + 16 + 128 = 157
1 .3
H o w C o m p u te rs S to re D a ta
F ig u r e 1 -1 1 s h o w s h o w y o u c a n p ic tu r e th e n u m b e r 1 5 7 s to r e d in a b y te o f m e m o r y . E a c h
1 is r e p r e s e n te d b y a b it in th e o n p o s itio n , a n d e a c h 0 is r e p r e s e n te d b y a b it in th e
o ffp o s itio n .
F ig u r e 1 -1 1
T h e b it p a t t e r n fo r 1 5 7
1
Position
values
1
1
128
0
0
64
32
1
1
0
16
8
4
2
1
128 + 16 + 8 + 4 + 1 = 157
W h e n a ll th e b its in a b y te a r e s e t to 0 (tu r n e d o ff), th e n th e v a lu e o f th e b y te is 0 . W h e n
a ll th e b its in a b y te a r e s e t to 1 (tu r n e d o n ), th e n th e b y te h o ld s th e la r g e s t v a lu e th a t c a n
b e s to r e d in it. T h e la r g e s t v a lu e th a t c a n b e s to r e d in a b y te is 1 + 2 + 4 + 8 + 1 6 + 3 2 +
6 4 + 1 2 8 = 2 5 5 . T h is lim it e x is ts b e c a u s e th e r e a r e o n ly e ig h t b its in a b y te .
W h a t if y o u n e e d to s to r e a n u m b e r la r g e r th a n 2 5 5 ? T h e a n s w e r is s im p le : u s e m o r e th a n
1 b y te . F o r e x a m p le , s u p p o s e w e p u t 2 b y te s to g e th e r . T h a t g iv e s u s 1 6 b its . T h e p o s itio n
v a lu e s o f th o s e 1 6 b its w o u ld b e 2 0 , 2 1 , 2 2 , 2 3 , a n d s o fo r th , u p th r o u g h 2 1 5 . A s s h o w n in
F ig u r e 1 -1 2 , th e m a x im u m v a lu e th a t c a n b e s to r e d in 2 b y te s is 6 5 ,5 3 5 . If y o u n e e d to
s to r e a n u m b e r la r g e r th a n th is , th e n m o r e b y te s a r e n e c e s s a r y .
F ig u r e 1 -1 2
T w o b y te s u s e d fo r a la r g e n u m b e r
1
Position
values
1
32768 16384
1
1
1
1
1
1
1
1
1
1
1
1
1
1
8192
4096
2048
1024
512
256
128
64
32
16
8
4
2
1
32768 + 16384 + 8192 + 4096 + 2048 + 1024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 65535
T I P : In c a s e y o u ’r e fe e lin g o v e r w h e lm e d b y a ll th is , r e la x ! Y o u w ill n o t h a v e to
a c tu a lly c o n v e r t n u m b e r s to b in a r y w h ile p r o g r a m m in g . K n o w in g th a t th is p r o c e s s is
ta k in g p la c e in s id e th e c o m p u te r w ill h e lp y o u a s y o u le a r n , a n d in th e lo n g te r m th is
k n o w le d g e w ill m a k e y o u a b e tte r p r o g r a m m e r .
S t o r in g C h a r a c t e r s
A n y p ie c e o f d a ta th a t is s to r e d in a c o m p u te r ’s m e m o r y m u s t b e s to r e d a s a b in a r y n u m b e r . T h a t in c lu d e s c h a r a c te r s s u c h a s le tte r s a n d p u n c tu a tio n m a r k s . W h e n a c h a r a c te r is
s to r e d in m e m o r y , it is fir s t c o n v e r te d to a n u m e r ic c o d e . T h e n u m e r ic c o d e is th e n s to r e d
in m e m o r y a s a b in a r y n u m b e r .
O v e r th e y e a r s , d iffe r e n t c o d in g s c h e m e s h a v e b e e n d e v e lo p e d to r e p r e s e n t c h a r a c te r s in
c o m p u te r m e m o r y . H is to r ic a lly , th e m o s t im p o r ta n t o f th e s e c o d in g s c h e m e s is A S C II,
9
10
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
w h ic h s ta n d s fo r th e A m e r ic a n S ta n d a r d C o d e fo r In fo r m a tio n In te r c h a n g e . A S C II is a s e t
o f 1 2 8 n u m e r ic c o d e s th a t r e p r e s e n t th e E n g lis h le tte r s , v a r io u s p u n c tu a tio n m a r k s , a n d
o th e r c h a r a c te r s . F o r e x a m p le , th e A S C II c o d e fo r th e u p p e r c a s e le tte r A is 6 5 . W h e n y o u
ty p e a n u p p e r c a s e A o n y o u r c o m p u te r k e y b o a r d , th e n u m b e r 6 5 is s to r e d in m e m o r y (a s
a b in a r y n u m b e r , o f c o u r s e ). T h is is s h o w n in F ig u r e 1 -1 3 .
F ig u r e 1 -1 3
A
T I P :
T h e le t t e r A s t o r e d in m e m o r y a s t h e n u m b e r 6 5
1
1
65
0
0
0
0
0
0
T h e a c r o n y m A S C II is p r o n o u n c e d “ a s k e e .”
In c a s e y o u a r e c u r io u s , th e A S C II c o d e fo r u p p e r c a s e B is 6 6 , fo r u p p e r c a s e C is 6 7 , a n d
s o fo r th . A p p e n d ix C s h o w s a ll th e A S C II c o d e s a n d th e c h a r a c te r s th e y r e p r e s e n t.
T h e A S C II c h a r a c te r s e t w a s d e v e lo p e d in th e e a r ly 1 9 6 0 s a n d w a s e v e n tu a lly a d o p te d b y
a lm o s t a ll c o m p u te r m a n u fa c tu r e r s . A S C II is lim ite d , h o w e v e r , b e c a u s e it d e fin e s c o d e s
fo r o n ly 1 2 8 c h a r a c te r s . T o r e m e d y th is , th e U n ic o d e c h a r a c te r s e t w a s d e v e lo p e d in th e
e a r ly 1 9 9 0 s . U n ic o d e is a n e x te n s iv e e n c o d in g s c h e m e th a t is c o m p a tib le w ith A S C II a n d
c a n a ls o r e p r e s e n t th e c h a r a c te r s o f m a n y o f th e w o r ld ’s la n g u a g e s . T o d a y , U n ic o d e is
q u ic k ly b e c o m in g th e s ta n d a r d c h a r a c te r s e t u s e d in th e c o m p u te r in d u s tr y .
A d v a n c e d N u m b e r S t o r a g e
E a r lie r y o u s a w h o w n u m b e r s a r e s to r e d in m e m o r y . P e r h a p s it o c c u r r e d to y o u th e n th a t
th e b in a r y n u m b e r in g s y s te m c a n b e u s e d to r e p r e s e n t o n ly in te g e r n u m b e r s , b e g in n in g
w ith 0 . N e g a tiv e n u m b e r s a n d r e a l n u m b e r s (s u c h a s 3 .1 4 1 5 9 ) c a n n o t b e r e p r e s e n te d
u s in g th e s im p le b in a r y n u m b e r in g te c h n iq u e w e d is c u s s e d .
C o m p u te r s a r e a b le to s to r e n e g a tiv e n u m b e r s a n d r e a l n u m b e r s in m e m o r y , b u t to d o
s o th e y u s e e n c o d in g s c h e m e s a lo n g w ith th e b in a r y n u m b e r in g s y s te m . N e g a tiv e n u m b e r s a r e e n c o d e d u s in g a te c h n iq u e k n o w n a s tw o ’s c o m p le m e n t, a n d r e a l n u m b e r s a r e
e n c o d e d in flo a tin g -p o in t n o ta tio n . Y o u d o n ’t n e e d to k n o w h o w th e s e e n c o d in g
s c h e m e s w o r k , o n ly th a t th e y a r e u s e d to c o n v e r t n e g a tiv e n u m b e r s a n d r e a l n u m b e r s to
b in a r y fo r m a t.
O t h e r T y p e s o f D a t a
C o m p u te r s a r e o fte n r e fe r r e d to a s d ig ita l d e v ic e s . T h e te r m d ig ita l c a n b e u s e d to d e s c r ib e
a n y th in g th a t u s e s b in a r y n u m b e r s . D ig ita l d a ta is d a ta th a t is s to r e d in b in a r y , a n d a
d ig ita l d e v ic e is a n y d e v ic e th a t w o r k s w ith b in a r y d a ta . In th is s e c tio n , w e h a v e d is c u s s e d
h o w n u m b e r s a n d c h a r a c te r s a r e s to r e d in b in a r y , b u t c o m p u te r s a ls o w o r k w ith m a n y
o th e r ty p e s o f d ig ita l d a ta .
F o r e x a m p le , c o n s id e r th e p ic tu r e s th a t y o u ta k e w ith y o u r d ig ita l c a m e r a . T h e s e im a g e s
a r e c o m p o s e d o f tin y d o ts o f c o lo r k n o w n a s p ix e ls . (T h e te r m p ix e l s ta n d s fo r p ic tu r e e le m e n t.) A s s h o w n in F ig u r e 1 -1 4 , e a c h p ix e l in a n im a g e is c o n v e r te d to a n u m e r ic c o d e th a t
r e p r e s e n ts th e p ix e l’s c o lo r . T h e n u m e r ic c o d e is s to r e d in m e m o r y a s a b in a r y n u m b e r .
1 .4
F ig u r e 1 -1 5
H o w a P ro g ra m W o rk s
A p r o g r a m b e in g c o p ie d in t o m a in m e m o r y a n d t h e n e x e c u t e d
The program is copied
from secondary storage
to main memory.
The CPU executes
the program in
main memory.
Main memory
(RAM)
Disk drive
CPU
W h e n a C P U e x e c u te s th e in s tr u c tio n s in a p r o g r a m , it is e n g a g e d in a p r o c e s s th a t is
k n o w n a s th e fe tc h -d e c o d e -e x e c u te c y c le . T h is c y c le , w h ic h c o n s is ts o f th r e e s te p s , is
r e p e a te d fo r e a c h in s tr u c tio n in th e p r o g r a m . T h e s te p s a r e a s fo llo w s :
1 . F e tc h A p r o g r a m is a lo n g s e q u e n c e o f m a c h in e la n g u a g e in s tr u c tio n s . T h e fir s t s te p
o f th e c y c le is to fe tc h , o r r e a d , th e n e x t in s tr u c tio n fr o m m e m o r y in to th e C P U .
2 . D e c o d e A m a c h in e la n g u a g e in s tr u c tio n is a b in a r y n u m b e r th a t r e p r e s e n ts a c o m m a n d th a t te lls th e C P U to p e r fo r m a n o p e r a tio n . In th is s te p th e C P U d e c o d e s th e
in s tr u c tio n th a t w a s ju s t fe tc h e d fr o m m e m o r y , to d e te r m in e w h ic h o p e r a tio n it
s h o u ld p e r fo r m .
3 . E x e c u te T h e la s t s te p in th e c y c le is to e x e c u te , o r p e r fo r m , th e o p e r a tio n .
F ig u r e 1 -1 6 illu s tr a te s th e s e s te p s .
F ig u r e 1 -1 6
T h e fe tc h -d e c o d e -e x e c u te c y c le
10100001
1
10100001
10111000
10011110
00011010
11011100
and so forth...
Fetch the next instruction
in the program.
2
Decode the instruction
to determine which
operation to perform.
3
Execute the instruction
(perform the operation).
CPU
Main memory
(RAM)
F r o m M a c h in e L a n g u a g e t o A s s e m b ly L a n g u a g e
C o m p u te r s c a n e x e c u te o n ly p r o g r a m s th a t a r e w r itte n in m a c h in e la n g u a g e . A s p r e v io u s ly m e n tio n e d , a p r o g r a m c a n h a v e th o u s a n d s o r e v e n a m illio n o r m o r e b in a r y in s tr u c tio n s , a n d w r itin g s u c h a p r o g r a m w o u ld b e v e r y te d io u s a n d tim e c o n s u m in g .
P r o g r a m m in g in m a c h in e la n g u a g e w o u ld a ls o b e v e r y d iffic u lt b e c a u s e p u ttin g a 0 o r a 1
in th e w r o n g p la c e w o u ld c a u s e a n e r r o r .
A lth o u g h a c o m p u te r ’s C P U u n d e r s ta n d s o n ly m a c h in e la n g u a g e , it is im p r a c tic a l fo r
p e o p le to w r ite p r o g r a m s in m a c h in e la n g u a g e . F o r th is r e a s o n , a s s e m b ly la n g u a g e w a s
13
14
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
c r e a te d in th e e a r ly d a y s o f c o m p u tin g 2 a s a n a lte r n a tiv e to m a c h in e la n g u a g e . In s te a d o f
u s in g b in a r y n u m b e r s fo r in s tr u c tio n s , a s s e m b ly la n g u a g e u s e s s h o r t w o r d s th a t a r e
k n o w n a s m n e m o n i c s . F o r e x a m p l e , i n a s s e m b l y l a n g u a g e , t h e m n e m o n i c add t y p i c a l l y
m e a n s t o a d d n u m b e r s , mul t y p i c a l l y m e a n s t o m u l t i p l y n u m b e r s , a n d mov t y p i c a l l y m e a n s
to m o v e a v a lu e to a lo c a tio n in m e m o r y . W h e n a p r o g r a m m e r u s e s a s s e m b ly la n g u a g e to
w r ite a p r o g r a m , h e o r s h e c a n w r ite s h o r t m n e m o n ic s in s te a d o f b in a r y n u m b e r s .
N O T E : T h e r e a r e m a n y d iffe r e n t v e r s io n s o f a s s e m b ly la n g u a g e . It w a s m e n tio n e d
e a r lie r th a t e a c h b r a n d o f C P U h a s its o w n m a c h in e la n g u a g e in s tr u c tio n s e t. E a c h
b r a n d o f C P U ty p ic a lly h a s its o w n a s s e m b ly la n g u a g e a s w e ll.
A s s e m b ly la n g u a g e p r o g r a m s c a n n o t b e e x e c u te d b y th e C P U , h o w e v e r . T h e C P U u n d e r s ta n d s o n ly m a c h in e la n g u a g e , s o a s p e c ia l p r o g r a m k n o w n a s a n a s s e m b le r is u s e d to
tr a n s la te a n a s s e m b ly la n g u a g e p r o g r a m to a m a c h in e la n g u a g e p r o g r a m . T h is p r o c e s s is
s h o w n in F ig u r e 1 -1 7 . T h e C P U c a n th e n e x e c u te th e m a c h in e la n g u a g e p r o g r a m th a t th e
a s s e m b le r c r e a te s .
F i g u r e 1 - 1 7 A n a s s e m b le r t r a n s la t in g a n a s s e m b ly la n g u a g e p r o g r a m t o a m a c h in e
la n g u a g e p r o g r a m
Assembly Language
Program
Machine Language
Program
mov eax, Z
add eax, 2
mov Y, eax
10100001
and so forth...
Assembler
10111000
10011110
and so forth...
H ig h -L e v e l L a n g u a g e s
A lth o u g h a s s e m b ly la n g u a g e m a k e s it u n n e c e s s a r y to w r ite b in a r y m a c h in e la n g u a g e
in s tr u c tio n s , it is n o t w ith o u t d iffic u ltie s . A s s e m b ly la n g u a g e is p r im a r ily a d ir e c t s u b s titu te fo r m a c h in e la n g u a g e , a n d lik e m a c h in e la n g u a g e , it r e q u ir e s th a t y o u k n o w a lo t
a b o u t th e C P U . A s s e m b ly la n g u a g e a ls o r e q u ir e s th a t y o u w r ite a la r g e n u m b e r o f in s tr u c tio n s fo r e v e n th e s im p le s t p r o g r a m . B e c a u s e a s s e m b ly la n g u a g e is s o c lo s e in n a tu r e to
m a c h in e la n g u a g e , it is r e fe r r e d to a s a lo w -le v e l la n g u a g e .
In th e 1 9 5 0 s , a n e w g e n e r a tio n o f p r o g r a m m in g la n g u a g e s k n o w n a s h ig h -le v e l la n g u a g e s
b e g a n to a p p e a r . A h ig h -le v e l la n g u a g e a llo w s y o u to c r e a te p o w e r fu l a n d c o m p le x p r o g r a m s w ith o u t k n o w in g h o w th e C P U w o r k s a n d w ith o u t w r itin g la r g e n u m b e r s o f lo w le v e l in s tr u c tio n s . In a d d itio n , m o s t h ig h -le v e l la n g u a g e s u s e w o r d s th a t a r e e a s y to
u n d e r s ta n d . F o r e x a m p le , if a p r o g r a m m e r w e r e u s in g C O B O L (w h ic h w a s o n e o f th e
e a r ly h ig h -le v e l la n g u a g e s c r e a te d in th e 1 9 5 0 s ), h e o r s h e w o u ld w r ite th e fo llo w in g
i n s t r u c t i o n t o d i s p l a y t h e m e s s a g e H ello world o n t h e c o m p u t e r s c r e e n :
2
DISPLAY "Hello world"
T h e fi r s t a s s e m b l y l a n g u a g e w a s m o s t l i k e l y d e v e l o p e d i n t h e 1 9 4 0 s a t C a m b r i d g e U n i v e r s i t y f o r u s e w i t h a
h is to r ic a l c o m p u te r k n o w n a s th e E D S A C .
1 .4
H o w a P ro g ra m W o rk s
D o in g th e s a m e th in g in a s s e m b ly la n g u a g e w o u ld r e q u ir e s e v e r a l in s tr u c tio n s a n d a n
in tim a te k n o w le d g e o f h o w th e C P U in te r a c ts w ith th e c o m p u te r ’s v id e o c ir c u itr y . A s y o u
c a n s e e fr o m th is e x a m p le , h ig h -le v e l la n g u a g e s a llo w p r o g r a m m e r s to c o n c e n tr a te o n th e
ta s k s th e y w a n t to p e r fo r m w ith th e ir p r o g r a m s r a th e r th a n th e d e ta ils o f h o w th e C P U
w ill e x e c u te th o s e p r o g r a m s .
S in c e th e 1 9 5 0 s , th o u s a n d s o f h ig h -le v e l la n g u a g e s h a v e b e e n c r e a te d . T a b le 1 -1 lis ts s e v e r a l o f th e m o r e w e ll-k n o w n la n g u a g e s .
T a b le 1 -1
P r o g r a m m in g la n g u a g e s
Lan gu age
D e s c r ip tio n
Ad a
A d a w a s c r e a te d in th e 1 9 7 0 s , p r im a r ily fo r a p p lic a tio n s u s e d b y th e U .S .
D e p a r tm e n t o f D e fe n s e . T h e la n g u a g e is n a m e d in h o n o r o f C o u n te s s A d a
L o v e la c e , a n in flu e n tia l a n d h is to r ic a l fig u r e in th e fie ld o f c o m p u tin g .
BASIC
B e g in n e r s A ll-p u r p o s e S y m b o lic In s tr u c tio n C o d e is a g e n e r a l-p u r p o s e la n g u a g e
th a t w a s o r ig in a lly d e s ig n e d in th e e a r ly 1 9 6 0 s to b e s im p le e n o u g h fo r b e g in n e r s
to le a r n . T o d a y , th e r e a r e m a n y d iffe r e n t v e r s io n s o f B A S IC .
FORTRAN
F O R m u la T R A N s la to r w a s th e fir s t h ig h -le v e l p r o g r a m m in g la n g u a g e . It w a s
d e s ig n e d in th e 1 9 5 0 s fo r p e r fo r m in g c o m p le x m a th e m a tic a l c a lc u la tio n s .
COBOL
C o m m o n B u s in e s s -O r ie n te d L a n g u a g e w a s c r e a te d in th e 1 9 5 0 s a n d w a s d e s ig n e d
fo r b u s in e s s a p p lic a tio n s .
P ascal
P a s c a l w a s c r e a te d in 1 9 7 0 a n d w a s o r ig in a lly d e s ig n e d fo r te a c h in g p r o g r a m m in g .
T h e la n g u a g e w a s n a m e d in h o n o r o f th e m a th e m a tic ia n , p h y s ic is t, a n d
p h ilo s o p h e r B la is e P a s c a l.
C an d C+ +
C a n d C + + (p r o n o u n c e d “ c p lu s p lu s ” ) a r e p o w e r fu l, g e n e r a l-p u r p o s e la n g u a g e s
d e v e lo p e d a t B e ll L a b o r a to r ie s . T h e C la n g u a g e w a s c r e a te d in 1 9 7 2 , a n d th e C + +
la n g u a g e w a s c r e a te d in 1 9 8 3 .
C#
P r o n o u n c e d “ c s h a r p ,” th is la n g u a g e w a s c r e a te d b y M ic r o s o ft a r o u n d th e y e a r
2 0 0 0 fo r d e v e lo p in g a p p lic a tio n s b a s e d o n th e M ic r o s o ft .N E T p la tfo r m .
Java
J a v a w a s c r e a te d b y S u n M ic r o s y s te m s in th e e a r ly 1 9 9 0 s . It c a n b e u s e d to d e v e lo p
p r o g r a m s th a t r u n o n a s in g le c o m p u te r o r o v e r th e In te r n e t fr o m a W e b s e r v e r .
J a v a S c r ip t
J a v a S c r ip t, c r e a te d in th e 1 9 9 0 s , c a n b e u s e d in W e b p a g e s . D e s p ite its n a m e ,
J a v a S c r ip t is n o t r e la te d to J a v a .
P yth o n
P y th o n is a g e n e r a l-p u r p o s e la n g u a g e c r e a te d in th e e a r ly 1 9 9 0 s . It h a s b e c o m e
p o p u la r in b u s in e s s a n d a c a d e m ic a p p lic a tio n s .
Ru b y
R u b y is a g e n e r a l-p u r p o s e la n g u a g e th a t w a s c r e a te d in th e 1 9 9 0 s . It is in c r e a s in g ly
b e c o m in g a p o p u la r la n g u a g e fo r p r o g r a m s th a t r u n o n W e b s e r v e r s .
V is u a l B a s ic
V is u a l B a s ic (c o m m o n ly k n o w n a s V B ) is a M ic r o s o ft p r o g r a m m in g la n g u a g e a n d
s o ftw a r e d e v e lo p m e n t e n v ir o n m e n t th a t a llo w s p r o g r a m m e r s to c r e a te W in d o w s b a s e d a p p lic a tio n s q u ic k ly . V B w a s o r ig in a lly c r e a te d in th e e a r ly 1 9 9 0 s .
K e y w o r d s , O p e r a t o r s , a n d S y n t a x : A n O v e r v ie w
E a c h h ig h -le v e l la n g u a g e h a s its o w n s e t o f p r e d e fin e d w o r d s th a t th e p r o g r a m m e r m u s t u s e
to w r ite a p r o g r a m . T h e w o r d s th a t m a k e u p a h ig h -le v e l p r o g r a m m in g la n g u a g e a r e k n o w n
a s k e y w o r d s o r r e s e r v e d w o r d s . E a c h k e y w o r d h a s a s p e c ific m e a n in g a n d c a n n o t b e u s e d
fo r a n y o th e r p u r p o s e . T a b le 1 -2 s h o w s th e k e y w o r d s in th e C # p r o g r a m m in g la n g u a g e .
15
16
C h a p te r 1
T a b le 1 -2
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
T h e C # k e y w o rd s
abstract
as
base
bool
break
byte
case
catch
char
checked
class
const
continue
decimal
default
delegate
do
double
else
enum
event
explicit
extern
false
finally
fixed
float
for
foreach
goto
if
implicit
in
is
int
lock
interface
long
internal
namespace
new
null
object
operator
out
override
params
private
protected
public
readonly
ref
return
sbyte
sealed
short
sizeof
stackalloc
static
string
struct
switch
this
throw
true
try
typeof
uint
ulong
unchecked
unsafe
ushort
using
virtual
void
volatile
while
In a d d itio n to k e y w o r d s , p r o g r a m m in g la n g u a g e s h a v e o p e r a to r s th a t p e r fo r m v a r io u s
o p e r a tio n s o n d a ta . F o r e x a m p le , a ll p r o g r a m m in g la n g u a g e s h a v e m a th o p e r a to r s th a t
p e r fo r m a r ith m e tic . In C # , a s w e ll a s m o s t o th e r la n g u a g e s , th e + s ig n is a n o p e r a to r th a t
a d d s tw o n u m b e r s . T h e fo llo w in g a d d s 1 2 a n d 7 5 :
12 + 75
T h e r e a r e n u m e r o u s o th e r o p e r a to r s in th e C # la n g u a g e , m a n y o f w h ic h y o u w ill le a r n
a b o u t a s y o u p r o g r e s s th r o u g h th is te x t.
In a d d itio n to k e y w o r d s a n d o p e r a to r s , e a c h la n g u a g e a ls o h a s its o w n s y n ta x , w h ic h is a
s e t o f r u le s th a t m u s t b e s tr ic tly fo llo w e d w h e n w r itin g a p r o g r a m . T h e s y n ta x r u le s d ic ta te h o w k e y w o r d s , o p e r a to r s , a n d v a r io u s p u n c tu a tio n c h a r a c te r s m u s t b e u s e d in a
p r o g r a m . W h e n y o u a r e le a r n in g a p r o g r a m m in g la n g u a g e , y o u m u s t le a r n th e s y n ta x
r u le s fo r th a t p a r tic u la r la n g u a g e .
T h e in d iv id u a l in s tr u c tio n s th a t y o u u s e to w r ite a p r o g r a m in a h ig h -le v e l p r o g r a m m in g
la n g u a g e a r e c a lle d s ta te m e n ts . A p r o g r a m m in g s ta te m e n t c a n c o n s is t o f k e y w o r d s , o p e r a to r s , p u n c tu a tio n , a n d o th e r a llo w a b le p r o g r a m m in g e le m e n ts , a r r a n g e d in th e p r o p e r
s e q u e n c e to p e r fo r m a n o p e r a tio n .
C o m p ile r s a n d In t e r p r e t e r s
B e c a u s e th e C P U u n d e r s ta n d s o n ly m a c h in e la n g u a g e in s tr u c tio n s , p r o g r a m s th a t a r e
w r itte n in a h ig h -le v e l la n g u a g e m u s t b e tr a n s la te d in to m a c h in e la n g u a g e . D e p e n d in g o n
th e la n g u a g e in w h ic h a p r o g r a m h a s b e e n w r itte n , th e p r o g r a m m e r w ill u s e e ith e r a c o m p ile r o r a n in te r p r e te r to m a k e th e tr a n s la tio n .
A c o m p ile r is a p r o g r a m th a t tr a n s la te s a h ig h -le v e l la n g u a g e p r o g r a m in to a s e p a r a te
m a c h in e la n g u a g e p r o g r a m . T h e m a c h in e la n g u a g e p r o g r a m c a n th e n b e e x e c u te d a n y
1 .4
H o w a P ro g ra m W o rk s
tim e it is n e e d e d . T h is is s h o w n in F ig u r e 1 -1 8 . A s s h o w n in th e fig u r e , c o m p ilin g a n d
e x e c u tin g a r e tw o d iffe r e n t p r o c e s s e s .
F ig u r e 1 -1 8
1
C o m p ilin g a h ig h - le v e l p r o g r a m a n d e x e c u t in g it
The compiler is used
to translate the high-level
language program to a
machine language program.
High-level language
program
Machine language
program
Display "Hello,
Earthling"
10100001
10111000
10011110
and so forth...
and so forth...
Machine language
program
2
The machine language
program can be executed
at any time, without using
the compiler.
Compiler
CPU
10100001
10111000
10011110
and so forth...
S o m e p r o g r a m m in g la n g u a g e s u s e a n in te r p r e te r , w h ic h is a p r o g r a m th a t b o th tr a n s la te s
a n d e x e c u te s th e in s tr u c tio n s in a h ig h -le v e l la n g u a g e p r o g r a m . A s th e in te r p r e te r r e a d s
e a c h in d iv id u a l in s tr u c tio n in th e p r o g r a m , it c o n v e r ts it to a m a c h in e la n g u a g e in s tr u c tio n a n d th e n im m e d ia te ly e x e c u te s it. T h is p r o c e s s r e p e a ts fo r e v e r y in s tr u c tio n in th e
p r o g r a m . T h is p r o c e s s is illu s tr a te d in F ig u r e 1 -1 9 . B e c a u s e in te r p r e te r s c o m b in e tr a n s la tio n a n d e x e c u tio n , th e y ty p ic a lly d o n o t c r e a te s e p a r a te m a c h in e la n g u a g e p r o g r a m s .
F ig u r e 1 -1 9
E x e c u t in g a h ig h - le v e l p r o g r a m w it h a n in t e r p r e t e r
program
Display "Hello,
Earthling"
Interpreter
Machine language
instruction
10100001
CPU
and so forth...
The interpreter translates each high-level instruction to
its equivalent machine language instructions and
immediately executes them.
This process is repeated for each high-level instruction.
T h e s ta te m e n ts th a t a p r o g r a m m e r w r ite s in a h ig h -le v e l la n g u a g e a r e c a lle d s o u r c e c o d e ,
o r s im p ly c o d e . T y p ic a lly , th e p r o g r a m m e r ty p e s a p r o g r a m ’s c o d e in to a te x t e d ito r a n d
th e n s a v e s th e c o d e in a file o n th e c o m p u te r ’s d is k . N e x t, th e p r o g r a m m e r u s e s a c o m p ile r
to tr a n s la te th e c o d e in to a m a c h in e la n g u a g e p r o g r a m o r a n in te r p r e te r to tr a n s la te a n d
e x e c u te th e c o d e . If th e c o d e c o n ta in s a s y n ta x e r r o r , h o w e v e r , it c a n n o t b e tr a n s la te d . A
s y n ta x e r r o r is a m is ta k e s u c h a s a m is s p e lle d k e y w o r d , a m is s in g p u n c tu a tio n c h a r a c te r ,
o r th e in c o r r e c t u s e o f a n o p e r a to r . W h e n th is h a p p e n s , th e c o m p ile r o r in te r p r e te r d is p la y s a n e r r o r m e s s a g e , in d ic a tin g th a t th e p r o g r a m c o n ta in s a s y n ta x e r r o r . T h e p r o g r a m m e r c o r r e c ts th e e r r o r a n d th e n a tte m p ts o n c e a g a in to tr a n s la te th e p r o g r a m .
17
28
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
T u t o r ia l 1 -1 :
S t a r t in g V is u a l S t u d io a n d S e t t in g U p t h e E n v ir o n m e n t
S t e p 1 :
D e p e n d in g o n y o u r o p e r a tin g s y s te m , u s e o n e o f th e fo llo w in g p r o c e d u r e s to
s ta r t V is u a l S tu d io :
VideoNot e
• W i n d o w s 1 0 : O p e n t h e Start m e n u , a n d t h e n s e l e c t All Apps. S c r o l l d o w n i n
t h e l i s t . W h e n y o u s e e Visual Studio 2015 a p p e a r , c l i c k i t .
• W in d o w s 8 : O n th e S ta r t s c r e e n , s im p ly s ta r t ty p in g V is u a l S tu d io . A s y o u
ty p e , th e s e a r c h r e s u lts w ill a p p e a r o n th e r ig h t e d g e o f th e s c r e e n . W h e n y o u
s e e Visual Studio 2015 a p p e a r , c l i c k i t .
• W i n d o w s 7 : C l i c k t h e Start b u t t o n , a n d t h e n s e l e c t All Programs. O p e n t h e
V i s u a l S t u d i o 2 0 1 5 p r o g r a m g r o u p , a n d c l i c k Visual Studio 2015.
T u to r ia l 1 -1 :
S ta r tin g
V is u a l S tu d io
a n d S e ttin g
Up th e
E n v ir o n m e n t
S t e p 2 :
F ig u r e 1 -2 9 s h o w s th e V is u a l S tu d io e n v ir o n m e n t. T h e s c r e e n s h o w n in th e fig u r e i s k n o w n a s t h e Start Page. B y d e f a u l t , t h e Start Page i s d i s p l a y e d w h e n y o u
s ta r t V is u a l S tu d io , b u t y o u m a y n o t s e e it b e c a u s e it c a n b e d is a b le d .
N o t i c e t h e c h e c k b o x i n t h e b o t t o m l e f t c o r n e r o f t h e Start Page t h a t r e a d s Show
page on startup. I f t h i s b o x i s n o t c h e c k e d , t h e Start Page w i l l n o t b e d i s p l a y e d
w h e n y o u s t a r t V i s u a l S t u d i o . I f y o u d o n o t s e e t h e Start Page, y o u c a n a l w a y s
d i s p l a y i t b y c l i c k i n g View o n t h e m e n u b a r a t t h e t o p o f t h e s c r e e n a n d t h e n
c l i c k i n g Start Page.
F ig u r e 1 -2 9
S t e p 3 :
V i s u a l S t u d i o Sta rt Pa ge
In a s c h o o l c o m p u te r la b , it is p o s s ib le th a t th e V is u a l S tu d io e n v ir o n m e n t
h a s b e e n s e t u p fo r a p r o g r a m m in g la n g u a g e o th e r th a n V is u a l C # . T o m a k e
s u r e th a t V is u a l S tu d io lo o k s a n d b e h a v e s a s d e s c r ib e d in th is b o o k , y o u
s h o u ld m a k e s u r e th a t V is u a l C # is s e le c te d a s th e p r o g r a m m in g e n v ir o n m e n t. P e r fo r m th e fo llo w in g :
1 .8
G e t t in g S t a r t e d w it h t h e V is u a l S t u d io E n v ir o n m e n t
• A s s h o w n i n F i g u r e 1 - 3 0 , c l i c k Tools o n t h e m e n u b a r a n d t h e n c l i c k I mport
and Export Settings. . . .
• O n t h e s c r e e n t h a t a p p e a r s n e x t , s e l e c t Reset all settings a n d c l i c k t h e
N ext > b u t t o n .
• O n t h e s c r e e n t h a t a p p e a r s n e x t , s e l e c t N o, just reset settings, overwriting my
current settings. C l i c k t h e N ext > b u t t o n .
• T h e w i n d o w s h o w n i n F i g u r e 1 - 3 1 s h o u l d a p p e a r n e x t . S e l e c t Visual C# a n d
t h e n c l i c k t h e Finish b u t t o n . A f t e r a m o m e n t y o u s h o u l d s e e a Reset Complete
w i n d o w . C l i c k t h e Close b u t t o n a n d c o n t i n u e w i t h t h e n e x t s t e p i n t h e t u t o r i a l .
F ig u r e 1 -3 0
S e l e c t i n g Tools a n d t h e n Import a nd Export Settings . . .
F ig u r e 1 -3 1
S e l e c t i n g Visua l C# D e v e l o p m e n t S e t t i n g s
S t e p 4 :
N o w y o u w ill r e s e t V is u a l S tu d io ’s w in d o w la y o u t to th e d e fa u lt c o n fig u r a tio n .
A s s h o w n i n F i g u r e 1 - 3 2 , c l i c k Window o n t h e m e n u b a r a n d t h e n c l i c k Reset
Window L ayout. N e x t y o u w i l l s e e a d i a l o g b o x a s k i n g Are you sure you want
to restore the default window layout for the environment? C l i c k Yes.
29
30
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
T h e V is u a l S tu d io e n v ir o n m e n t is n o w s e t u p s o y o u c a n fo llo w th e r e m a in in g
tu to r ia ls in th is b o o k . If y o u a r e w o r k in g in y o u r s c h o o l’s c o m p u te r la b , it is
p r o b a b ly a g o o d id e a to g o th r o u g h th e s e s te p s e a c h tim e y o u s ta r t V is u a l S tu d io . If y o u a r e c o n tin u in g w ith th e n e x t tu to r ia l, le a v e V is u a l S tu d io r u n n in g .
Y o u c a n e x i t V i s u a l S t u d i o a t a n y t i m e b y c l i c k i n g File o n t h e m e n u b a r a n d
t h e n c l i c k i n g Exit.
F ig u r e 1 -3 2
R e s e t t in g t h e w in d o w la y o u t
S t a r t in g a N e w P r o je c t
E a c h V is u a l C # a p p lic a tio n th a t y o u c r e a te is c a lle d a p r o je c t. W h e n y o u a r e r e a d y to c r e a te a n e w a p p lic a tio n , y o u s ta r t a n e w p r o je c t. T u to r ia l 1 -2 le a d s y o u th r o u g h th e s te p s o f
s ta r tin g a n e w V is u a l C # p r o je c t.
T u t o r ia l 1 -2 :
S t a r t in g a N e w V is u a l C # P r o je c t
VideoNot e
T u to r ia l 1 -2 :
S ta r tin g a
N e w V is u a l
C # P r o je c t
S t e p 1 :
If V is u a l S tu d io is n o t a lr e a d y r u n n in g , s ta r t it a s y o u d id in T u to r ia l 1 -1 .
S t e p 2 :
C l i c k File o n t h e m e n u b a r a t t h e t o p o f t h e s c r e e n , t h e n s e l e c t N ew, a n d t h e n
s e l e c t Project. A f t e r d o i n g t h i s , t h e N ew Project w i n d o w s h o w n i n F i g u r e 1 - 3 3
s h o u ld b e d is p la y e d .
S t e p 3 :
A t t h e l e f t s i d e o f t h e w i n d o w , u n d e r I nstalled Templates, m a k e s u r e Visual C#
i s s e l e c t e d . T h e n , s e l e c t Windows Forms Application, a s s h o w n i n F i g u r e 1 - 3 3 .
S t e p 4 :
A t t h e b o t t o m o f t h e N ew Project w i n d o w , y o u s e e a N ame t e x t b o x . T h i s i s
w h e r e y o u e n t e r t h e n a m e o f y o u r p r o j e c t . T h e N ame t e x t b o x w i l l b e a u t o m a tic a lly fille d in w ith a d e fa u lt n a m e . In F ig u r e 1 -3 3 th e d e fa u lt n a m e is
WindowsApplication1. C h a n g e t h e p r o j e c t n a m e t o M y First Project, a s s h o w n
in F ig u r e 1 -3 4 .
1 .8
F ig u r e 1 -3 3
T h e New Project w i n d o w
Make sure
1 Visual C#
is selected
F ig u r e 1 -3 4
G e t t in g S t a r t e d w it h t h e V is u a l S t u d io E n v ir o n m e n t
2
Select Windows
Forms Application
C h a n g i n g t h e p r o j e c t n a m e t o My First Project
Change the project
name to My First
Project
J u s t b e l o w t h e N ame t e x t b o x y o u w i l l s e e a L ocation t e x t b o x a n d a Solution
name t e x t b o x .
• T h e L ocation t e x t b o x s h o w s w h e r e a f o l d e r w i l l b e c r e a t e d t o h o l d t h e p r o j e c t . I f y o u w i s h t o c h a n g e t h e l o c a t i o n , c l i c k t h e Browse b u t t o n a n d s e l e c t
th e d e s ir e d lo c a tio n .
• A s o l u t i o n i s a c o n t a i n e r t h a t h o l d s a p r o j e c t , a n d t h e Solution name t e x t
b o x s h o w s th e n a m e o f th e s o lu tio n th a t w ill h o ld th is p r o je c t. B y d e fa u lt,
th e s o lu tio n n a m e is th e s a m e a s th e p r o je c t n a m e . F o r a ll th e p r o je c ts th a t
y o u c r e a te in th is b o o k , y o u s h o u ld k e e p th e s o lu tio n n a m e th e s a m e a s th e
p r o je c t n a m e .
N O T E : A s y o u w o r k th r o u g h th is b o o k , y o u w ill c r e a te a lo t o f V is u a l C # p r o j e c t s . A s y o u d o , y o u w i l l f i n d t h a t d e f a u l t n a m e s s u c h a s WindowsApplication1
d o n o t h e lp y o u r e m e m b e r w h a t e a c h p r o je c t d o e s ; th e r e fo r e , y o u s h o u ld
a lw a y s c h a n g e th e n a m e o f a n e w p r o je c t to s o m e th in g th a t d e s c r ib e s th e
p r o je c t’s p u r p o s e .
S t e p 5 .
C l i c k t h e Ok b u t t o n t o c r e a t e t h e p r o j e c t . I t m i g h t t a k e a m o m e n t f o r t h e
p r o je c t to b e c r e a te d . O n c e it is , th e V is u a l S tu d io e n v ir o n m e n t s h o u ld
31
32
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
a p p e a r , s i m i l a r t o F i g u r e 1 - 3 5 . N o t i c e t h a t t h e n a m e o f t h e p r o j e c t , M y First
Project, i s d i s p l a y e d i n t h e t i t l e b a r a t t h e t o p o f t h e V i s u a l S t u d i o w i n d o w .
L e a v e V is u a l S tu d io r u n n in g a n d c o m p le te th e n e x t tu to r ia l.
F ig u r e 1 -3 5
T h e V is u a l S t u d io e n v ir o n m e n t w it h a n e w p r o je c t o p e n
T u t o r ia l 1 -3 :
S a v in g a n d C lo s in g a P r o je c t
VideoNot e
T u to r ia l 1 -3 :
S a v in g a n d
C lo s in g a
P r o je c t
A s y o u w o r k o n a p r o je c t, y o u s h o u ld g e t in to th e h a b it o f s a v in g it o fte n . In th is tu to r ia l
y o u w i l l s a v e t h e M y First Project a p p l i c a t i o n a n d t h e n c l o s e i t .
S t e p 1 :
V is u a l S tu d io s h o u ld s till b e r u n n in g fr o m th e p r e v io u s tu to r ia l. T o s a v e
t h e p r o j e c t t h a t i s c u r r e n t l y o p e n , c l i c k File o n t h e m e n u b a r a n d t h e n s e l e c t
Save All.
S t e p 2 :
T o c l o s e t h e p r o j e c t , c l i c k File o n t h e m e n u b a r a n d t h e n c l i c k Close Solution.
T h e V is u a l S t u d io E n v ir o n m e n t
T h e V is u a l S tu d io e n v ir o n m e n t c o n s is ts o f a n u m b e r o f w in d o w s th a t y o u w ill u s e o n a
r e g u la r b a s is . F ig u r e 1 -3 6 s h o w s th e lo c a tio n s o f th e fo llo w in g w in d o w s th a t a p p e a r
w i t h i n t h e V i s u a l S t u d i o e n v i r o n m e n t : t h e Desi gner w i n d o w , t h e Soluti on Explorer
w i n d o w , a n d t h e Properties w i n d o w . H e r e i s a b r i e f s u m m a r y o f e a c h w i n d o w ’ s p u r p o s e :
1 .8
G e t t in g S t a r t e d w it h t h e V is u a l S t u d io E n v ir o n m e n t
• T h e Designer W i n d o w
Y o u u s e t h e D esigner w i n d o w t o c r e a t e a n a p p l i c a t i o n ’ s g r a p h i c a l u s e r i n t e r f a c e . T h e
D esigner w i n d o w s h o w s t h e a p p l i c a t i o n ’ s f o r m a n d a l l o w s y o u t o v i s u a l l y d e s i g n i t s
a p p e a r a n c e b y p la c in g th e d e s ir e d c o n tr o ls th a t w ill a p p e a r o n th e fo r m w h e n th e
a p p lic a tio n e x e c u te s .
• T h e Solution Explorer W i n d o w
A s o lu tio n is a c o n ta in e r fo r h o ld in g Vis u a l C # p r o je c ts . (We d is c u s s s o lu tio n s in
g r e a te r d e ta il in a m o m e n t.) W h e n y o u c r e a te a n e w C # p r o je c t, a n e w s o lu tio n is
a u t o m a t i c a l l y c r e a t e d t o c o n t a i n i t . T h e Solution Explorer w i n d o w a l l o w s y o u t o
n a v i g a t e a m o n g t h e fi l e s i n a V i s u a l C # p r o j e c t .
• T h e Properties W i n d o w
A c o n t r o l ’s a p p e a r a n c e a n d o t h e r c h a r a c t e r i s t i c s a r e d e t e r m i n e d b y t h e c o n t r o l ’s
p r o p e r t i e s . W h e n y o u a r e c r e a t i n g a V i s u a l C # a p p l i c a t i o n , y o u u s e t h e Properties
w i n d o w t o e x a m i n e a n d c h a n g e a c o n t r o l ’s p r o p e r t i e s .
R e m e m b e r th a t Vis u a l S tu d io is a c u s to m iz a b le e n v ir o n m e n t. Yo u c a n m o v e th e
v a r io u s w in d o w s a r o u n d , s o th e y m a y n o t a p p e a r in th e e x a c t lo c a tio n s s h o w n in
F ig u r e 1 -3 6 o n y o u r s y s te m .
F ig u r e 1 -3 6
T h e Designer w i n d o w , Solution Explorer w i n d o w , a n d Properties w i n d o w
Solution Explorer
window
Designer window
Properties
window
D i s p l a y i n g t h e Solution Explor er a n d Pr oper ties W i n d o w s
I f y o u d o n o t s e e t h e Solution Explorer o r t h e Properties w i n d o w , y o u c a n f o l l o w t h e s e
s te p s to m a k e th e m v is ib le :
• I f y o u d o n o t s e e t h e Solution Explorer w i n d o w , c l i c k View o n t h e m e n u b a r . O n t h e
View m e n u , c l i c k Solution Explorer.
• I f y o u d o n o t s e e t h e Properties w i n d o w , c l i c k View o n t h e m e n u b a r . O n t h e View
m e n u , c l i c k Properties.
U s in g A u t o H id e
M a n y w in d o w s in V is u a l S tu d io h a v e a fe a tu r e k n o w n a s A u to H id e . W h e n y o u s e e th e
p u s h p in ic o n in a w in d o w ’s title b a r , a s s h o w n in F ig u r e 1 -3 7 , y o u k n o w th a t th e w in d o w
33
34
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
h a s A u to H id e c a p a b ility . Y o u c lic k th e p u s h p in ic o n to tu r n A u to H id e o n o r o ff fo r
a w in d o w .
W h e n A u to H id e is tu r n e d o n , th e w in d o w is d is p la y e d o n ly a s a ta b a lo n g o n e o f th e
e d g e s o f th e V is u a l S tu d io e n v ir o n m e n t. T h is fe a tu r e g iv e s y o u m o r e r o o m to v ie w
y o u r a p p l i c a t i o n ’ s f o r m s a n d c o d e . F i g u r e 1 - 3 8 s h o w s h o w t h e Solution Explorer a n d
Properties w i n d o w s a p p e a r w h e n t h e i r A u t o H i d e f e a t u r e i s t u r n e d o n . N o t i c e t h e
t a b s t h a t r e a d Solution Explorer a n d Properties a l o n g t h e r i g h t e d g e o f t h e s c r e e n .
( F i g u r e 1 - 3 8 a l s o s h o w s a Team Explorer t a b . W e d o n o t d i s c u s s t h e Team Explorer
in th is b o o k .)
F ig u r e 1 -3 7
Auto Hide p u s h p i n i c o n
Pushpin icon
F ig u r e 1 -3 8
T h e Solution Explorer a n d Properties w i n d o w s h i d d e n
Solution Explorer tab
Properties tab
1 .8
G e t t in g S t a r t e d w it h t h e V is u a l S t u d io E n v ir o n m e n t
T h e M e n u B a r a n d t h e S t a n d a r d T o o lb a r
Y o u ’v e a lr e a d y u s e d th e V is u a l S tu d io m e n u b a r s e v e r a l tim e s . T h is is th e b a r a t th e to p o f
t h e V i s u a l S t u d i o w i n d o w t h a t p r o v i d e s m e n u s s u c h a s File, Edit, View, Project, a n d s o
fo r th . A s y o u p r o g r e s s th r o u g h th is b o o k , y o u w ill b e c o m e fa m ilia r w ith m a n y o f th e m e n u s .
B e lo w th e m e n u b a r is th e s ta n d a r d to o lb a r . T h e s ta n d a r d to o lb a r c o n ta in s b u tto n s th a t
e x e c u te fr e q u e n tly u s e d c o m m a n d s . A ll c o m m a n d s th a t a r e d is p la y e d o n th e to o lb a r m a y
a ls o b e e x e c u te d fr o m a m e n u , b u t th e s ta n d a r d to o lb a r g iv e s y o u q u ic k e r a c c e s s to th e m .
F ig u r e 1 -3 9 id e n tifie s th e s ta n d a r d to o lb a r b u tto n s th a t y o u w ill u s e m o s t o fte n , a n d
T a b le 1 -3 g iv e s a b r ie f d e s c r ip tio n o f e a c h .
F ig u r e 1 -3 9
Navigate
Backward
V is u a l S t u d io t o o lb a r b u t t o n s
New
Project
Navigate
Forward
Save
Open
File
T a b le 1 -3
Solution
Configuration
Undo
Save
All
Solution
Platform
Start
Debugging
Redo
Find
V is u a l S t u d io t o o lb a r b u t t o n s
T o o lb a r B u tto n
D e s c r ip tio n
N a v ig a te B a c k w a r d
M o v e s t o t h e p r e v i o u s l y a c t i v e t a b i n t h e D esigner
w in d o w
N a v ig a te F o r w a r d
M o v e s t o t h e n e x t a c t i v e t a b i n t h e D esigner w i n d o w
N e w P r o je c t
S ta r ts a n e w p r o je c t
O p e n F ile
O p e n s a n e x is tin g file
Save
S a v e s t h e f i l e n a m e d b y filename
S a v e A ll
S a v e s a ll th e file s in th e c u r r e n t p r o je c t
Un d o
U n d o e s th e m o s t r e c e n t o p e r a tio n
Red o
R e d o e s th e m o s t r e c e n tly u n d o n e o p e r a tio n
S o lu tio n C o n fig u r a tio n s
C o n fig u r e s y o u r p r o je c t’s e x e c u ta b le c o d e
S o lu tio n P la tfo r m
L e ts y o u s e le c t th e p la tfo r m o n w h ic h th e a p p lic a tio n
w ill r u n
S ta r t D e b u g g in g
S ta r ts d e b u g g in g (r u n n in g ) y o u r p r o g r a m
F in d
S e a r c h e s fo r te x t in y o u r a p p lic a tio n c o d e
T h e Toolbox
T h e Toolbox i s a w i n d o w t h a t a l l o w s y o u t o s e l e c t t h e c o n t r o l s t h a t y o u w a n t t o u s e i n a n
a p p lic a tio n ’s u s e r in te r fa c e . W h e n y o u w a n t to p la c e a B u tto n , L a b e l, T e x tB o x , o r o th e r
c o n t r o l o n a n a p p l i c a t i o n ’ s f o r m , y o u s e l e c t i t i n t h e Toolbox. Y o u w i l l u s e t h e Toolbox
e x te n s iv e ly a s y o u d e v e lo p V is u a l C # a p p lic a tio n s .
T h e Toolbox t y p i c a l l y a p p e a r s o n t h e l e f t s i d e o f t h e V i s u a l S t u d i o e n v i r o n m e n t . I f t h e
Toolbox i s i n A u t o H i d e m o d e , i t s t a b w i l l a p p e a r a s s h o w n i n F i g u r e 1 - 4 0 . F i g u r e 1 - 4 1
s h o w s t h e Toolbox o p e n e d , w i t h A u t o H i d e t u r n e d o f f .
35
36
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
F ig u r e 1 -4 0
T h e Toolbox t a b ( A u t o H i d e t u r n e d o n )
Toolbox tab
F ig u r e 1 -4 1
T h e Toolbox o p e n e d ( A u t o H i d e t u r n e d o f f )
N O T E : I f y o u d o n o t s e e t h e Toolbox o r i t s t a b a l o n g t h e s i d e o f t h e V i s u a l S t u d i o
e n v i r o n m e n t , c l i c k View o n t h e m e n u b a r a n d t h e n c l i c k Toolbox.
T h e Toolbox i s d i v i d e d i n t o s e c t i o n s , a n d e a c h s e c t i o n h a s a n a m e . I n F i g u r e 1 - 4 1 y o u c a n
s e e t h e All Windows Forms a n d Common Controls s e c t i o n s . I f y o u s c r o l l t h e Toolbox,
y o u w ill s e e m a n y o th e r s e c tio n s . E a c h s e c tio n c a n b e o p e n e d o r c lo s e d .
I f y o u w a n t t o o p e n a s e c t i o n o f t h e Toolbox, y o u s i m p l y c l i c k o n i t s n a m e t a b . T o c l o s e
t h e s e c t i o n , c l i c k o n i t s n a m e t a b a g a i n . I n F i g u r e 1 - 4 1 , t h e Common Controls s e c t i o n i s
o p e n . Y o u u s e t h e Common Controls s e c t i o n t o a c c e s s c o n t r o l s t h a t y o u f r e q u e n t l y n e e d ,
s u c h a s B u tto n s , L a b e ls , a n d T e x tB o x e s . Y o u c a n m o v e a n y s e c tio n to th e to p o f th e lis t
b y d r a g g in g its n a m e w ith th e m o u s e .
U s in g T o o lT ip s
A T o o lT ip is a s m a ll r e c ta n g u la r b o x th a t p o p s u p w h e n y o u h o v e r th e m o u s e p o in te r
o v e r a b u t t o n o n t h e t o o l b a r o r i n t h e Toolbox f o r a f e w s e c o n d s . T h e T o o l T i p b o x
1 .8
G e t t in g S t a r t e d w it h t h e V is u a l S t u d io E n v ir o n m e n t
c o n ta in s a s h o r t d e s c r ip tio n o f th e b u tto n ’s p u r p o s e . F ig u r e 1 -4 2 s h o w s th e T o o lT ip th a t
a p p e a r s w h e n t h e c u r s o r i s l e f t s i t t i n g o n t h e Save All b u t t o n . U s e a T o o l T i p w h e n e v e r y o u
c a n n o t r e m e m b e r a p a r tic u la r b u tto n ’s fu n c tio n .
F ig u r e 1 -4 2
Sa ve All T o o l T i p
D o c k e d a n d F lo a t in g W in d o w s
F i g u r e 1 - 4 1 s h o w s t h e Toolbox, Solution Explorer, a n d Properties w i n d o w s w h e n t h e y
a r e d o c k e d , w h ic h m e a n s th e y a r e a tta c h e d to o n e o f th e e d g e s o f th e V is u a l S tu d io w in d o w . A lte r n a tiv e ly , th e w in d o w s c a n b e flo a tin g . Y o u c a n c o n tr o l w h e th e r a w in d o w is
d o c k e d o r flo a tin g a s fo llo w s :
• T o c h a n g e a w in d o w fr o m d o c k e d to flo a tin g , r ig h t-c lic k
s e l e c t Float.
• T o c h a n g e a w in d o w fr o m flo a tin g to d o c k e d , r ig h t-c lic k
s e l e c t D ock.
its title b a r a n d
its title b a r a n d
F i g u r e 1 - 4 3 s h o w s V i s u a l S t u d i o w i t h t h e Toolbox, Solution Explorer, a n d Properties
w in d o w s flo a tin g . W h e n a w in d o w is flo a tin g , y o u c a n c lic k a n d d r a g it b y its title b a r
F ig u r e 1 -4 3
Toolbox, Solution Explorer, a n d Properties w i n d o w s f l o a t i n g
37
38
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
a r o u n d th e s c r e e n . Y o u m a y u s e w h ic h e v e r s ty le y o u p r e fe r — d o c k e d o r flo a tin g . W h e n
w in d o w s a r e flo a tin g , th e y b e h a v e a s n o r m a l w in d o w s . Y o u m a y m o v e o r r e s iz e th e m to
s u it y o u r p r e fe r e n c e .
N O T E :
A w in d o w c a n n o t flo a t if its A u to H id e fe a tu r e is tu r n e d o n .
T I P : R e m e m b e r , y o u c a n a l w a y s r e s e t t h e w i n d o w l a y o u t b y c l i c k i n g Window o n
t h e m e n u b a r a n d t h e n s e l e c t i n g Reset Window L ayout. I f y o u a c c i d e n t a l l y c l o s e t h e
D esigner w i n d o w , t h e Solution Explorer w i n d o w , o r t h e Properties w i n d o w , y o u c a n
u s e t h e View m e n u t o r e d i s p l a y t h e m .
P r o je c t s a n d S o lu t io n s
A s y o u l e a r n t o p r o g r a m i n V i s u a l C # , y o u w i l l s e e t h e t e r m s project a n d solution u s e d
o fte n . T h e s e te r m s d o n o t m e a n th e s a m e th in g , b u t th e y a r e s o m e tim e s u s e d in te r c h a n g e a b ly . L e t’s b r ie fly d is c u s s th e d iffe r e n c e b e tw e e n a p r o je c t a n d a s o lu tio n .
E a c h V is u a l C # a p p lic a tio n th a t y o u c r e a te is c a lle d a p r o je c t. A V is u a l C # p r o je c t
c o n s is ts o f s e v e r a l file s . Y o u c a n th in k o f a p r o je c t a s a c o lle c tio n o f file s th a t b e lo n g to a
s in g le a p p lic a tio n .
A s o lu tio n is a c o n ta in e r th a t h o ld s o n e o r m o r e V is u a l C # p r o je c ts . If y o u a r e d e v e lo p in g
a p p lic a tio n s fo r a la r g e o r g a n iz a tio n , y o u m ig h t fin d it c o n v e n ie n t to s to r e s e v e r a l r e la te d
p r o je c ts to g e th e r in th e s a m e s o lu tio n .
A lth o u g h it is p o s s ib le fo r a s o lu tio n to h o ld m o r e th a n o n e p r o je c t, e a c h p r o je c t th a t y o u
w ill c r e a te in th is b o o k w ill b e s a v e d in its o w n s o lu tio n . E a c h tim e y o u c r e a te a n e w p r o je c t, y o u w ill a ls o c r e a te a n e w s o lu tio n to h o ld it. F ig u r e 1 -4 4 illu s tr a te s th is c o n c e p t.
T y p ic a lly , th e s o lu tio n w ill b e g iv e n th e s a m e n a m e a s th e p r o je c t.
F ig u r e 1 -4 4
S o lu t io n a n d p r o je c t o r g a n iz a t io n
Solution
Project
Files Belonging
to the Project
T y p ic a l O r g a n iz a t io n o f S o lu t io n s
a n d P r o je c t s o n t h e D is k
W h e n y o u c r e a te a n e w p r o je c t, y o u s p e c ify th e p r o je c t’s n a m e , th e s o lu tio n ’s n a m e , a n d
a lo c a tio n o n th e d is k w h e r e th e s o lu tio n s h o u ld b e s to r e d . Y o u s p e c ify th is in fo r m a tio n
a t t h e b o t t o m o f t h e N ew Project w i n d o w , a s s h o w n i n F i g u r e 1 - 4 5 .
1 .8
F ig u r e 1 -4 5
G e t t in g S t a r t e d w it h t h e V is u a l S t u d io E n v ir o n m e n t
S p e c ify in g t h e p r o je c t n a m e , s o lu t io n n a m e , a n d lo c a t io n
Project name
Solution name
This is where the solution folder will be created
L e t ’ s u s e F i g u r e 1 - 4 5 t o s e e a n e x a m p l e o f h o w t h e f i l e s f o r t h e M y First Project s o l u t i o n
a n d p r o je c t w ill b e o r g a n iz e d o n th e d is k . N o tic e th a t in F ig u r e 1 -4 5 , th e fo llo w in g lo c a tio n is s h o w n fo r th e s o lu tio n :
C:\Users\Tony\D ocuments\Visual Studio 2015\Projects\
O n y o u r s y s te m , th e lo c a tio n w ill n o t b e e x a c tly th e s a m e a s th is , b u t it w ill b e s o m e t h i n g s i m i l a r . A t t h i s l o c a t i o n , a s o l u t i o n f o l d e r n a m e d M y First Project w i l l b e c r e a t e d .
If w e u s e W in d o w s to lo o k in s id e th a t fo ld e r , w e w ill s e e th e tw o ite m s s h o w n in F ig u r e
1 - 4 6 . N o t i c e t h a t o n e o f t h e i t e m s i s a n o t h e r f o l d e r n a m e d M y First Project. T h a t i s t h e
p r o je c t fo ld e r , w h ic h c o n ta in s v a r io u s file s r e la te d to th e p r o je c t. T h e o th e r ite m is th e
s o lu tio n file . In W in d o w s , y o u c a n d o u b le -c lic k th e s o lu tio n file to o p e n th e p r o je c t in
V is u a l S tu d io .
F ig u r e 1 -4 6
C o n t e n t s o f t h e My First Project s o l u t i o n f o l d e r
Project folder
Solution file
O p e n in g a n E x is t in g P r o je c t
If V is u a l S tu d io is a lr e a d y r u n n in g , y o u c a n p e r fo r m th e fo llo w in g s te p s to o p e n a n e x is tin g p r o je c t:
• C l i c k File o n t h e V i s u a l S t u d i o m e n u b a r , t h e n s e l e c t O pen, a n d t h e n s e l e c t
Project/ Solution. . . .
• T h e O pen Project w i n d o w w i l l a p p e a r . N a v i g a t e t o t h e d e s i r e d s o l u t i o n f o l d e r ,
s e l e c t t h e s o l u t i o n f i l e , a n d c l i c k O pen.
39
40
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
T u t o r ia l 1 -4 :
O p e n in g a n E x is t in g P r o je c t
I n t h i s t u t o r i a l y o u w i l l r e o p e n t h e My First Project a p p l i c a t i o n t h a t y o u c r e a t e d i n T u t o r i a l 1 - 2 .
VideoNot e
T u to r ia l 1 -4 :
O p e n in g a n
E x is tin g
P r o je c t
S t e p 1 :
V is u a l S tu d io s h o u ld s till b e r u n n in g fr o m th e p r e v io u s tu to r ia l.
C l i c k File o n t h e m e n u b a r ; s e l e c t O pen a n d t h e n s e l e c t Project/Solution. . . .
T h e O pen Project w i n d o w w i l l a p p e a r . N a v i g a t e t o t h e M y First Project s o l u t i o n , s e l e c t t h e s o l u t i o n f i l e , a n d c l i c k t h e O pen b u t t o n .
M y First Project s h o u l d b e o p e n e d . I f y o u p l a n t o c o m p l e t e t h e n e x t t u t o r i a l ,
l e a v e V i s u a l S t u d i o r u n n i n g w i t h M y First Project o p e n e d .
D i s p l a y i n g t h e Designer ( W h e n I t D o e s N o t
A u t o m a t ic a lly A p p e a r )
S o m e tim e s w h e n y o u o p e n a n e x is tin g p r o je c t, th e p r o je c t’s fo r m w ill n o t b e a u to m a tic a l l y d i s p l a y e d i n t h e D esigner. F i g u r e 1 - 4 7 s h o w s a n e x a m p l e o f t h e V i s u a l S t u d i o
e n v i r o n m e n t w i t h a n o p e n e d p r o j e c t b u t n o f o r m d i s p l a y e d i n t h e D esigner. W h e n t h i s
h a p p e n s , p e r f o r m t h e f o l l o w i n g s t e p s t o d i s p l a y t h e p r o j e c t ’ s f o r m i n t h e D esigner:
• A s s h o w n i n F i g u r e 1 - 4 8 , r i g h t - c l i c k F o r m 1 . c s i n t h e Solution Explorer.
• C l i c k View D esigner i n t h e p o p - u p m e n u .
F ig u r e 1 -4 7
A p r o j e c t o p e n e d w i t h n o f o r m d i s p l a y e d i n t h e Designer
1 .8
F ig u r e 1 -4 8
G e t t in g S t a r t e d w it h t h e V is u a l S t u d io E n v ir o n m e n t
U s i n g t h e Solution Explorer t o o p e n a f o r m i n t h e Designer
1
Right-click Form1.cs in
the Solution Explorer
2
Click View Designer
A c c e s s in g t h e V is u a l S t u d io D o c u m e n t a t io n
Y o u c a n a c c e s s t h e d o c u m e n t a t i o n f o r V i s u a l S t u d i o b y C l i c k i n g H elp o n t h e m e n u b a r ,
a n d t h e n s e l e c t i n g View H elp. ( O r , y o u c a n p r e s s
+ , an d th en p ress
o n th e k eyb o a r d . ) T h i s l a u n c h e s y o u r W e b b r o w s e r a n d o p e n s t h e o n l i n e M icrosoft D eveloper N etwork (M SD N ) L ibrary. T h e M S D N L i b r a r y p r o v i d e s c o m p l e t e d o c u m e n t a t i o n f o r V i s u a l
C # a s w e ll a s th e o th e r p r o g r a m m in g la n g u a g e s in c lu d e d in V is u a l S tu d io . Y o u w ill a ls o
fin d c o d e s a m p le s , tu to r ia ls , a r tic le s , a n d a c c e s s to tu to r ia l v id e o s .
T u t o r ia l 1 -5 :
G e t t in g F a m ilia r w it h t h e V is u a l S t u d io E n v ir o n m e n t
VideoNot e
T u to r ia l 1 -5 :
G e ttin g
F a m ilia r w ith
th e V is u a l
S tu d io
E n v ir o n m e n t
T h i s e x e r c i s e w i l l g i v e y o u p r a c t i c e i n t e r a c t i n g w i t h t h e Solution Explorer w i n d o w , t h e
Properties w i n d o w , a n d t h e Toolbox.
S t e p 1 :
If V is u a l S tu d io is s till r u n n in g o n y o u r c o m p u te r fr o m th e p r e v io u s tu to r ia l,
c o n tin u e to S te p 2 . If V is u a l S tu d io is n o t r u n n in g o n y o u r c o m p u te r , r e p e a t th e
s t e p s i n T u t o r i a l 1 - 4 t o o p e n M y First Project.
S t e p 2 :
P r a c t i c e t u r n i n g t h e A u t o H i d e f e a t u r e o n a n d o f f f o r t h e Solution Explorer
w i n d o w , t h e Properties w i n d o w , a n d t h e Toolbox. R e c a l l f r o m o u r p r e v i o u s
d is c u s s io n th a t c lic k in g th e p u s h p in ic o n in e a c h w in d o w ’s title b a r tu r n s A u to
H id e o n a n d o ff. W h e n y o u a r e fin is h e d p r a c tic in g , m a k e s u r e A u to H id e is
tu r n e d o ff fo r e a c h o f th e s e w in d o w s . Y o u r s c r e e n s h o u ld lo o k lik e F ig u r e 1 -4 1 .
S t e p 3 :
P r a c t i c e f l o a t i n g a n d d o c k i n g t h e Solution Explorer w i n d o w , t h e Properties
w i n d o w , a n d t h e Toolbox. R e c a l l f r o m o u r p r e v i o u s d i s c u s s i o n t h a t y o u c a n
41
K e y T e rm s
K e y T e r m s
a lg o r ith m
A m e r ic a n S ta n d a r d C o d e fo r
In fo r m a tio n In te r c h a n g e (A S C II)
a p p lic a tio n s o ftw a r e
a s s e m b le r
a s s e m b ly la n g u a g e
A u to H id e
b in a r y
b in a r y d ig it
b in a r y n u m b e r in g s y s te m
b it
Bu tto n
b yte
c e n tr a l p r o c e s s in g u n it (C P U )
c la s s
co d e
c o m m a n d lin e in te r fa c e
c o m p a c t d is c (C D )
c o m p ile r
c o n s o le in te r fa c e
c o n tr o ls
d eb u g
D esigner w i n d o w
d ig ita l
d ig ita l d a ta
d ig ita l d e v ic e
d ig ita l v e r s a tile d is c (D V D )
d is k d r iv e
d o c k e d (w in d o w )
E n d te r m in a l
ENIAC
e v e n t d r iv e n
e x e c u tin g
fe tc h -d e c o d e -e x e c u te c y c le
fie ld s
flo a tin g (w in d o w )
flo a tin g -p o in t n o ta tio n
flo w c h a r t
Fo rm
g r a p h ic a l u s e r in te r fa c e (G U I)
h ard ware
h ig h -le v e l la n g u a g e s
in p u t
in p u t d e v ic e
in p u t s y m b o ls
in s tr u c tio n s e t
in te g r a te d d e v e lo p m e n t
e n v ir o n m e n t (ID E )
in te r p r e te r
k eywo rd s
Lab el
lo g ic e r r o r
lo w -le v e l la n g u a g e
m a c h in e la n g u a g e
m a in m e m o r y
meth o d s
m ic r o p r o c e s s o r s
m n e m o n ic s
.N E T F r a m e w o r k
o b je c t o r ie n te d
o p e r a tin g s y s te m
o p erato rs
o u tp u t
o u tp u t d e v ic e
o u tp u t s y m b o ls
p ic tu r e e le m e n t
p ix e l
p r o c e s s in g s y m b o ls
p ro gram
p r o g r a m d e v e lo p m e n t c y c le
p ro grammer
p r o je c t
p r o je c t fo ld e r
p r o p e r tie s
Properties w i n d o w
p seu d o co d e
ran d o m access memo ry (RAM)
reserved wo rd s
r u n n in g
s a m p le s
seco n d ary sto rage
s e c u r e d ig ita l (S D ) m e m o r y c a r d
so ftware
s o ftw a r e d e v e lo p e r
s o ftw a r e d e v e lo p m e n t to o ls
s o lid -s ta te d r iv e
s o lu tio n
Solution Explorer w i n d o w
s o lu tio n file
s o lu tio n fo ld e r
so u rce co d e
s ta n d a r d to o lb a r
s ta r t te r m in a l
statemen ts
syn tax
syn tax erro r
system so ftware
te r m in a l s y m b o l
Tex tBo x
Toolbox
43
44
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
T o o lT ip
tw o ’s c o m p le m e n t
U n ic o d e
u n iv e r s a l s e r ia l b u s (U S B ) d r iv e s
u ser
u s e r in te r fa c e
u tility p r o g r a m
v o la tile
V is u a l S tu d io
V is u a l S tu d io 2 0 1 5
R e v ie w Q u e s t io n s
M u lt ip le C h o ic e
1 .
A (n ) _ _ _ _ _ _ _ _ _ _ is a s e t o f in s tr u c tio n s th a t a c o m p u te r fo llo w s to p e r fo r m a
task .
a.
b .
c.
d .
2 .
T h e p h y s ic a l d e v ic e s th a t a c o m p u te r is m a d e o f a r e r e fe r r e d to a s _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
3 .
b .
c.
d .
b .
c.
d .
b .
c.
d .
seco n d ary sto rage
th e CP U
m a in m e m o r y
th e m ic r o p r o c e s s o r
_ _ _ _ _ _ _ _ _ _ is a v o la tile ty p e o f m e m o r y th a t is u s e d o n ly fo r te m p o r a r y s to r a g e
w h ile a p r o g r a m is r u n n in g .
a.
b .
c.
d .
7 .
ENIACs
m ic r o p r o c e s s o r s
m e m o r y c h ip s
o p e r a tin g s y s te m s
T h e c o m p u te r s to r e s a p r o g r a m w h ile th e p r o g r a m is r u n n in g , a s w e ll a s th e d a ta
th a t th e p r o g r a m is w o r k in g w ith , in _ _ _ _ _ _ _ _ _ _ .
a.
6 .
RAM
seco n d ary sto rage
m a in m e m o r y
th e CP U
T o d a y , C P U s a r e s m a ll c h ip s k n o w n a s _ _ _ _ _ _ _ _ _ _ .
a.
5 .
h ard ware
so ftware
th e o p e r a tin g s y s te m
to o ls
T h e p a r t o f a c o m p u te r th a t r u n s p r o g r a m s is c a lle d _ _ _ _ _ _ _ _ _ _ .
a.
4 .
c o m p ile r
p ro gram
in te r p r e te r
p r o g r a m m in g la n g u a g e
RAM
seco n d ary sto rage
th e d is k d r iv e
th e U S B d r iv e
A ty p e o f m e m o r y th a t c a n h o ld d a ta fo r lo n g p e r io d s o f tim e — e v e n w h e n th e r e is
n o p o w e r to th e c o m p u te r — is c a lle d _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
RAM
m a in m e m o r y
seco n d ary sto rage
CP U sto rage
R e v ie w Q u e s t io n s
8 .
A c o m p o n e n t th a t c o lle c ts d a ta fr o m p e o p le o r o th e r d e v ic e s a n d s e n d s it to th e
c o m p u te r is c a lle d _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
9 .
A v id e o d is p la y is a (n ) _ _ _ _ _ _ _ _ _ _ d e v ic e .
a.
b .
c.
d .
1 0 .
a n o u tp u t d e v ic e
a n in p u t d e v ic e
a s e c o n d a r y s to r a g e d e v ic e
m a in m e m o r y
o u tp u t d e v ic e
in p u t d e v ic e
s e c o n d a r y s to r a g e d e v ic e
m a in m e m o r y
A _ _ _ _ _ _ _ _ _ _ is e n o u g h m e m o r y to s to r e a le tte r o f th e a lp h a b e t o r a s m a ll n u m b e r .
a.
b yte
b it
s w itc h
tr a n s is to r
b .
c.
d .
1 1 .
A b y te is m a d e u p o f e ig h t _ _ _ _ _ _ _ _ _ _ .
a.
CP Us
in s tr u c tio n s
v a r ia b le s
b its
b .
c.
d .
1 2 .
In th e _ _ _ _ _ _ _ _ _ _ n u m b e r in g s y s te m , a ll n u m e r ic v a lu e s a r e w r itte n a s s e q u e n c e s o f
0 s an d 1 s.
a.
h e x a d e c im a l
b in a r y
o ctal
d e c im a l
b .
c.
d .
1 3 .
1 4 .
A b it th a t is tu r n e d o ff r e p r e s e n ts th e fo llo w in g v a lu e : _ _ _ _ _ _ _ _ _ _ .
a.
1
b .
c.
− 1
d .
“ n o ”
A s e t o f 1 2 8 n u m e r ic c o d e s th a t r e p r e s e n t th e E n g lis h le tte r s , v a r io u s p u n c tu a tio n
m a r k s , a n d o th e r c h a r a c te r s is _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
1 5 .
b in a r y n u m b e r in g
ASCII
U n ic o d e
ENIAC
A n e x te n s iv e e n c o d in g s c h e m e th a t c a n r e p r e s e n t th e c h a r a c te r s o f m a n y o f th e la n g u a g e s in th e w o r ld is _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
1 6 .
0
b in a r y n u m b e r in g
ASCII
U n ic o d e
ENIAC
N e g a tiv e n u m b e r s a r e e n c o d e d u s in g th e _ _ _ _ _ _ _ _ _ _ te c h n iq u e .
a.
b .
c.
d .
tw o ’s c o m p le m e n t
flo a tin g p o in t
ASCII
U n ic o d e
45
46
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
1 7 .
R e a l n u m b e r s a r e e n c o d e d u s in g th e _ _ _ _ _ _ _ _ _ _ te c h n iq u e .
a.
b .
c.
d .
1 8 .
T h e tin y d o ts o f c o lo r th a t d ig ita l im a g e s a r e c o m p o s e d o f a r e c a lle d _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
1 9 .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b in a r y in s tr u c tio n s
m n e m o n ic s
co mman d s
k eywo rd s
T h e r u le s th a t m u s t b e fo llo w e d w h e n w r itin g a p r o g r a m a r e c a lle d _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
2 5 .
a s s e m b le r
c o m p ile r
tr a n s la to r
in te r p r e te r
T h e w o r d s th a t m a k e u p a h ig h -le v e l p r o g r a m m in g la n g u a g e a r e c a lle d _ _ _ _ _ _ _ _ _ _ .
a.
2 4 .
C#
a s s e m b ly la n g u a g e
m a c h in e la n g u a g e
Java
T h e _ _ _ _ _ _ _ _ _ _ tr a n s la te s a n a s s e m b ly la n g u a g e p r o g r a m to a m a c h in e la n g u a g e
p ro gram.
a.
2 3 .
fetch
d eco d e
ex ecu te
im m e d ia te ly a fte r th e in s tr u c tio n is e x e c u te d
C o m p u te r s c a n e x e c u te o n ly p r o g r a m s th a t a r e w r itte n in _ _ _ _ _ _ _ _ _ _ .
a.
2 2 .
C# co d e
a s tr e a m o f b in a r y n u m b e r s
E n g lis h w o r d s
c ir c u its
In th e _ _ _ _ _ _ _ _ _ _ p a r t o f th e fe tc h -d e c o d e -e x e c u te c y c le , th e C P U d e te r m in e s w h ic h
o p e r a tio n it s h o u ld p e r fo r m .
a.
2 1 .
b its
b ytes
c o lo r p a c k e ts
p ix e ls
If y o u w e r e to lo o k a t a m a c h in e la n g u a g e p r o g r a m , y o u w o u ld s e e _ _ _ _ _ _ _ _ _ _ .
a.
2 0 .
tw o ’s c o m p le m e n t
flo a tin g p o in t
ASCII
U n ic o d e
syn tax
p u n c tu a tio n
k eywo rd s
o p erato rs
A (n ) _ _ _ _ _ _ _ _ _ _ is a p r o g r a m th a t tr a n s la te s a h ig h -le v e l la n g u a g e p r o g r a m in to a
s e p a r a te m a c h in e la n g u a g e p r o g r a m .
a.
b .
c.
d .
a s s e m b le r
c o m p ile r
tr a n s la to r
u tility
R e v ie w Q u e s t io n s
2 6 .
A _ _ _ _ _ _ _ _ _ _ is a n y h y p o th e tic a l p e r s o n u s in g a p r o g r a m a n d p r o v id in g in p u t
fo r it.
a.
b .
c.
d .
2 7 .
A _ _ _ _ _ _ _ _ _ _ e r r o r d o e s n o t p r e v e n t th e p r o g r a m fr o m r u n n in g b u t c a u s e s it to
p r o d u c e in c o r r e c t r e s u lts .
a.
b .
c.
d .
2 8 .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
a p r o g r a m ’s g r a p h ic a l u s e r in te r fa c e a r e c o m m o n ly
b u tto n s
c o n tr o ls
fo rms
w in d o w s
A _ _ _ _ _ _ _ _ _ _ is c o d e th a t d e s c r ib e s a p a r tic u la r ty p e o f o b je c t.
a.
b .
c.
d .
3 3 .
flo w c h a r t
step ch art
co d e grap h
p ro gram grap h
O b je c ts th a t a r e v is ib le in
referred to as __________.
a.
3 2 .
fau x co d e
p seu d o co d e
C#
a flo w c h a r t
A _ _ _ _ _ _ _ _ _ _ is a d ia g r a m th a t g r a p h ic a lly d e p ic ts th e s te p s th a t ta k e p la c e in a
p ro gram.
a.
3 1 .
lo g a r ith m
p la n o f a c tio n
lo g ic s c h e d u le
a lg o r ith m
A n in fo r m a l la n g u a g e th a t h a s n o s y n ta x r u le s a n d is n o t m e a n t to b e c o m p ile d o r
e x e c u te d is c a lle d _ _ _ _ _ _ _ _ _ _ .
a.
3 0 .
syn tax
h ard ware
lo g ic
fatal
A (n ) _ _ _ _ _ _ _ _ _ _ is a s e t o f w e ll-d e fin e d lo g ic a l s te p s th a t m u s t b e ta k e n to p e r fo r m
a task .
a.
2 9 .
d e s ig n e r
u ser
g u in e a p ig
te s t s u b je c t
n amesp ace
b lu e p r in t
sch ema
c la s s
T h e _ _ _ _ _ _ _ _ _ _ is a c o lle c tio n o f c la s s e s a n d o th e r c o d e th a t c a n b e u s e d , a lo n g w ith
a p r o g r a m m in g la n g u a g e s u c h a s C # , to c r e a te p r o g r a m s fo r th e W in d o w s o p e r a tin g
system.
a.
b .
c.
d .
.N E T fr a m e w o r k
S ta n d a r d T e m p la te L ib r a r y
GUI framewo rk
M S D N L ib r a r y
47
48
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
3 4 .
T h e _ _ _ _ _ _ _ _ _ _ is th e p a r t o f a c o m p u te r w ith w h ic h th e u s e r in te r a c ts .
a.
b .
c.
d .
3 5 .
B e fo r e G U Is b e c a m e p o p u la r , th e _ _ _ _ _ _ _ _ _ _ in te r fa c e w a s th e m o s t c o m m o n ly
u sed .
a.
b .
c.
d .
3 6 .
c e n tr a l p r o c e s s in g u n it
u s e r in te r fa c e
co n tro l system
in te r a c tiv ity s y s te m
c o m m a n d lin e
r e m o te te r m in a l
sen so ry
e v e n t-d r iv e n
_ _ _ _ _ _ _ _ _ _ p r o g r a m s a r e u s u a lly e v e n t d r iv e n .
a.
b .
c.
d .
c o m m a n d lin e
tex t-b ased
GUI
p ro ced u ral
T r u e o r F a ls e
1 .
T o d a y , C P U s a r e h u g e d e v ic e s m a d e o f e le c tr ic a l a n d m e c h a n ic a l c o m p o n e n ts s u c h
a s v a c u u m tu b e s a n d s w itc h e s .
2 .
M a in m e m o r y is a ls o k n o w n a s R A M .
3 .
A n y p ie c e o f d a ta th a t is s to r e d
b in a r y n u m b e r .
4 .
Im a g e s , s u c h a s th e o n e s y o u m a k e w ith y o u r d ig ita l c a m e r a , c a n n o t b e s to r e d a s
b in a r y n u m b e r s .
5 .
M a c h in e la n g u a g e is th e o n ly la n g u a g e th a t a C P U u n d e r s ta n d s .
6 .
A s s e m b ly la n g u a g e is c o n s id e r e d a h ig h -le v e l la n g u a g e .
7 .
A n in te r p r e te r is a p r o g r a m th a t b o th tr a n s la te s a n d e x e c u te s th e in s tr u c tio n s in a
h ig h -le v e l la n g u a g e p r o g r a m .
8 .
A s y n ta x e r r o r d o e s n o t p r e v e n t a p r o g r a m fr o m b e in g c o m p ile d a n d e x e c u te d .
9 .
W in d o w s , L in u x , U N IX , a n d M a c O S a r e a ll e x a m p le s o f a p p lic a tio n s o ftw a r e .
1 0 .
W o r d p r o c e s s in g p r o g r a m s , s p r e a d s h e e t p r o g r a m s , e -m a il p r o g r a m s , W e b b r o w s e r s ,
a n d g a m e s a r e a ll e x a m p le s o f u tility p r o g r a m s .
1 1 .
P r o g r a m m e r s m u s t b e
p s e u d o c o d e p r o g r a m s .
1 2 .
C # p r o v id e s o n ly th e b a s ic k e y w o r d s a n d o p e r a to r s th a t y o u n e e d to c o n s tr u c t
a p ro gram.
in
a c o m p u te r ’s m e m o r y m u s t b e s to r e d
c a r e fu l n o t
to
m a k e
s y n ta x
e r r o r s
w h e n
as a
w r itin g
S h o r t A n s w e r
1 .
W h y is th e C P U th e m o s t im p o r ta n t c o m p o n e n t in a c o m p u te r ?
2 .
W h a t n u m b e r d o e s a b it th a t is tu r n e d o n r e p r e s e n t? W h a t n u m b e r d o e s a b it th a t is
tu rn ed o ff rep resen t?
3 .
W h a t w o u ld y o u c a ll a d e v ic e th a t w o r k s w ith b in a r y d a ta ?
4 .
W h a t a r e th e w o r d s th a t m a k e u p a h ig h -le v e l p r o g r a m m in g la n g u a g e c a lle d ?
P r o g r a m m in g P r o b le m s
5 .
W h a t a r e th e s h o r t w o r d s th a t a r e u s e d in a s s e m b ly la n g u a g e c a lle d ?
6 .
W h a t is th e d iffe r e n c e b e tw e e n a c o m p ile r a n d a n in te r p r e te r ?
7 .
W h a t ty p e o f s o ftw a r e c o n tr o ls th e in te r n a l o p e r a tio n s o f th e c o m p u te r ’s h a r d w a r e ?
8 .
W h a t is p s e u d o c o d e ? W h a t is a flo w c h a r t?
9 .
W h e n a p r o g r a m r u n s in a te x t-b a s e d e n v ir o n m e n t, s u c h a s a c o m m a n d lin e in te r fa c e , w h a t d e te r m in e s th e o r d e r in w h ic h th in g s h a p p e n ?
1 0 .
W h a t d o e s a c la s s s p e c ify a b o u t a n o b je c t?
1 1 .
C a n y o u u s e C # a lo n e to p e r fo r m a d v a n c e d o p e r a tio n s s u c h a s c r e a tin g G U Is , r e a d in g d a ta fr o m a file , o r w o r k in g w ith d a ta b a s e s ? W h y o r w h y n o t?
1 2 .
F ig u r e 1 -4 9 s h o w s th e V is u a l S tu d io ID E . W h a t a r e th e n a m e s o f th e fo u r a r e a s th a t
a r e in d ic a te d in th e fig u r e ?
1 3 .
W h a t i s t h e p u r p o s e o f t h e Toolbox i n t h e V i s u a l S t u d i o e n v i r o n m e n t ?
1 4 .
H o w c a n y o u a c c e s s th e d o c u m e n ta tio n fo r V is u a l S tu d io ? W h a t r e s o u r c e s a r e p r o v id e d b y th e M S D N L ib r a r y ?
1 5 .
W h a t s te p s m u s t y o u ta k e to o p e n a n e x is tin g p r o je c t?
1 6 .
H o w c a n y o u
t h e D esigner?
F ig u r e 1 -4 9
v ie w th e p r o je c t’s fo r m if it is n o t a u to m a tic a lly d is p la y e d
in
T h e V is u a l S t u d io ID E
2
3
1
4
P r o g r a m m in g P r o b le m s
1 .
U s e w h a t y o u ’v e le a r n e d a b o u t th e b in a r y n u m b e r in g s y s te m in th is c h a p te r to c o n v e r t th e fo llo w in g d e c im a l n u m b e r s to b in a r y :
1 1
6 5
1 0 0
2 5 5
49
50
C h a p te r 1
In t r o d u c t io n t o C o m p u t e r s a n d P r o g r a m m in g
2 .
U s e w h a t y o u ’v e le a r n e d a b o u t th e b in a r y n u m b e r in g s y s te m in th is c h a p te r to c o n v e r t th e fo llo w in g b in a r y n u m b e r s to d e c im a l:
1 1 0 1
1 0 0 0
1 0 1 0 1 1
3 .
L o o k a t th e A S C II c h a r t in A p p e n d ix C a n d d e te r m in e th e c o d e s fo r e a c h le tte r o f
y o u r fir s t n a m e .
4 .
S u p p o s e y o u r in s tr u c to r g iv e s th r e e e x a m s d u r in g th e s e m e s te r a n d y o u w a n t to
w r ite a p r o g r a m th a t c a lc u la te s y o u r a v e r a g e e x a m s c o r e . A n s w e r th e fo llo w in g :
a . W h a t ite m s o f in p u t m u s t th e u s e r e n te r ?
b . O n c e th e in p u t h a s b e e n e n te r e d , h o w w ill th e p r o g r a m d e te r m in e th e a v e r a g e ?
c . W h a t o u tp u t w ill th e p r o g r a m d is p la y ?
C H A P T E R
2
In t r o d u c t io n t o V is u a l C #
T O P I C S
2 .1
2 .1
G e t t in g S t a r t e d w it h F o r m s a n d
C o n tr o ls
2 .6
M a k in g S e n s e o f In t e lliS e n s e
2 .7
P ic t u r e B o x C o n t r o ls
2 .2
C r e a t in g t h e G U I fo r Y o u r F ir s t V is u a l
C # A p p l i c a t i o n : T h e Hello World
A p p lic a t io n
2 .8
C o m m e n t s , B la n k L in e s , a n d
In d e n t a t io n
2 .3
In t r o d u c t io n t o C # C o d e
2 .9
W r it in g t h e C o d e t o C lo s e a n
A p p lic a t io n ’ s F o r m
2 .4
W r i t i n g C o d e f o r t h e Hello World
A p p lic a t io n
2 .1 0
D e a lin g w it h S y n t a x E r r o r s
2 .5
L a b e l C o n tr o ls
G e t t in g S t a r t e d w it h F o r m s a n d C o n t r o ls
C O N C E P T :
T h e f i r s t s t e p i n c r e a t i n g a V i s u a l C # a p p l i c a t i o n i s c r e a t i n g t h e a p p l i c a t i o n ’s
G U I . Y o u u s e t h e V i s u a l S t u d i o Designer, Toolbox, a n d Properties w i n d o w
t o b u i l d t h e a p p l i c a t i o n ’s f o r m w i t h t h e d e s i r e d c o n t r o l s a n d s e t e a c h
c o n t r o l ’s p r o p e r t i e s .
In th is c h a p te r , y o u w ill c r e a te y o u r fir s t V is u a l C # a p p lic a tio n . B e fo r e y o u s ta r t, h o w e v e r , y o u n e e d to le a r n s o m e fu n d a m e n ta l c o n c e p ts a b o u t c r e a tin g a G U I in V is u a l S tu d io .
T h is s e c tio n s h o w s th e b a s ic s o f e d itin g fo r m s a n d c r e a tin g c o n tr o ls .
T h e A p p lic a t io n ’s F o r m
W h e n y o u s ta r t a n e w V is u a l C # p r o je c t, V is u a l S tu d io a u to m a tic a lly c r e a te s a n e m p ty
f o r m a n d d i s p l a y s i t i n t h e D esigner. F i g u r e 2 - 1 s h o w s a n e x a m p l e . T h i n k o f t h e e m p t y
fo r m a s a b la n k c a n v a s th a t c a n b e u s e d to c r e a te th e a p p lic a tio n ’s u s e r in te r fa c e . Y o u c a n
a d d c o n tr o ls to th e fo r m , c h a n g e th e fo r m ’s s iz e , a n d m o d ify m a n y o f its c h a r a c te r is tic s .
W h e n th e a p p lic a tio n r u n s , th e fo r m w ill b e d is p la y e d o n th e s c r e e n .
51
52
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
F ig u r e 2 -1
A n e w p r o j e c t w i t h a b l a n k f o r m d i s p l a y e d i n t h e Designer
The project’s form
If y o u ta k e a c lo s e r lo o k a t th e fo r m , y o u w ill n o tic e th a t it is e n c lo s e d b y a th in d o tte d
lin e , k n o w n a s a b o u n d in g b o x . A s s h o w n in F ig u r e 2 -2 , th e b o u n d in g b o x h a s s m a ll s iz in g h a n d le s , w h ic h a p p e a r o n th e fo r m ’s r ig h t e d g e , b o tto m e d g e , a n d lo w e r -r ig h t c o r n e r .
W h e n a b o u n d i n g b o x a p p e a r s a r o u n d a n o b j e c t i n t h e D esigner, i t i n d i c a t e s t h a t t h e
o b je c t is s e le c te d a n d is r e a d y fo r e d itin g .
F ig u r e 2 -2
T h e fo r m ’ s b o u n d in g b o x a n d s iz in g h a n d le s
Thin dotted line (bounding box)
Sizing handle
Sizing handle
Sizing handle
In itia lly th e fo r m ’s s iz e is 3 0 0 p ix e ls w id e b y 3 0 0 p ix e ls h ig h . Y o u c a n e a s ily r e s iz e th e
fo r m w ith th e m o u s e . W h e n y o u p o s itio n th e m o u s e c u r s o r o v e r a n y e d g e o r c o r n e r th a t
h a s a s iz in g h a n d le , th e c u r s o r c h a n g e s to a tw o -h e a d e d a r r o w (
). F ig u r e 2 -3 s h o w s
e x a m p le s . W h e n th e m o u s e c u r s o r b e c o m e s a tw o -h e a d e d a r r o w , y o u c a n c lic k a n d d r a g
th e m o u s e to r e s iz e fo r m .
2 .1
F ig u r e 2 -3
G e t t in g S t a r t e d w it h F o r m s a n d C o n t r o ls
U s in g t h e m o u s e t o r e s iz e t h e fo r m
Id e n t ify in g F o r m s a n d C o n t r o ls b y T h e ir N a m e s
A n a p p lic a tio n ’s G U I is m a d e o f fo r m s a n d v a r io u s c o n tr o ls . E a c h fo r m a n d c o n tr o l in a n
a p p lic a tio n ’s G U I m u s t h a v e a n a m e th a t id e n tifie s it. T h e b la n k fo r m th a t V is u a l S tu d io
in itia lly c r e a te s in a n e w p r o je c t is n a m e d F o r m 1 .
N O T E : L a te r in th is b o o k , y o u w ill le a r n h o w to c h a n g e a fo r m ’s n a m e , b u t fo r
n o w , y o u w ill k e e p th e d e fa u lt n a m e , F o r m 1 .
T h e Pr oper ties W i n d o w
T h e a p p e a r a n c e a n d o th e r c h a r a c te r is tic s o f a G U I o b je c t a r e d e te r m in e d b y th e o b je c t’s
p r o p e r t i e s . W h e n y o u s e l e c t a n o b j e c t i n t h e D esigner, t h a t o b j e c t ’ s p r o p e r t i e s a r e d i s p l a y e d i n t h e Properties w i n d o w . F o r e x a m p l e , w h e n t h e F o r m 1 f o r m i s s e l e c t e d , i t s
p r o p e r t i e s a r e d i s p l a y e d i n t h e Properties w i n d o w , a s s h o w n i n F i g u r e 2 - 4 .
T I P : R e c a l l f r o m C h a p t e r 1 t h a t i f t h e Properties w i n d o w i s i n A u t o H i d e m o d e ,
y o u c a n c l i c k i t s t a b t o o p e n i t . I f y o u d o n o t s e e t h e Properties w i n d o w , c l i c k View o n
t h e m e n u b a r . O n t h e View m e n u , c l i c k Properties Window.
T h e a r e a a t t h e t o p o f t h e Properties w i n d o w s h o w s t h e n a m e o f t h e o b j e c t t h a t i s c u r r e n t l y s e l e c t e d . Y o u c a n s e e i n F i g u r e 2 - 4 t h a t t h e n a m e o f t h e s e l e c t e d o b j e c t i s Form1.
B e lo w th a t is a s c r o lla b le lis t o f p r o p e r tie s . T h e lis t o f p r o p e r tie s h a s tw o c o lu m n s : th e
le ft c o lu m n s h o w s e a c h p r o p e r ty ’s n a m e , a n d th e r ig h t c o lu m n s h o w s e a c h p r o p e r ty ’s
v a l u e . F o r e x a m p l e , l o o k a t t h e f o r m ’ s S i z e p r o p e r t y i n F i g u r e 2 - 4 . I t s v a l u e i s 300, 300.
T h is m e a n s th a t th e fo r m ’s s iz e is 3 0 0 p ix e ls w id e b y 3 0 0 p ix e ls h ig h . N e x t, lo o k a t th e
fo r m ’s T e x t p r o p e r ty . T h e T e x t p r o p e r ty d e te r m in e s th e te x t th a t is d is p la y e d in th e fo r m ’s
title b a r (th e b a r th a t a p p e a r s a t th e to p o f th e fo r m ). Its c u r r e n t v a lu e is F o r m 1 , s o th e
t e x t Form1 i s d i s p l a y e d i n t h e f o r m ’ s t i t l e b a r .
W h e n a fo r m is c r e a te d , its T e x t p r o p e r ty is in itia lly s e t to th e s a m e v a lu e a s th e fo r m ’s
n a m e . W h e n y o u s t a r t a n e w p r o j e c t , t h e b l a n k f o r m t h a t a p p e a r s i n t h e D esigner w i l l
a l w a y s b e n a m e d F o r m 1 , s o t h e t e x t Form1 w i l l a l w a y s a p p e a r i n t h e f o r m ’ s t i t l e b a r . I n
m o s t c a s e s , y o u w a n t to c h a n g e th e v a lu e o f th e fo r m ’s T e x t p r o p e r ty to s o m e th in g m o r e
m e a n in g fu l. F o r e x a m p le , a s s u m e th e F o r m 1 fo r m is c u r r e n tly s e le c te d . Y o u c a n p e r fo r m
t h e f o l l o w i n g s t e p s t o c h a n g e i t s T e x t p r o p e r t y t o M y First Program.
53
54
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
F ig u r e 2 -4
Step 1 :
Step 2 :
Step 3 :
T h e Properties w i n d o w , s h o w i n g t h e s e l e c t e d o b j e c t ’ s p r o p e r t i e s
I n t h e Properties w i n d o w , l o c a t e t h e T e x t p r o p e r t y .
D o u b l e - c l i c k t h e w o r d Form1 t h a t c u r r e n t l y a p p e a r s a s t h e T e x t p r o p e r t y ’ s
v a lu e , a n d th e n u s e th e
k e y to d e le te it.
T y p e M y First Program i n i t s p l a c e a n d p r e s s t h e
k e y . T h e t e x t M y First
Program w i l l n o w a p p e a r i n t h e f o r m ’ s t i t l e b a r , a s s h o w n i n F i g u r e 2 - 5 .
N O T E : C h a n g in g a n o b je c t’s T e x t p r o p e r ty d o e s n o t c h a n g e th e o b je c t’s n a m e . F o r
e x a m p l e , i f y o u c h a n g e t h e F o r m 1 f o r m ’ s T e x t p r o p e r t y t o M y First Program, t h e
fo r m ’s n a m e is s till F o r m 1 . Y o u h a v e c h a n g e d o n ly th e te x t th a t is d is p la y e d in th e
fo r m ’s title b a r .
F ig u r e 2 -5
T h e fo r m ’ s T e x t p r o p e r t y v a lu e d is p la y e d in t h e fo r m ’ s t it le b a r
2 .1
G e t t in g S t a r t e d w it h F o r m s a n d C o n t r o ls
E a r l i e r , w e d i s c u s s e d h o w t o u s e t h e m o u s e t o r e s i z e a f o r m i n t h e D esigner. A n a l t e r n a t i v e m e t h o d i s t o c h a n g e t h e f o r m ’ s S i z e p r o p e r t y i n t h e Properties w i n d o w . F o r e x a m p l e ,
a s s u m e th e F o r m 1 fo r m is c u r r e n tly s e le c te d . Y o u c a n p e r fo r m th e fo llo w in g s te p s to
c h a n g e its s iz e to 4 0 0 p ix e ls w id e b y 1 0 0 p ix e ls h ig h .
Step 1 :
Step 2 :
Step 3 :
F ig u r e 2 -6
I n t h e Properties w i n d o w , l o c a t e t h e S i z e p r o p e r t y .
C l i c k i n s i d e t h e a r e a t h a t h o l d s t h e S i z e p r o p e r t y ’s v a l u e , a n d t h e n d e l e t e t h e
c u r r e n t v a lu e .
T y p e 400, 100 i n i t s p l a c e a n d p r e s s t h e
k e y . T h e fo r m w ill b e r e s iz e d a s
s h o w n in F ig u r e 2 -6 .
T h e fo r m ’ s s iz e c h a n g e d t o 4 0 0 b y 1 0 0
N O T E : N o tic e in F ig u r e 2 -6 th a t th e A lp h a b e tic a l b u tto n (
) is s e le c te d n e a r th e
t o p o f t h e Properties w i n d o w . T h i s c a u s e s t h e p r o p e r t i e s t o b e d i s p l a y e d i n a l p h a b e t i c a l o r d e r . A lte r n a tiv e ly , th e C a te g o r iz e d b u tto n (
) c a n b e s e le c te d , w h ic h c a u s e s th e
p r o p e r tie s to b e d is p la y e d in g r o u p s . T h e a lp h a b e tic a l lis tin g is th e d e fa u lt s e le c tio n ,
a n d m o s t o f th e tim e , it m a k e s it e a s ie r to lo c a te s p e c ific p r o p e r tie s .
A d d in g C o n t r o ls t o a F o r m
W h e n y o u a r e r e a d y t o c r e a t e c o n t r o l s o n t h e a p p l i c a t i o n ’ s f o r m , y o u u s e t h e Toolbox.
R e c a l l f r o m C h a p t e r 1 t h a t t h e Toolbox u s u a l l y a p p e a r s o n t h e l e f t s i d e o f t h e V i s u a l S t u d i o e n v i r o n m e n t . I f t h e Toolbox i s i n A u t o H i d e m o d e , y o u c a n c l i c k i t s t a b t o o p e n i t .
F i g u r e 2 - 7 s h o w s a n e x a m p l e o f h o w t h e Toolbox t y p i c a l l y a p p e a r s w h e n i t i s o p e n .
T I P : R e c a l l f r o m C h a p t e r 1 t h a t i f y o u d o n o t s e e t h e Toolbox o r i t s t a b , c l i c k View
o n t h e m e n u b a r a n d t h e n c l i c k Toolbox.
T h e Toolbox s h o w s a s c r o l l a b l e l i s t o f c o n t r o l s t h a t y o u c a n a d d t o a f o r m . T o a d d a c o n t r o l t o a f o r m , y o u s i m p l y f i n d i t i n t h e Toolbox a n d t h e n d o u b l e - c l i c k i t . T h e c o n t r o l w i l l
b e c r e a te d o n th e fo r m . F o r e x a m p le , s u p p o s e y o u w a n t to c r e a te a B u tto n c o n tr o l o n th e
f o r m . Y o u f i n d i t i n t h e Toolbox, a s s h o w n i n F i g u r e 2 - 8 , d o u b l e - c l i c k i t , a n d a B u t t o n
c o n tr o l w ill a p p e a r o n th e fo r m .
55
56
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
F ig u r e 2 -7
T h e Toolbox
F ig u r e 2 -8
C r e a t in g a B u t t o n c o n t r o l
Double-click the
Button tool...
And a Button control will
be created on the form.
T I P :
Y o u c a n a l s o c l i c k a n d d r a g c o n t r o l s f r o m t h e Toolbox o n t o t h e f o r m .
R e s iz in g a n d M o v in g C o n t r o ls
T a k e a c lo s e r lo o k a t th e B u tto n c o n tr o l th a t is s h o w n o n th e fo r m in F ig u r e 2 -8 . N o tic e
th a t it is e n c lo s e d in a b o u n d in g b o x w ith s iz in g h a n d le s . T h is in d ic a te s th a t th e c o n tr o l is
c u r r e n tly s e le c te d . W h e n a c o n tr o l is s e le c te d , y o u c a n u s e th e m o u s e to r e s iz e it in th e
s a m e w a y th a t y o u le a r n e d to r e s iz e a fo r m e a r lie r . Y o u c a n a ls o u s e th e m o u s e to m o v e a
2 .1
G e t t in g S t a r t e d w it h F o r m s a n d C o n t r o ls
c o n tr o l to a n e w lo c a tio n o n th e fo r m . P o s itio n th e m o u s e c u r s o r in s id e th e c o n tr o l, a n d
wh en th e mo u se cu rso r b eco mes a fo u r-h ead ed arro w (
), y o u c a n c lic k a n d d r a g th e
c o n tr o l to a n e w lo c a tio n . F ig u r e 2 -9 s h o w s a fo r m w ith a B u tto n c o n tr o l th a t h a s b e e n
e n la r g e d a n d m o v e d .
F ig u r e 2 -9
A B u t t o n c o n t r o l r e s iz e d a n d m o v e d
D e le t in g a C o n t r o l
D e le tin g a c o n tr o l is s im p le : y o u s e le c t it a n d th e n p r e s s th e
k ey o n th e k eyb o ard .
M o r e a b o u t B u t t o n C o n t r o ls
Y o u le a r n e d e a r lie r th a t e a c h fo r m a n d e a c h c o n tr o l in a n a p p lic a tio n ’s G U I m u s t h a v e a
n a m e th a t id e n tifie s it. W h e n y o u c r e a te B u tto n c o n tr o ls , th e y a r e a u to m a tic a lly g iv e n
d e f a u l t n a m e s s u c h a s button1, button2, a n d s o f o r t h .
B u tto n c o n tr o ls h a v e a T e x t p r o p e r ty , w h ic h h o ld s th e te x t th a t is d is p la y e d o n th e fa c e o f
th e b u tto n . W h e n a B u tto n c o n tr o l is c r e a te d , its T e x t p r o p e r ty is in itia lly s e t to th e s a m e
v a lu e a s th e B u tto n c o n tr o l’s n a m e . A s a r e s u lt, w h e n y o u c r e a te a B u tto n c o n tr o l, its
n a m e w ill b e d is p la y e d o n th e fa c e o f th e b u tto n . F o r e x a m p le , th e fo r m in F ig u r e 2 -1 0
c o n t a i n s t h r e e B u t t o n c o n t r o l s n a m e d button1, button2, a n d button3.
F ig u r e 2 -1 0
A fo r m w it h t h r e e B u t t o n c o n t r o ls
57
58
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
A fte r y o u c r e a te a B u tto n c o n tr o l, y o u s h o u ld a lw a y s c h a n g e its T e x t p r o p e r ty . T h e te x t
th a t is d is p la y e d o n a b u tto n s h o u ld in d ic a te w h a t th e b u tto n w ill d o w h e n it is c lic k e d .
F o r e x a m p l e , a b u t t o n t h a t c a l c u l a t e s a n a v e r a g e m i g h t h a v e t h e t e x t Calculate Average
d i s p l a y e d o n i t , a n d a b u t t o n t h a t p r i n t s a r e p o r t m i g h t h a v e t h e t e x t Print Report d i s p la y e d o n it. H e r e a r e th e s te p s y o u p e r fo r m to c h a n g e a B u tto n c o n tr o l’s T e x t p r o p e r ty :
Step 1 :
Step 2 :
Step 3 :
M a k e s u r e t h e B u t t o n c o n t r o l is s e le c t e d . ( I f y o u d o n ’t s e e t h e b o u n d in g b o x
a n d s iz in g h a n d le s a r o u n d th e c o n tr o l, ju s t c lic k th e c o n tr o l to s e le c t it.)
I n t h e Properties w i n d o w , l o c a t e t h e T e x t p r o p e r t y .
C l i c k i n s i d e t h e a r e a t h a t h o l d s t h e T e x t p r o p e r t y ’s v a l u e , a n d t h e n d e l e t e t h e
c u r r e n t v a lu e . T h e n , ty p e th e n e w te x t in its p la c e a n d p r e s s th e
k ey. Th e
n e w te x t w ill b e d is p la y e d o n th e b u tto n .
F ig u r e 2 -1 1 s h o w s a n e x a m p le o f h o w c h a n g in g a B u tto n c o n tr o l’s T e x t p r o p e r ty c h a n g e s
th e te x t d is p la y e d o n th e fa c e o f th e b u tto n .
F ig u r e 2 -1 1
A B u tto n c o n tr o l’s T e x t p r o p e r ty c h a n g e d
C h a n g in g a C o n t r o l’s N a m e
A c o n tr o l’s n a m e id e n tifie s th e c o n tr o l in th e a p p lic a tio n ’s c o d e a n d in th e V is u a l S tu d io
e n v ir o n m e n t. W h e n y o u c r e a te a c o n tr o l o n a n a p p lic a tio n ’s fo r m , y o u s h o u ld a lw a y s
c h a n g e th e c o n tr o l’s n a m e to s o m e th in g th a t is m o r e m e a n in g fu l th a n th e d e fa u lt n a m e
th a t V is u a l S tu d io g iv e s it. A c o n tr o l’s n a m e s h o u ld r e fle c t th e p u r p o s e o f th e c o n tr o l.
F o r e x a m p le , s u p p o s e y o u ’v e c r e a te d a B u tto n c o n tr o l to c a lc u la te a n a m o u n t o f ta x . A
d e f a u l t n a m e s u c h a s button1 d o e s n o t c o n v e y t h e b u t t o n ’ s p u r p o s e . A n a m e s u c h a s
calculateTaxButton w o u l d b e m u c h b e t t e r . W h e n y o u a r e w o r k i n g w i t h t h e a p p l i c a t i o n ’ s c o d e a n d y o u s e e t h e n a m e calculateTaxButton, y o u w i l l k n o w p r e c i s e l y w h i c h
b u tto n th e c o d e is r e fe r r in g to .
Y o u c a n c h a n g e a c o n tr o l’s n a m e b y c h a n g in g its N a m e p r o p e r ty . H e r e a r e th e s te p s :
Step 1 :
Step 2 :
Step 3 :
M a k e s u r e th e c o n tr o l is s e le c te d . (If y o u d o n o t s e e th e b o u n d in g b o x a n d
s iz in g h a n d le s a r o u n d th e c o n tr o l, ju s t c lic k th e c o n tr o l to s e le c t it.)
I n t h e Properties w i n d o w , s c r o l l u p t o t h e t o p o f t h e l i s t o f p r o p e r t i e s . Y o u
s h o u ld s e e th e N a m e p r o p e r ty , a s s h o w n in F ig u r e 2 -1 2 . (T h e N a m e p r o p e r ty
is e n c lo s e d in p a r e n th e s e s to m a k e it a p p e a r n e a r th e to p o f th e a lp h a b e tic a l
l i s t o f p r o p e r t i e s . T h i s m a k e s i t e a s i e r t o fi n d . )
C l i c k i n s i d e t h e a r e a t h a t h o l d s t h e N a m e p r o p e r t y ’s v a l u e a n d t h e n d e l e t e t h e
c u r r e n t n a m e . T h e n , ty p e th e n e w n a m e in its p la c e a n d p r e s s th e
k ey. Yo u
h a v e s u c c e s s fu lly c h a n g e d th e n a m e o f th e c o n tr o l.
2 .1
F ig u r e 2 -1 2
G e t t in g S t a r t e d w it h F o r m s a n d C o n t r o ls
T h e N a m e p ro p e rty
F i g u r e 2 - 1 3 s h o w s t h e Properties w i n d o w a f t e r a B u t t o n c o n t r o l ’ s n a m e h a s b e e n c h a n g e d
t o calculateTaxButton.
F ig u r e 2 -1 3
T h e N a m e p r o p e r t y c h a n g e d t o calculateTaxButton
R u le s fo r N a m in g C o n t r o ls
C o n tr o l n a m e s a r e a ls o k n o w n a s id e n tifie r s . W h e n n a m in g a c o n tr o l, y o u m u s t fo llo w
th e s e r u le s fo r C # id e n tifie r s :
• T h e fir s t c h a r a c te r m u s t b e o n e o f th e le tte r s ath r o u g h zo r A th r o u g h Z o r a n
u n d e r s c o r e c h a r a c t e r ( _) .
• A f t e r t h e f i r s t c h a r a c t e r , y o u m a y u s e t h e l e t t e r s a t h r o u g h z o r A t h r o u g h Z, t h e
d ig its 0 th r o u g h 9 , o r u n d e r s c o r e s .
• T h e n a m e c a n n o t c o n ta in s p a c e s .
T a b le 2 -1 lis ts s o m e id e n tifie r s th a t m ig h t b e u s e d fo r B u tto n c o n tr o l n a m e s a n d in d ic a te s
w h e th e r e a c h is a le g a l o r ille g a l id e n tifie r in C # .
T a b le 2 -1
L e g a l a n d ille g a l id e n t ifie r s
Id e n tifie r
L e g a l o r Ille g a l?
showDayOfWeekButton
Legal
3rdQuarterButton
Ille g a l b e c a u s e id e n tifie r s c a n n o t b e g in w ith a d ig it.
change*color*Button
Ille g a l b e c a u s e th e * c h a r a c te r is n o t a llo w e d .
displayTotalButton
Legal
calculate Tax Button
Ille g a l b e c a u s e id e n tifie r s c a n n o t c o n ta in s p a c e s .
59
60
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
B e c a u s e a c o n tr o l’s n a m e s h o u ld r e fle c t th e c o n tr o l’s p u r p o s e , p r o g r a m m e r s o fte n fin d
th e m s e lv e s c r e a tin g n a m e s th a t a r e m a d e o f m u ltip le w o r d s . F o r e x a m p le , c o n s id e r th e
fo llo w in g B u tto n c o n tr o l n a m e s :
calculatetaxbutton
printreportbutton
displayanimationbutton
U n fo r tu n a te ly , th e s e n a m e s a r e n o t e a s ily r e a d b y th e h u m a n e y e b e c a u s e th e w o r d s a r e n o t
s e p a r a te d . B e c a u s e w e c a n n o t h a v e s p a c e s in c o n tr o l n a m e s , w e n e e d to fin d a n o th e r w a y to
s e p a r a te th e w o r d s in a m u ltiw o r d c o n tr o l n a m e to m a k e it m o r e r e a d a b le to th e h u m a n e y e .
M o s t C # p r o g r a m m e r s a d d r e s s th is p r o b le m b y u s in g th e c a m e lC a s e n a m in g c o n v e n tio n
fo r c o n tr o ls . c a m e lC a s e n a m e s a r e w r itte n in th e fo llo w in g m a n n e r :
• Y o u b e g in w r itin g th e n a m e w ith lo w e r c a s e le tte r s .
• T h e fir s t c h a r a c te r o f th e s e c o n d a n d s u b s e q u e n t w o r d s is w r itte n in u p p e r c a s e .
F o r e x a m p le , th e fo llo w in g c o n tr o l n a m e s a r e w r itte n in c a m e lC a s e :
calculateTaxButton
printReportButton
displayAnimationButton
N O T E : T h is s ty le o f n a m in g is c a lle d c a m e lC a s e b e c a u s e th e u p p e r c a s e c h a r a c te r s
th a t a p p e a r in a n a m e a r e s o m e tim e s r e m in is c e n t o f a c a m e l’s h u m p s .
C h e c k p o in t
2 .2
2 .1
W h e n y o u s ta r t a n e w V is u a l C # p r o je c t, w h a t is a u to m a tic a lly c r e a te d a n d d is p l a y e d i n t h e D esigner?
2 .2
H o w c a n y o u t e l l t h a t a n o b j e c t i s s e l e c t e d a n d r e a d y f o r e d i t i n g i n t h e D esigner?
2 .3
W h a t is th e p u r p o s e o f a n o b je c t’s s iz in g h a n d le s ?
2 .4
W h a t m u s t e a c h fo r m a n d c o n tr o l in a n a p p lic a tio n ’s G U I h a v e to id e n tify it?
2 .5
W h a t i s t h e p u r p o s e o f t h e Properties w i n d o w ?
2 .6
W h a t d o e s t h e A l p h a b e t i c a l b u t t o n d o w h e n i t i s s e l e c t e d i n t h e Properties w i n d o w ?
2 .7
W h a t d o e s t h e C a t e g o r i z e d b u t t o n d o w h e n i t i s s e l e c t e d i n t h e Properties w i n d o w ?
2 .8
W h a t d o e s a fo r m ’s T e x t p r o p e r ty d e te r m in e ?
2 .9
W h a t d o e s a fo r m ’s S iz e p r o p e r ty d e te r m in e ?
2 .1 0
W h a t i s s h o w n i n t h e Toolbox?
2 .1 1
Ho w d o yo u ad d a co n tro l to a fo rm?
2 .1 2
W h a t s h o u ld th e te x t th a t is d is p la y e d o n a b u tto n in d ic a te ?
2 .1 3
W h a t a r e th e r u le s fo r n a m in g c o n tr o ls ?
2 .1 4
W h a t n a m in g c o n v e n tio n d o m o s t C # p r o g r a m m e r s u s e to s e p a r a te w o r d s in a
m u ltiw o r d id e n tifie r ?
C r e a t in g t h e G U I fo r Y o u r F ir s t V is u a l C #
A p p l i c a t i o n : T h e Hello Wor ld A p p l i c a t i o n
W h e n a s tu d e n t is le a r n in g c o m p u te r p r o g r a m m in g , it is tr a d itio n a l to s ta r t b y le a r n in g to
w r i t e a H ello World p r o g r a m . A Hello World p r o g r a m i s a s i m p l e p r o g r a m t h a t m e r e l y
d i s p l a y s t h e w o r d s “ H ello World” o n t h e s c r e e n . I n t h i s c h a p t e r y o u w i l l c r e a t e y o u r f i r s t
2 .2
C r e a t i n g t h e G U I f o r Y o u r F i r s t V i s u a l C # A p p l i c a t i o n : T h e Hello World A p p l i c a t i o n
V i s u a l C # a p p l i c a t i o n , w h i c h w i l l b e a n e v e n t - d r i v e n H ello World p r o g r a m . W h e n t h e
fin is h e d a p p lic a tio n r u n s , it w ill d is p la y th e fo r m s h o w n o n th e le ft in F ig u r e 2 -1 4 . N o tic e
t h a t t h e f o r m c o n t a i n s a b u t t o n t h a t r e a d s D isplay M essage. W h e n y o u c l i c k t h e b u t t o n ,
th e w in d o w s h o w n o n th e r ig h t in th e fig u r e w ill a p p e a r .
F ig u r e 2 -1 4
S c r e e n s d i s p l a y e d b y t h e c o m p l e t e d Hello World p r o g r a m
When you click this button...
this window will appear.
T h e p r o c e s s o f c r e a tin g th is a p p lic a tio n is d iv id e d in to tw o p a r ts . F ir s t, y o u w ill c r e a te th e
a p p l i c a t i o n ’ s G U I , a n d s e c o n d , y o u w i l l w r i t e t h e c o d e t h a t c a u s e s t h e H ello World m e s s a g e t o a p p e a r w h e n t h e u s e r c l i c k s t h e D isplay M essage b u t t o n . T u t o r i a l 2 - 1 l e a d s y o u
th r o u g h th e p r o c e s s o f c r e a tin g th e G U I.
T u t o r ia l 2 -1 :
C r e a t i n g t h e G U I f o r t h e Hello World A p p l i c a t i o n
S t e p 1 :
S ta r t V is u a l S tu d io .
S t e p 2 :
S t a r t a n e w p r o j e c t b y c l i c k i n g File o n t h e m e n u b a r a n d t h e n s e l e c t i n g N ew
Project. . .
S t e p 3 :
T h e N ew Project w i n d o w s h o u l d a p p e a r . A t t h e l e f t s i d e o f t h e w i n d o w , u n d e r
I nstalled > Templates, m a k e s u r e Visual C# i s s e l e c t e d . T h e n , s e l e c t Windows
Forms Application a s t h e t y p e o f a p p l i c a t i o n . I n t h e N ame t e x t b o x ( a t t h e b o t t o m o f t h e w i n d o w ) , c h a n g e t h e n a m e o f t h e p r o j e c t t o H ello World, a n d t h e n
c l i c k t h e Ok b u t t o n .
S t e p 4 :
M a k e s u r e t h e Toolbox, t h e Solution Explorer, a n d t h e Properties w i n d o w a r e
v is ib le a n d th a t A u to H id e is tu r n e d o ff fo r e a c h o f th e s e w in d o w s . T h e V is u a l
S tu d io e n v ir o n m e n t s h o u ld a p p e a r a s s h o w n in F ig u r e 2 -1 5 .
S t e p 5 :
C h a n g e t h e F o r m 1 f o r m ’ s T e x t p r o p e r t y t o M y First Program, a s s h o w n i n
F ig u r e 2 -1 6 .
S t e p 6 :
T h e fo r m ’s d e fa u lt s iz e is to o la r g e fo r th is a p p lic a tio n , s o y o u n e e d to m a k e it
s m a lle r . U s e th e te c h n iq u e d is c u s s e d in th e p r e v io u s s e c tio n to a d ju s t th e fo r m ’s s iz e
w ith th e m o u s e . T h e fo r m s h o u ld a p p e a r s im ila r to th a t s h o w n in F ig u r e 2 -1 7 .
(D o n ’t w o r r y a b o u t th e fo r m ’s e x a c t s iz e . J u s t m a k e it a p p e a r s im ila r to F ig u r e 2 -1 7 .)
S t e p 7 :
No w yo u are read y to ad d a Bu tto n co n tro l to th e fo rm. Lo cate th e Bu tto n to o l
i n t h e Toolbox a n d d o u b l e - c l i c k i t . A B u t t o n c o n t r o l s h o u l d a p p e a r o n t h e f o r m ,
a s s h o w n in F ig u r e 2 -1 8 . M o v e th e B u tto n c o n tr o l s o it a p p e a r s a p p r o x im a te ly
in th e c e n te r o f th e fo r m , a s s h o w n in F ig u r e 2 -1 9 .
VideoNot e
T u to r ia l 2 -1 :
C r e a tin g th e
GUI fo r th e
H ello World
A p p lic a tio n
61
62
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
F ig u r e 2 -1 5
T h e V is u a l S t u d io e n v ir o n m e n t
F ig u r e 2 -1 6
T h e f o r m ’ s T e x t p r o p e r t y c h a n g e d t o My First Progra m
F ig u r e 2 -1 7
T h e fo r m r e s iz e d
2 .2
C r e a t i n g t h e G U I f o r Y o u r F i r s t V i s u a l C # A p p l i c a t i o n : T h e Hello World A p p l i c a t i o n
F ig u r e 2 -1 8
A B u tto n c o n tro l c re a te d o n th e fo rm
F ig u r e 2 -1 9
T h e B u tto n c o n tro l m o v e d
S t e p 8 :
C h a n g e t h e v a l u e o f t h e B u t t o n c o n t r o l ’ s T e x t p r o p e r t y t o Display Message. A f t e r
d o in g th is , n o tic e th a t th e te x t d is p la y e d o n th e b u tto n h a s c h a n g e d , a s s h o w n in
F ig u r e 2 -2 0 .
F ig u r e 2 -2 0
S t e p 9 :
T h e B u tto n c o n tr o l’s T e x t p r o p e r ty c h a n g e d
T h e B u tto n c o n tr o l is n ’t q u ite la r g e e n o u g h to a c c o m m o d a te a ll o f th e te x t th a t
y o u ty p e d in to its T e x t p r o p e r ty , s o e n la r g e th e B u tto n c o n tr o l, a s s h o w n in
F ig u r e 2 -2 1 .
F ig u r e 2 -2 1
T h e B u tto n c o n tr o l e n la r g e d
63
64
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
S t e p 1 0 : A s d is c u s s e d
in th e p r e v io u s s e c tio n , a c o n tr o l’s n a m e s h o u ld r e fle c t th e
p u r p o s e o f th e c o n tr o l. T h e B u tto n c o n tr o l th a t y o u c r e a te d in th is a p p lic a tio n
w i l l c a u s e a m e s s a g e t o b e d i s p l a y e d w h e n i t i s c l i c k e d . T h e n a m e button1
d o e s n o t c o n v e y th a t p u r p o s e , h o w e v e r . C h a n g e th e B u tto n c o n tr o l’s N a m e
p r o p e r t y t o messageButton. T h e Properties w i n d o w s h o u l d a p p e a r a s s h o w n
in F ig u r e 2 -2 2 .
F ig u r e 2 -2 2
S t e p 1 1 : C lic k
T h e B u t t o n c o n t r o l ’ s N a m e p r o p e r t y c h a n g e d t o messageButton
File o n
th e p r o je c t.
th e V is u a l S tu d io
m e n u
b a r a n d
th e n
c lic k
Save All t o
s a v e
S t e p 1 2 : Y o u ’r e o n ly p a r tia lly fin is h e d
w ith th e a p p lic a tio n , b u t y o u c a n r u n it n o w to
s e e h o w th e G U I lo o k s o n th e s c r e e n . T o r u n th e a p p lic a tio n , p r e s s th e
k ey o n
t h e k e y b o a r d o r c l i c k t h e Start D ebugging b u t t o n ( ) o n t h e t o o l b a r . T h i s
c a u s e s th e a p p lic a tio n to b e c o m p ile d a n d e x e c u te d . Y o u w ill n o tic e th e a p p e a r a n c e o f th e V is u a l S tu d io e n v ir o n m e n t c h a n g e s o m e w h a t, a n d y o u w ill s e e th e
a p p lic a tio n ’s fo r m a p p e a r o n th e s c r e e n a s s h o w n in F ig u r e 2 -2 3 .
F ig u r e 2 -2 3
T h e a p p lic a t io n r u n n in g
Click here to end
the application.
A lth o u g h th e a p p lic a tio n is r u n n in g , it is n o t c a p a b le o f d o in g a n y th in g o th e r th a n d is p l a y i n g t h e f o r m . I f y o u c l i c k t h e D isplay M essage b u t t o n , n o t h i n g w i l l h a p p e n . T h a t i s
b e c a u s e y o u h a v e n o t y e t w r itte n th e c o d e th a t e x e c u te s w h e n th e b u tto n is c lic k e d . Y o u
w ill d o th a t in th e n e x t tu to r ia l. T o e n d th e a p p lic a tio n , c lic k th e s ta n d a r d W in d o w s c lo s e
) in th e fo r m ’s u p p e r -r ig h t c o r n e r .
b u tto n (
2 .3
2 .3
In t r o d u c t io n t o C # C o d e
In t r o d u c t io n t o C # C o d e
C O N C E P T :
Y o u u s e t h e V i s u a l S t u d i o c o d e e d i t o r t o w r i t e a n a p p l i c a t i o n ’s c o d e . M u c h
o f th e c o d e th a t y o u w ill w r ite in a n a p p lic a tio n w ill b e e v e n t h a n d le r s .
E v e n t h a n d le r s r e s p o n d to s p e c ific e v e n ts th a t ta k e p la c e w h ile a n
a p p lic a tio n is r u n n in g .
In th e p r e v io u s s e c tio n s o f th is c h a p te r , y o u le a r n e d th e b a s ic s o f c r e a tin g a n a p p lic a tio n ’s G U I. A n a p p lic a tio n is m o r e th a n a u s e r in te r fa c e , h o w e v e r . If y o u w a n t y o u r
a p p lic a tio n to p e r fo r m a n y m e a n in g fu l a c tio n s , y o u h a v e to w r ite c o d e . T h is s e c tio n
in tr o d u c e s y o u to V is u a l C # c o d e a n d s h o w s h o w to p r o g r a m a n a p p lic a tio n to r e s p o n d
to b u tto n c lic k s .
A file th a t c o n ta in s p r o g r a m c o d e is c a lle d a s o u r c e c o d e file . W h e n y o u s ta r t a C # W in d o w s F o r m s A p p lic a tio n p r o je c t, V is u a l S tu d io a u to m a tic a lly c r e a te s s e v e r a l s o u r c e c o d e
f i l e s a n d a d d s t h e m t o t h e p r o j e c t . I f y o u l o o k a t t h e Solution Explorer, a s s h o w n i n
F ig u r e 2 -2 4 , y o u w ill s e e th e n a m e s o f tw o s o u r c e c o d e file s : F o r m 1 .c s a n d P r o g r a m .c s .
(C # s o u r c e c o d e file s a lw a y s e n d w ith th e .c s e x te n s io n .)
F ig u r e 2 -2 4
S o u r c e c o d e f i l e s s h o w n i n t h e Solution Explorer
Form1.cs contains code associatied with the Form1 form.
Program.cs contains the application’s startup code.
H e r e is a b r ie f d e s c r ip tio n o f th e tw o file s :
• T h e P r o g r a m .c s file c o n ta in s th e a p p lic a tio n ’s s ta r t-u p c o d e , w h ic h e x e c u te s w h e n
th e a p p lic a tio n r u n s . T h e c o d e in th is file p e r fo r m s b e h in d -th e -s c e n e s in itia liz a tio n
ta s k s th a t a r e n e c e s s a r y to g e t th e a p p lic a tio n u p a n d r u n n in g . It is im p o r ta n t th a t
y o u d o n o t m o d ify th e c o n te n ts o f th is file b e c a u s e d o in g s o c o u ld p r e v e n t th e a p p lic a tio n fr o m e x e c u tin g .
• T h e F o r m 1 .c s file c o n ta in s c o d e th a t is a s s o c ia te d w ith th e F o r m 1 fo r m . W h e n y o u
w r ite c o d e th a t d e fin e s s o m e a c tio n r e la te d to F o r m 1 (s u c h a s r e s p o n d in g to a b u tto n c lic k ), y o u w ill w r ite th e c o d e in th is file .
N O T E : Y o u m i g h t s e e a d d i t i o n a l s o u r c e c o d e f i l e s i n t h e Solution Explorer, o t h e r
th a n th o s e s h o w n in F ig u r e 2 -2 4 .
T h e F o r m 1 .c s file a lr e a d y c o n ta in s c o d e th a t w a s g e n e r a te d b y V is u a l S tu d io w h e n th e
p r o je c t w a s c r e a te d . Y o u c a n th in k o f th is a u to -g e n e r a te d c o d e a s a n o u tlin e to w h ic h y o u
c a n a d d y o u r o w n c o d e a s y o u d e v e lo p th e a p p lic a tio n .
65
66
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
L e t ’ s t a k e a l o o k a t t h e c o d e . I f y o u s t i l l h a v e t h e H ello World p r o j e c t o p e n f r o m t h e p r e v i o u s t u t o r i a l , r i g h t - c l i c k F o r m 1 . c s i n t h e Solution Explorer. A p o p - u p m e n u w i l l a p p e a r ,
a s s h o w n i n F i g u r e 2 - 2 5 . O n t h e p o p - u p m e n u , c l i c k View Code. T h e f i l e ’ s c o n t e n t s w i l l
b e d is p la y e d in th e V is u a l S tu d io c o d e e d ito r , a s s h o w n in F ig u r e 2 -2 6 .
F ig u r e 2 -2 5
F ig u r e 2 -2 6
O p e n in g F o r m 1 .c s in t h e c o d e e d it o r
1
Right-click Form1.cs in
the Solution Explorer
2
Click View Code
F o r m 1 .c s c o d e d is p la y e d in t h e V is u a l S t u d io c o d e e d it o r
2 .3
In t r o d u c t io n t o C # C o d e
A t th is p o in t, it’s n o t n e c e s s a r y fo r y o u to u n d e r s ta n d th e m e a n in g o f th e s ta te m e n ts th a t
y o u s e e in th is c o d e . It w ill b e h e lp fu l fo r y o u to k n o w h o w th is c o d e is o r g a n iz e d , h o w e v e r , b e c a u s e la te r y o u w ill a d d y o u r o w n c o d e to th is file . C # c o d e is p r im a r ily o r g a n iz e d
in th r e e w a y s : n a m e s p a c e s , c la s s e s , a n d m e th o d s . H e r e ’s a s u m m a r y :
• A n a m e s p a c e is a c o n ta in e r th a t h o ld s c la s s e s .
• A c la s s is a c o n ta in e r th a t h o ld s m e th o d s (a m o n g o th e r th in g s ).
• A m e th o d is a g r o u p o f o n e o r m o r e p r o g r a m m in g s ta te m e n ts th a t p e r fo r m s
s o m e o p e r a tio n .
S o , C # c o d e is o r g a n iz e d a s m e th o d s , w h ic h a r e c o n ta in e d in s id e c la s s e s , w h ic h a r e
c o n ta in e d in s id e n a m e s p a c e s . W ith th is o r g a n iz a tio n a l s tr u c tu r e in m in d , lo o k a t
F ig u r e 2 -2 7 .
F ig u r e 2 -2 7
O r g a n iz a t io n o f t h e F o r m 1 .c s c o d e
T h e fig u r e s h o w s fo u r d iffe r e n t s e c tio n s o f th e c o d e , m a r k e d w ith th e n u m b e r s 1 , 2 , 3 ,
a n d 4 . L e t’s d is c u s s e a c h s e c tio n o f c o d e .
R e c a ll fr o m C h a p te r 1 th a t C # a p p lic a tio n s r e ly h e a v ily o n th e .N E T F r a m e w o r k ,
w h ic h is a c o lle c tio n o f c la s s e s a n d o th e r c o d e . T h e c o d e in th e .N E T F r a m e w o r k is
o r g a n i z e d i n t o n a m e s p a c e s . T h e s e r i e s o f using d i r e c t i v e s t h a t a p p e a r s a t t h e t o p o f
a C # s o u r c e c o d e file in d ic a te w h ic h n a m e s p a c e s in th e .N E T F r a m e w o r k th e
p r o g r a m w ill u s e .
2 T h is s e c t io n o f c o d e c r e a t e s a n a m e s p a c e f o r t h e p r o je c t . T h e lin e t h a t r e a d s
namespace Hello_World m a r k s t h e b e g i n n i n g o f a n a m e s p a c e n a m e d Hello_
World. N o t i c e t h a t t h e n e x t l i n e c o n t a i n s a n o p e n i n g b r a c e ( {) a n d t h a t t h e l a s t l i n e
i n t h e f i l e c o n t a i n s a c o r r e s p o n d i n g c l o s i n g b r a c e ( }) . A l l t h e c o d e t h a t a p p e a r s
b e t w e e n t h e s e b r a c e s i s i n s i d e t h e Hello_World n a m e s p a c e .
3 T h i s s e c t i o n o f c o d e i s a c l a s s d e c l a r a t i o n . T h e l i n e t h a t r e a d s public partial
class, a n d s o f o r t h , m a r k s t h e b e g i n n i n g o f t h e c l a s s . T h e n e x t l i n e c o n t a i n s a n
o p e n i n g b r a c e ( {) , a n d t h e l a s t l i n e i n t h i s s e c t i o n o f c o d e c o n t a i n s a c o r r e s p o n d i n g c l o s i n g b r a c e ( }) . A l l t h e c o d e t h a t a p p e a r s b e t w e e n t h e s e b r a c e s i s i n s i d e
th e c la s s .
4 T h i s s e c t i o n o f c o d e i s a m e t h o d . T h e l i n e t h a t r e a d s public Form1()m a r k s t h e
b e g i n n i n g o f t h e m e t h o d . T h e n e x t l i n e c o n t a i n s a n o p e n i n g b r a c e ( {) , a n d t h e l a s t
l i n e i n t h i s s e c t i o n o f c o d e c o n t a i n s a c o r r e s p o n d i n g c l o s i n g b r a c e ( }) . T h e c o d e t h a t
a p p e a r s b e tw e e n th e s e b r a c e s is in s id e th e m e th o d .
1
67
68
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
It’s im p o r ta n t to p o in t o u t th a t c o d e c o n ta in e r s , s u c h a s n a m e s p a c e s , c la s s e s , a n d m e th o d s , u s e b r a c e s ( {}) t o e n c l o s e c o d e . E a c h o p e n i n g b r a c e ( {) m u s t h a v e a c o r r e s p o n d i n g
c l o s i n g b r a c e ( }) a t s o m e l a t e r p o i n t i n t h e p r o g r a m . F i g u r e 2 - 2 8 s h o w s h o w t h e b r a c e s i n
F o r m 1 .c s a r e p a ir e d .
F ig u r e 2 -2 8
C o r r e s p o n d in g b r a c e s
S w i t c h i n g b e t w e e n t h e C o d e E d i t o r a n d t h e Designer
W h e n y o u o p e n t h e c o d e e d i t o r , i t a p p e a r s i n t h e s a m e p a r t o f t h e s c r e e n a s t h e D esigner.
W h ile d e v e lo p in g a V is u a l C # a p p lic a tio n , y o u w ill o fte n fin d y o u r s e lf n e e d in g to s w itc h
b a c k a n d f o r t h b e t w e e n t h e D esigner a n d t h e c o d e e d i t o r . O n e w a y t o q u i c k l y s w i t c h
b e tw e e n th e tw o w in d o w s is to u s e th e ta b s s h o w n in F ig u r e 2 -2 9 . In th e fig u r e , n o tic e
t h a t t h e l e f t m o s t t a b r e a d s Form1. cs. T h a t i s t h e t a b f o r t h e c o d e e d i t o r . T h e r i g h t m o s t t a b
r e a d s Form1. cs [ D esign] . T h a t i s t h e t a b f o r t h e D esigner. ( T h e t a b s m a y n o t a l w a y s
a p p e a r i n t h i s o r d e r . ) T o s w i t c h b e t w e e n t h e D esigner a n d t h e c o d e e d i t o r , y o u s i m p l y
c lic k th e ta b fo r th e d e s ir e d w in d o w .
F ig u r e 2 -2 9
C o d e e d i t o r a n d Designer t a b s
Code editor tab
Designer tab
Y o u c a n a ls o d e ta c h th e c o d e e d ito r a n d m o v e it to a n o th e r p a r t o f th e s c r e e n . T h is a llo w s
y o u t o s e e t h e c o d e e d i t o r a n d t h e D esigner a t t h e s a m e t i m e . A s s h o w n i n F i g u r e 2 - 3 0 ,
c lic k th e c o d e e d ito r ta b a n d d r a g it to th e d e s ir e d lo c a tio n o n th e s c r e e n . (If y o u h a v e
m u ltip le m o n ito r s c o n n e c te d to y o u r c o m p u te r , y o u c a n e v e n d r a g th e c o d e e d ito r to a
d iffe r e n t m o n ito r .) T o r e tu r n th e c o d e e d ito r to its p o s itio n w ith in th e ID E , r ig h t-c lic k th e
t a b f o r t h e s o u r c e c o d e f i l e i n t h e c o d e e d i t o r w i n d o w a n d s e l e c t M ove to M ain D ocument
Group. T h i s i s s h o w n i n F i g u r e 2 - 3 1 .
2 .3
F ig u r e 2 -3 0
In t r o d u c t io n t o C # C o d e
D e t a c h in g t h e c o d e e d it o r b y c lic k in g a n d d r a g g in g
F ig u r e 2 -3 1
R e t u r n in g t h e c o d e e d it o r t o it s d o c k e d p o s it io n
A d d in g Y o u r O w n C o d e t o a P r o je c t
N o w y o u a r e r e a d y to le a r n h o w to a d d y o u r o w n c o d e to a p r o je c t. S u p p o s e y o u h a v e
c r e a t e d a p r o j e c t n a m e d Code D emo a n d s e t u p t h e p r o j e c t ’ s f o r m w i t h a B u t t o n c o n t r o l ,
a s s h o w n i n F i g u r e 2 - 3 2 . T h e B u t t o n c o n t r o l ’ s n a m e i s myButton, a n d i t s T e x t p r o p e r t y i s
s e t t o Click M e!.
S u p p o s e y o u w a n t t h e a p p l i c a t i o n t o d i s p l a y t h e m e s s a g e Thanks for clicking the button!
w h e n th e u s e r c lic k s th e b u tto n . T o a c c o m p lis h th a t, y o u n e e d to w r ite a s p e c ia l ty p e o f
m e th o d k n o w n a s a n e v e n t h a n d le r . A n e v e n t h a n d le r is a m e th o d th a t e x e c u te s w h e n a
s p e c ific e v e n t ta k e s p la c e w h ile a n a p p lic a tio n is r u n n in g . In th is p r o je c t y o u n e e d to w r ite
a n e v e n t h a n d l e r t h a t w i l l e x e c u t e w h e n t h e u s e r c l i c k s t h e myButton c o n t r o l . T o c r e a t e
t h e e v e n t h a n d l e r , y o u d o u b l e - c l i c k t h e myButton c o n t r o l i n t h e D esigner. T h i s o p e n s t h e
F o r m 1 .c s file in th e c o d e e d ito r , a s s h o w n in F ig u r e 2 -3 3 , w ith s o m e n e w c o d e a d d e d to it.
69
70
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
F ig u r e 2 -3 2
A fo r m w it h a B u t t o n c o n t r o l
F ig u r e 2 -3 3
T h e c o d e w in d o w o p e n e d w it h e v e n t h a n d le r c o d e g e n e r a t e d
This code was automatically added.
2 .3
In t r o d u c t io n t o C # C o d e
W h e n a n a p p lic a tio n is r u n n in g a n d th e u s e r c lic k s a c o n tr o l, w e s a y th a t a C lic k e v e n t h a s
o c c u r r e d o n th e c o n tr o l. T h e c o d e th a t h a s b e e n a d d e d to th e F o r m 1 .c s file (s h o w n in
F ig u r e 2 -3 3 ) is a n e v e n t h a n d le r th a t w ill e x e c u te w h e n a C lic k e v e n t o c c u r s o n th e
myButton c o n t r o l . F o r n o w y o u d o n o t n e e d t o u n d e r s t a n d a l l p a r t s o f t h e e v e n t h a n d l e r
c o d e . A t th is p o in t, y o u n e e d to u n d e r s ta n d o n ly th e fo llo w in g c o n c e p ts :
i n F i g u r e 2 - 3 4 , t h e e v e n t h a n d l e r ’ s n a m e i s myButton_Click . T h e
myButton p o r t i o n o f t h e n a m e i n d i c a t e s t h a t t h e e v e n t h a n d l e r i s a s s o c i a t e d w i t h
t h e myButton c o n t r o l , a n d t h e Click p o r t i o n o f t h e n a m e i n d i c a t e s t h a t t h e
• A s s h o w n
e v e n th a n d le r r e s p o n d s to C lic k e v e n ts . T h is is th e ty p ic a l n a m in g c o n v e n tio n th a t
V is u a l S tu d io u s e s w h e n it g e n e r a te s e v e n t h a n d le r c o d e . W h e n y o u s e e th e n a m e
myButton_Click, y o u u n d e r s t a n d t h a t i t i s a n e v e n t h a n d l e r t h a t e x e c u t e s w h e n a
C l i c k e v e n t o c c u r s o n t h e myButton c o n t r o l .
F ig u r e 2 -3 4
A c lo s e r lo o k a t th e e v e n t h a n d le r c o d e
The event handler’s name
Your code goes here, between the braces.
• T h e e v e n t h a n d le r th a t V is u a l S tu d io g e n e r a te s d o e s n ’t a c tu a lly d o a n y th in g . Y o u
c a n th in k o f it a s a n e m p ty c o n ta in e r to w h ic h y o u c a n a d d y o u r o w n c o d e . N o tic e
t h a t t h e s e c o n d l i n e o f t h e e v e n t h a n d l e r i s a n o p e n i n g b r a c e ( {) a n d t h e l a s t l i n e i s a
c l o s i n g b r a c e ( }) . A n y c o d e t h a t y o u w a n t e x e c u t e d w h e n t h e u s e r c l i c k s t h e
myButton c o n t r o l m u s t b e w r i t t e n b e t w e e n t h e s e b r a c e s .
N o w y o u k n o w h o w to c r e a te a n e m p ty C lic k e v e n t h a n d le r fo r a B u tto n c o n tr o l. B u t
w h a t c o d e d o y o u w r ite in s id e th e e v e n t h a n d le r ? In th is e x a m p le , w e w r ite c o d e th a t
d i s p l a y s t h e m e s s a g e Thanks for clicking the button! i n a m e s s a g e b o x , w h i c h i s a s m a l l
p o p -u p w in d o w .
M e s s a g e B o x e s
A m e s s a g e b o x is a s m a ll w in d o w , s o m e tim e s r e fe r r e d to a s a d ia lo g b o x , th a t d is p la y s a
m e s s a g e . F i g u r e 2 - 3 5 s h o w s a n e x a m p l e o f a m e s s a g e b o x d i s p l a y i n g t h e m e s s a g e Thanks
for clicking the button! N o t i c e t h a t t h e m e s s a g e b o x a l s o h a s a n O K b u t t o n . W h e n t h e
u s e r c l i c k s t h e OK b u t t o n , t h e m e s s a g e b o x c l o s e s .
F ig u r e 2 -3 5
A m e s s a g e b o x
71
72
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
T h e . N E T F r a m e w o r k p r o v i d e s a m e t h o d n a m e d MessageBox.Show t h a t y o u c a n u s e i n
V i s u a l C # t o d i s p l a y a m e s s a g e b o x . I f y o u w a n t t o e x e c u t e t h e MessageBox.Show
m e th o d , y o u w r ite a s ta te m e n t k n o w n a s a m e th o d c a ll. (P r o g r a m m e r s r e fe r to th e a c t o f
e x e c u t i n g a m e t h o d a s calling t h e m e t h o d . ) T h e f o l l o w i n g s t a t e m e n t s h o w s a n e x a m p l e o f
h o w y o u w o u l d c a l l t h e MessageBox.Show m e t h o d t o d i s p l a y t h e m e s s a g e b o x s h o w n i n
F ig u r e 2 -3 5 :
MessageBox.Show("Thanks for clicking the button!");
W h e n y o u c a l l t h e MessageBox.Show m e t h o d , y o u w r i t e a s t r i n g o f c h a r a c t e r s i n s i d e
th e p a r e n th e s e s . (In p r o g r a m m in g , w e u s e th e te r m s tr in g to m e a n s tr in g o f c h a r a c te r s .)
T h e s tr in g th a t is w r itte n in s id e th e p a r e n th e s e s w ill b e d is p la y e d in th e m e s s a g e b o x .
I n t h i s e x a m p l e , t h e s t r i n g "Thanks for clicking the button!" i s w r i t t e n i n s i d e
th e p a r e n th e s e s .
N o tic e th a t th e s tr in g is e n c lo s e d in d o u b le q u o ta tio n m a r k s in th e c o d e . W h e n th e m e s s a g e is d is p la y e d (a s s h o w n in F ig u r e 2 -3 5 ), h o w e v e r , th e d o u b le q u o ta tio n m a r k s d o n o t
a p p e a r . T h e d o u b le q u o ta tio n m a r k s a r e r e q u ir e d in th e c o d e to in d ic a te th e b e g in n in g
a n d th e e n d o f th e s tr in g .
A ls o n o tic e th a t a s e m ic o lo n a p p e a r s a t th e e n d o f th e s ta te m e n t. T h is is r e q u ir e d b y C #
s y n ta x . J u s t a s a p e r io d m a r k s th e e n d o f a s e n te n c e , a s e m ic o lo n m a r k s th e e n d o f a p r o g r a m m in g s ta te m e n t in C # .
G e t t i n g b a c k t o o u r Code D emo e x a m p l e p r o j e c t , F i g u r e 2 - 3 6 s h o w s h o w y o u c a n c a l l t h e
MessageBox.Show m e t h o d f r o m t h e myButton_Click e v e n t h a n d l e r . A f t e r t y p i n g t h e
s ta te m e n t a s s h o w n in th e fig u r e , y o u c a n p r e s s th e
k e y o n th e k e y b o a r d , o r c lic k
t h e Start D ebugging b u t t o n ( ) o n t h e t o o l b a r t o c o m p i l e a n d r u n t h e a p p l i c a t i o n . W h e n
th e a p p lic a tio n r u n s , it w ill d is p la y th e fo r m s h o w n o n th e le ft in F ig u r e 2 -3 7 . W h e n y o u
c lic k th e b u tto n , th e m e s s a g e b o x s h o w n o n th e r ig h t in th e fig u r e w ill a p p e a r . Y o u c a n
c l i c k t h e OK b u t t o n o n t h e m e s s a g e b o x t o c l o s e i t .
F ig u r e 2 -3 6
E v e n t h a n d le r c o d e fo r d is p la y in g a m e s s a g e b o x
2 .3
F ig u r e 2 -3 7
In t r o d u c t io n t o C # C o d e
T h e Code Demo p r o j e c t r u n n i n g
When you click this button...
this window will appear.
N O T E : W h e n w r itin g a C lic k e v e n t h a n d le r fo r a B u tto n c o n tr o l, y o u m ig h t b e
w o n d e r i n g i f i t i s n e c e s s a r y t o f i r s t d o u b l e - c l i c k t h e B u t t o n c o n t r o l i n t h e D esigner,
c r e a tin g th e e m p ty e v e n t h a n d le r c o d e . A fte r a ll, c o u ld n ’t y o u ju s t s k ip th is s te p a n d
in s te a d o p e n th e c o d e e d ito r a n d w r ite a ll th e e v e n t h a n d le r c o d e y o u r s e lf? T h e a n s w e r
i s n o , y o u c a n n o t s k i p t h i s s t e p . W h e n y o u d o u b l e - c l i c k a c o n t r o l i n t h e D esigner,
V is u a l S tu d io n o t o n ly c r e a te s a n e m p ty e v e n t h a n d le r , b u t it a ls o w r ite s s o m e c o d e
th a t y o u d o n ’t s e e e ls e w h e r e in th e p r o je c t. T h is o th e r c o d e is n e c e s s a r y fo r th e e v e n t
h a n d le r to p r o p e r ly fu n c tio n .
S t r in g L it e r a ls
P r o g r a m s a lm o s t a lw a y s w o r k w ith d a ta o f s o m e ty p e . F o r e x a m p le , th e c o d e s h o w n in
F i g u r e 2 - 3 6 u s e s t h e f o l l o w i n g s t r i n g w h e n i t c a l l s t h e MessageBox.Show m e t h o d :
"Thanks for clicking the button!"
T h is s tr in g is th e d a ta th a t is d is p la y e d b y th e p r o g r a m . W h e n a p ie c e o f d a ta is w r itte n
i n t o a p r o g r a m ’ s c o d e , i t ’ s c a l l e d a l i t e r a l ( b e c a u s e t h e d a t a i s literally w r i t t e n i n t o t h e
p r o g r a m ) . W h e n a s t r i n g i s w r i t t e n i n t o a p r o g r a m ’ s c o d e , i t ’ s c a l l e d a string literal. I n C # ,
s tr in g lite r a ls m u s t b e e n c lo s e d in d o u b le q u o ta tio n m a r k s .
N O T E : P r o g r a m m e r s s o m e t i m e s s a y t h a t l i t e r a l s a r e v a l u e s t h a t a r e hard coded i n t o
a p r o g r a m b e c a u s e th e v a lu e o f a lite r a l c a n n o t c h a n g e w h ile th e p r o g r a m is r u n n in g .
M u lt ip le B u t t o n s w it h E v e n t H a n d le r s
T h e Code D emo p r o j e c t p r e v i o u s l y s h o w n h a s o n l y o n e b u t t o n w i t h a C l i c k e v e n t h a n d le r . M a n y o f th e a p p lic a tio n s th a t y o u w ill d e v e lo p w ill h a v e m u ltip le b u tto n s , e a c h w ith
its o w n C lic k e v e n t h a n d le r . F o r e x a m p le , th e fo r m s h o w n in F ig u r e 2 -3 8 h a s th r e e B u tto n
c o n t r o l s . A s s h o w n i n t h e f i g u r e , t h e c o n t r o l s a r e n a m e d firstButton, secondButton,
a n d thirdButton.
F ig u r e 2 -3 8
A fo r m w it h m u lt ip le B u t t o n c o n t r o ls
firstButton
secondButton
thirdButton
73
74
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
T o c r e a te C lic k e v e n t h a n d le r s fo r th e b u tto n s , y o u s im p ly d o u b le -c lic k e a c h B u tto n c o n t r o l i n t h e D esigner a n d a n e m p t y e v e n t h a n d l e r w i l l b e c r e a t e d i n t h e f o r m ’ s s o u r c e c o d e
f i l e . T h e n a m e s o f t h e C l i c k e v e n t h a n d l e r s w i l l b e firstButton_Click, secondButton_
Click, a n d thirdButton_Click. F i g u r e 2 - 3 9 s h o w s a n e x a m p l e o f t h e f o r m ’ s s o u r c e
c o d e a f t e r t h e t h r e e e v e n t h a n d l e r s h a v e b e e n c r e a t e d a n d a MessageBox.Show s t a t e m e n t
h as b een ad d ed to each o n e.
F ig u r e 2 -3 9
S o u r c e c o d e w it h t h r e e C lic k e v e n t h a n d le r s
D e s ig n T im e a n d R u n T im e
W h e n y o u h a v e a p r o je c t o p e n in V is u a l S tu d io , th e tim e d u r in g w h ic h y o u b u ild th e G U I
a n d w r ite th e a p p lic a tio n ’s c o d e is r e fe r r e d to a s d e s ig n tim e . D u r in g d e s ig n tim e , y o u c a n
u s e t h e D esigner a n d t h e Toolbox t o p l a c e c o n t r o l s o n t h e f o r m , u s e t h e Properties w i n d o w to s e t p r o p e r ty v a lu e s , u s e th e c o d e e d ito r to w r ite c o d e , a n d s o fo r th . T h is is th e
p h a s e d u r in g w h ic h y o u c r e a te o r m o d ify th e a p p lic a tio n .
W h e n y o u a r e r e a d y to r u n a p r o je c t th a t y o u h a v e o p e n in V is u a l S tu d io , y o u p r e s s th e
k e y o n t h e k e y b o a r d o r c l i c k t h e Start D ebugging b u t t o n ( ) o n t h e t o o l b a r . T h e p r o je c t w ill b e c o m p ile d , a n d if th e r e w e r e n o e r r o r s , it w ill b e e x e c u te d . T h e tim e d u r in g
w h ic h a n a p p lic a tio n is e x e c u tin g is r e fe r r e d to a s r u n tim e . D u r in g r u n tim e , y o u c a n
i n t e r a c t w i t h t h e r u n n i n g a p p l i c a t i o n , b u t y o u c a n n o t u s e t h e D esigner, t h e Toolbox, t h e
Properties w i n d o w , t h e c o d e e d i t o r , o r p a r t s o f V i s u a l S t u d i o t o m a k e c h a n g e s t o i t .
2 .4
W r i t i n g C o d e f o r t h e Hello World A p p l i c a t i o n
N O T E : I n c o m p u t i n g l i t e r a t u r e a n d o n t h e W e b , y o u w i l l s e e t h e t e r m run time a l s o
s p e l l e d a s runtime o r run- time. A l l t h e s e v a r i a t i o n s t y p i c a l l y m e a n t h e s a m e t h i n g .
C h e c k p o in t
2 .4
2 .1 5
A file th a t c o n ta in s p r o g r a m c o d e is k n o w n a s w h a t ty p e o f file ?
2 .1 6
W h a t m u s t y o u d o if y o u w a n t y o u r a p p lic a tio n to p e r fo r m a n y m e a n in g fu l a c tio n s ?
2 .1 7
W h a t d o e s th e P r o g r a m .c s file c o n ta in ?
2 .1 8
W h a t d o e s th e F o r m 1 .c s file c o n ta in ?
2 .1 9
H o w is C # c o d e o r g a n iz e d ?
2 .2 0
W h a t is a n a m e s p a c e ?
2 .2 1
W h a t c h a r a c te r s d o c o d e c o n ta in e r s , s u c h a s n a m e s p a c e s , c la s s e s , a n d m e th o d s ,
u s e to e n c lo s e c o d e ?
2 .2 2
H o w d o y o u s w i t c h b e t w e e n t h e D esigner a n d t h e c o d e e d i t o r ?
2 .2 3
H o w d o y o u c r e a te a n e v e n t h a n d le r fo r a b u tto n ?
2 .2 4
W h a t is a C lic k e v e n t?
2 .2 5
W h a t m e th o d d o y o u u s e in V is u a l C # to d is p la y a m e s s a g e b o x ?
2 .2 6
W h a t is a lite r a l?
2 .2 7
W h a t a r e s tr in g lite r a ls e n c lo s e d in ?
2 .2 8
H o w d o y o u r u n a p r o je c t th a t y o u h a v e o p e n in V is u a l S tu d io ?
W r i t i n g C o d e f o r t h e Hello Wor ld A p p l i c a t i o n
N o w y o u k n o w e v e r y t h i n g n e c e s s a r y t o c o m p l e t e t h e H ello World p r o j e c t . I n T u t o r i a l 2 - 2 ,
y o u w i l l o p e n t h e p r o j e c t a n d a d d a C l i c k e v e n t h a n d l e r f o r t h e messageButton c o n t r o l .
T h e e v e n t h a n d l e r w i l l c a l l t h e MessageBox.Show m e t h o d t o d i s p l a y a m e s s a g e b o x w i t h
t h e m e s s a g e H ello World.
T u t o r ia l 2 -2 :
W r i t i n g C o d e f o r t h e Hello World A p p l i c a t i o n
VideoNot e
T u to r ia l 2 -2 :
W r itin g
Co d e fo r th e
H ello World
A p p lic a tio n
S t e p 1 :
I f V i s u a l S t u d i o i s n o t a l r e a d y r u n n i n g , s t a r t i t . O p e n t h e H ello World p r o j e c t
th a t y o u s ta r te d in T u to r ia l 2 -1 .
S t e p 2 :
M a k e s u r e t h e F o r m 1 f o r m i s v i s i b l e i n t h e D esigner, a s s h o w n i n F i g u r e 2 - 4 0 . I f
i t i s n o t , r i g h t - c l i c k F o r m 1 . c s i n t h e Solution Explorer a n d t h e n s e l e c t View
D esigner f r o m t h e p o p - u p m e n u .
S t e p 3 :
I n t h e D esigner, d o u b l e - c l i c k t h e messageButton c o n t r o l . T h i s s h o u l d c a u s e t h e
c o d e e d ito r to a p p e a r a s s h o w n in F ig u r e 2 -4 1 . N o tic e th a t a n e m p ty e v e n t
h a n d l e r n a m e d messageButton_Click h a s b e e n c r e a t e d .
75
76
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
F ig u r e 2 -4 0
T h e Hello World p r o j e c t l o a d e d w i t h F o r m 1 s h o w n i n t h e Designer
F ig u r e 2 -4 1
C o d e e d it o r w it h a n e m p t y e v e n t h a n d le r
2 .4
S t e p 4 :
W r i t i n g C o d e f o r t h e Hello World A p p l i c a t i o n
I n s i d e t h e messageButton_Click e v e n t h a n d l e r , t y p e t h e f o l l o w i n g s t a t e m e n t
e x a c tly a s it is s h o w n :
MessageBox.Show("Hello World");
D o n ’t fo r g e t to ty p e th e s e m ic o lo n a t th e e n d o f th e s ta te m e n t! W h e n y o u h a v e
fin is h e d , th e c o d e w in d o w s h o u ld lo o k lik e F ig u r e 2 -4 2 .
F ig u r e 2 -4 2
S t a t e m e n t w r it t e n in s id e t h e e v e n t h a n d le r
S t e p 5 :
S a v e th e p r o je c t.
S t e p 6 :
P ress th e
k e y o n t h e k e y b o a r d , o r c l i c k t h e Start D ebugging b u t t o n (
th e to o lb a r to c o m p ile a n d r u n th e a p p lic a tio n .
) o n
N O T E : I f y o u t y p e d t h e s t a t e m e n t c o r r e c t l y i n s i d e t h e messageButton_
Click e v e n t h a n d l e r ( i n S t e p 4 ) , t h e a p p l i c a t i o n s h o u l d r u n . I f y o u d i d n o t t y p e
th e s ta te m e n t c o r r e c tly , h o w e v e r , a w in d o w w ill a p p e a r r e p o r tin g b u ild e r r o r s .
I f t h a t h a p p e n s , c l i c k t h e No b u t t o n i n t h e w i n d o w a n d t h e n c o r r e c t t h e s t a t e m e n t s o it a p p e a r s e x a c tly a s s h o w n in F ig u r e 2 -4 2 .
W h e n th e a p p lic a tio n r u n s , it w ill d is p la y th e fo r m s h o w n o n th e le ft in F ig u r e 2 -4 3 .
W h e n y o u c l i c k t h e D isplay M essage b u t t o n , t h e m e s s a g e b o x s h o w n o n t h e r i g h t i n t h e
f i g u r e w i l l a p p e a r . Y o u c a n c l i c k t h e OK b u t t o n o n t h e m e s s a g e b o x t o c l o s e i t .
77
78
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
F ig u r e 2 -4 3
T h e Hello World a p p l i c a t i o n r u n n i n g
When you click this button...
this window will appear.
2 .5
L a b e l C o n t r o ls
C O N C E P T :
A L a b e l c o n tr o l d is p la y s te x t o n a fo r m . L a b e l c o n tr o ls h a v e v a r io u s
p r o p e r t i e s t h a t a f f e c t t h e c o n t r o l ’s a p p e a r a n c e . L a b e l c o n t r o l s c a n b e u s e d
to d is p la y u n c h a n g in g te x t, o r p r o g r a m o u tp u t.
W h e n y o u w a n t to d is p la y te x t o n a fo r m , y o u u s e a L a b e l c o n tr o l. F ig u r e 2 -4 4 s h o w s a n
e x a m p le o f a fo r m w ith tw o L a b e l c o n tr o ls . O n c e y o u h a v e p la c e d a L a b e l c o n tr o l o n a
fo r m , y o u s e t its T e x t p r o p e r ty to th e te x t th a t y o u w a n t to d is p la y . F o r e x a m p le , in
F i g u r e 2 - 4 4 , t h e u p p e r L a b e l c o n t r o l ’ s T e x t p r o p e r t y i s s e t t o N umber of H ours Worked,
a n d t h e l o w e r L a b e l c o n t r o l ’ s T e x t p r o p e r t y i s s e t t o H ourly Pay Rate.
F ig u r e 2 -4 4
A fo r m w it h L a b e l c o n t r o ls
Label controls
Y o u ’ l l f i n d t h e L a b e l c o n t r o l t o o l i n t h e Common Controls g r o u p o f t h e Toolbox, a s
s h o w n in F ig u r e 2 -4 5 . T o c r e a te a L a b e l c o n tr o l o n a fo r m , y o u d o u b le -c lic k th e L a b e l
c o n t r o l t o o l i n t h e Toolbox. A s s h o w n i n F i g u r e 2 - 4 5 , a L a b e l c o n t r o l w i l l b e c r e a t e d o n
t h e f o r m . ( A l t e r n a t i v e l y , y o u c a n c l i c k a n d d r a g t h e L a b e l c o n t r o l t o o l f r o m t h e Toolbox
o n to th e fo r m .) N o tic e th a t a b o u n d in g b o x a p p e a r s a r o u n d th e L a b e l c o n tr o l in th e fig u r e . T h is in d ic a te s th a t th e c o n tr o l is c u r r e n tly s e le c te d .
W h e n y o u c r e a te L a b e l c o n tr o ls , th e y a r e a u to m a tic a lly g iv e n d e fa u lt n a m e s s u c h a s
label1, label2, a n d s o f o r t h . A L a b e l c o n t r o l ’ s T e x t p r o p e r t y i s i n i t i a l l y s e t t o t h e
s a m e v a lu e a s th e L a b e l c o n tr o l’s n a m e . S o , a L a b e l c o n tr o l w ill d is p la y its o w n n a m e
w h e n it is c r e a te d , a s s h o w n b y th e e x a m p le in F ig u r e 2 -4 5 . W h e n a L a b e l c o n tr o l is
s e l e c t e d i n t h e D esigner, y o u c a n u s e t h e Properties w i n d o w t o c h a n g e i t s T e x t p r o p e r t y .
F i g u r e 2 - 4 6 s h o w s a L a b e l c o n t r o l a f t e r i t s T e x t p r o p e r t y h a s b e e n c h a n g e d t o Programming in Visual C# is fun!
2 .5
F ig u r e 2 -4 5
C r e a t in g a L a b e l c o n t r o l
F ig u r e 2 -4 6
A L a b e l c o n t r o l d is p la y in g a m e s s a g e
L a b e l C o n tr o ls
Y o u c a n a l s o u s e t h e Properties w i n d o w t o c h a n g e a L a b e l c o n t r o l ’ s n a m e . I t ’ s a l w a y s a
g o o d id e a to c h a n g e a c o n tr o l’s n a m e to s o m e th in g th a t is m o r e m e a n in g fu l th a n th e
d e fa u lt n a m e th a t V is u a l S tu d io g iv e s it.
T h e F o n t P r o p e r t y
If y o u w a n t to c h a n g e th e a p p e a r a n c e o f a L a b e l c o n tr o l’s te x t, y o u c a n c h a n g e th e c o n tr o l’s F o n t p r o p e r ty . T h e F o n t p r o p e r ty a llo w s y o u to s e t th e fo n t, fo n t s ty le , a n d s iz e o f
t h e c o n t r o l ’ s t e x t . W h e n y o u s e l e c t t h e F o n t p r o p e r t y i n t h e Properties w i n d o w , y o u w i l l
n o tic e th a t a n e llip s e s b u tto n ( ) a p p e a r s n e x t to th e p r o p e r ty ’s v a lu e , a s s h o w n in
F i g u r e 2 - 4 7 . W h e n y o u c l i c k t h e e l l i p s e s b u t t o n , t h e Font d i a l o g b o x a p p e a r s , a s s h o w n
F ig u r e 2 -4 7
T h e F o n t p ro p e rty
Click here to change the Font property.
79
80
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
i n F i g u r e 2 - 4 8 . S e l e c t a f o n t , f o n t s t y l e , a n d s i z e , a n d c l i c k O K. T h e t e x t d i s p l a y e d b y t h e
c o n tr o l w ill b e u p d a te d w ith th e s e le c te d a ttr ib u te s . F o r e x a m p le , F ig u r e 2 -4 9 s h o w s a
L a b e l c o n tr o l w ith th e fo llo w in g F o n t p r o p e r ty a ttr ib u te s :
F o n t: L u c id a H a n d w r itin g
F o n t S ty le : Ita lic
S iz e : 1 0 p o in t
F ig u r e 2 -4 8
T h e Font d i a l o g b o x
F ig u r e 2 -4 9
A la b e l’ s a p p e a r a n c e w it h a lt e r e d fo n t a t t r ib u t e s
T h e B o r d e r S t y le P r o p e r t y
L a b e l c o n tr o ls h a v e a B o r d e r S ty le p r o p e r ty th a t a llo w s y o u to d is p la y a b o r d e r a r o u n d th e
c o n tr o l’s te x t. T h e B o r d e r S ty le p r o p e r ty m a y h a v e o n e o f th r e e v a lu e s : N o n e , F ix e d S in g le ,
o r F ix e d 3 D . T h e p r o p e r ty is s e t to N o n e b y d e fa u lt, w h ic h m e a n s th a t n o b o r d e r w ill
a p p e a r a r o u n d th e c o n tr o l’s te x t. If th e B o r d e r S ty le p r o p e r ty is s e t to F ix e d S in g le , th e
c o n tr o l’s te x t w ill b e o u tlin e d w ith a th in b o r d e r . If th e B o r d e r S ty le p r o p e r ty is s e t to
F ix e d 3 D , th e c o n tr o l’s te x t w ill h a v e a r e c e s s e d 3 D a p p e a r a n c e . F ig u r e 2 -5 0 s h o w s a n
e x a m p le o f L a b e l c o n tr o ls w ith e a c h B o r d e r S ty le s e ttin g . T h e im a g e o n th e le ft in th e fig u r e s h o w s th e fo r m in th e D e s ig n e r , a n d th e im a g e o n th e r ig h t s h o w s th e fo r m a t r u n tim e .
T o c h a n g e t h e B o r d e r S t y l e p r o p e r t y , s e l e c t i t i n t h e Properties w i n d o w a n d t h e n c l i c k
th e d o wn -arro w b u tto n (
) th a t a p p e a r s n e x t to th e p r o p e r ty ’s v a lu e . A s s h o w n in
F ig u r e 2 -5 1 , a d r o p -d o w n lis t w ill a p p e a r c o n ta in in g th e th r e e p o s s ib le v a lu e s fo r th is
p r o p e r ty . S e le c t th e d e s ir e d v a lu e a n d th e c o n tr o l’s te x t w ill b e u p d a te d .
2 .5
F ig u r e 2 -5 0
B o r d e r S ty le e x a m p le s
F ig u r e 2 -5 1
B o r d e r S t y le s e le c t io n s
L a b e l C o n tr o ls
T h e A u t o S iz e P r o p e r t y
L a b e l c o n tr o ls h a v e a n A u to S iz e p r o p e r ty th a t c o n tr o ls th e w a y th e y c a n b e r e s iz e d . T h e
A u to S iz e p r o p e r ty is a B o o le a n p r o p e r ty , w h ic h m e a n s th a t it c a n b e s e t to o n e o f tw o p o s s ib le
v a lu e s : T r u e o r F a ls e . B y d e fa u lt, a L a b e l c o n tr o l’s A u to S iz e p r o p e r ty is s e t to T r u e , w h ic h
m e a n s th a t th e c o n tr o l a u to m a tic a lly r e s iz e s its e lf to a c c o m m o d a te th e s iz e o f th e te x t it d is p la y s . F o r e x a m p le , lo o k a t th e th r e e L a b e l c o n tr o ls in F ig u r e 2 -5 2 . E a c h o f th e c o n tr o ls d is p la y s
d iffe r e n t a m o u n ts o f te x t a t d iffe r e n t fo n t s iz e s . B e c a u s e e a c h c o n tr o l’s B o r d e r S ty le p r o p e r ty is
s e t to F ix e d S in g le , y o u c a n s e e th a t e a c h c o n tr o l is ju s t la r g e e n o u g h to a c c o m m o d a te its te x t.
F ig u r e 2 -5 2
L a b e l c o n t r o ls w it h A u t o S iz e s e t t o T r u e
W h e n a L a b e l c o n tr o l’s A u to S iz e p r o p e r ty is s e t to T r u e , y o u c a n n o t m a n u a lly c h a n g e th e
s iz e o f th e c o n tr o l b y c lic k in g a n d d r a g g in g its b o u n d in g b o x . If y o u w a n t to m a n u a lly
c h a n g e th e s iz e o f a L a b e l c o n tr o l, y o u h a v e to s e t its A u to S iz e p r o p e r ty to F a ls e . W h e n
A u to S iz e is s e t to F a ls e , s iz in g h a n d le s w ill a p p e a r a r o u n d th e c o n tr o l, a llo w in g y o u to
81
82
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
c lic k a n d d r a g th e b o u n d in g b o x to r e s iz e th e c o n tr o l. F ig u r e 2 -5 3 s h o w s a n e x a m p le . In
th e fig u r e , th e L a b e l c o n tr o l h a s b e e n r e s iz e d s o it is m u c h la r g e r th a n th e te x t it d is p la y s .
F ig u r e 2 -5 3
L a b e l c o n t r o l w it h A u t o S iz e s e t t o F a ls e
N O T E : W h e n a L a b e l c o n tr o l’s A u to S iz e p r o p e r ty is s e t to T r u e , th e la b e l’s te x t w ill
a lw a y s a p p e a r o n o n e lin e . W h e n th e A u to S iz e p r o p e r ty is s e t to F a ls e , th e la b e l’s te x t
w ill w r a p a c r o s s m u ltip le lin e s if it is to o lo n g to fit o n o n e lin e .
T h e T e x t A lig n P r o p e r t y
W h e n y o u s e t a L a b e l c o n tr o l’s A u to S iz e p r o p e r ty to F a ls e a n d th e n m a n u a lly r e s iz e th e
c o n tr o l, it s o m e tim e s b e c o m e s n e c e s s a r y to c h a n g e th e w a y th e la b e l’s te x t is a lig n e d . B y
d e fa u lt, a la b e l’s te x t is a lig n e d w ith th e to p a n d le ft e d g e s o f th e la b e l’s b o u n d in g b o x .
F o r e x a m p le , lo o k a t th e la b e l s h o w n in F ig u r e 2 -5 3 . N o tic e h o w th e te x t is p o s itio n e d in
th e la b e l’s u p p e r -le ft c o r n e r .
W h a t if w e w a n t th e te x t to b e a lig n e d d iffe r e n tly w ith in th e la b e l? F o r e x a m p le , w h a t if w e
w a n t th e te x t to b e c e n te r e d in th e la b e l o r p o s itio n e d in th e lo w e r -r ig h t c o r n e r ? W e c a n
c h a n g e th e te x t’s a lig n m e n t in th e la b e l w ith th e T e x tA lig n p r o p e r ty . T h e T e x tA lig n p r o p e r ty m a y b e s e t to a n y o f th e fo llo w in g v a lu e s : T o p L e ft, T o p C e n te r , T o p R ig h t, M id d le L e ft,
M id d le C e n te r , M id d le R ig h t, B o tto m L e ft, B o tto m C e n te r , o r B o tto m R ig h t. F ig u r e 2 -5 4
s h o w s n in e L a b e l c o n tr o ls , e a c h w ith a d iffe r e n t T e x tA lig n v a lu e .
F ig u r e 2 -5 4
T e x t a lig n m e n t s
T o c h a n g e t h e T e x t A l i g n p r o p e r t y , s e l e c t i t i n t h e Properties w i n d o w a n d t h e n c l i c k t h e
d o wn -arro w b u tto n (
) th a t a p p e a r s n e x t to its v a lu e . T h is c a u s e s a d ia lo g b o x w ith n in e
b u tto n s , a s s h o w n in th e le ft im a g e in F ig u r e 2 -5 5 , to a p p e a r . A s s h o w n in th e r ig h t im a g e
in th e fig u r e , th e n in e b u tto n s r e p r e s e n t th e v a lid s e ttin g s o f th e T e x tA lig n p r o p e r ty .
U s in g C o d e t o D is p la y O u t p u t in a L a b e l C o n t r o l
In a d d itio n to d is p la y in g u n c h a n g in g te x t o n a fo r m , L a b e l c o n tr o ls a r e a ls o u s e fu l fo r
d is p la y in g o u tp u t w h ile a n a p p lic a tio n is r u n n in g . F o r e x a m p le , s u p p o s e y o u a r e c r e a tin g
a n a p p lic a tio n th a t p e r fo r m s a c a lc u la tio n a n d y o u w a n t to d is p la y th e r e s u lt o f th e
2 .5
F ig u r e 2 -5 5
L a b e l C o n tr o ls
S e t t in g t h e T e x t A lig n p r o p e r t y
TopCenter
MiddleCenter
TopLeft
TopRight
MiddleLeft
MiddleRight
BottomLeft
BottomRight
BottomCenter
c a lc u la tio n a t a s p e c ific lo c a tio n o n th e fo r m . U s in g a L a b e l c o n tr o l to d is p la y th e o u tp u t
w o u ld b e a n id e a l s o lu tio n . H e r e a r e th e g e n e r a l s te p s th a t y o u w o u ld fo llo w :
Step 1 :
Step 2 :
W h i l e c r e a t i n g t h e a p p l i c a t i o n ’s G U I , y o u p l a c e a L a b e l c o n t r o l o n t h e f o r m a t
t h e l o c a t i o n w h e r e y o u w a n t t h e r e s u l t t o b e d i s p l a y e d . T h e n , i n t h e Properties
w i n d o w , y o u e r a s e t h e c o n t e n t s o f t h e L a b e l c o n t r o l ’s T e x t p r o p e r t y . B e c a u s e
t h e c o n t r o l ’s T e x t p r o p e r t y i s e m p t y , t h e c o n t r o l w i l l n o t i n i t i a l l y d i s p l a y a n y th in g w h e n th e a p p lic a tio n r u n s .
I n t h e a p p l i c a t i o n ’s c o d e , y o u w r i t e t h e n e c e s s a r y s t a t e m e n t s t o p e r f o r m t h e c a l c u l a t i o n a n d t h e n y o u s t o r e t h e r e s u l t o f t h e c a l c u l a t i o n i n t h e L a b e l c o n t r o l ’s T e x t
p r o p e r ty . T h is c a u s e s th e r e s u lt to b e d is p la y e d o n th e fo r m in th e L a b e l c o n tr o l.
N O T E : W e d o n o t d is c u s s c a lc u la tio n s u n til C h a p te r 3 , s o in th is c h a p te r w e lo o k a t
e x a m p le s th a t d is p la y n o n m a th e m a tic a l d a ta a s o u tp u t in L a b e l c o n tr o ls .
In c o d e , y o u u s e a n a s s ig n m e n t s ta te m e n t to s to r e a v a lu e in a c o n tr o l’s p r o p e r ty . F o r e x a m p le ,
s u p p o s e y o u h a v e c r e a t e d a L a b e l c o n t r o l a n d n a m e d i t outputLabel. T h e f o l l o w i n g a s s i g n m e n t s t a t e m e n t s t o r e s t h e s t r i n g "Thank you very much" i n t h e c o n t r o l ’ s T e x t p r o p e r t y .
outputLabel.Text = "Thank you very much";
T h e e q u a l s i g n ( =) i s k n o w n a s t h e a s s i g n m e n t o p e r a t o r . I t a s s i g n s t h e v a l u e t h a t a p p e a r s
o n its r ig h t s id e to th e ite m th a t a p p e a r s o n its le ft s id e . In th is e x a m p le , th e ite m o n th e
l e f t s i d e o f t h e a s s i g n m e n t o p e r a t o r i s t h e e x p r e s s i o n outputLabel.Text. T h i s i s s i m p l y
t h e outputLabel c o n t r o l ’ s T e x t p r o p e r t y . T h e v a l u e o n t h e r i g h t s i d e o f t h e a s s i g n m e n t
o p e r a t o r i s t h e s t r i n g "Thank you very much". W h e n t h i s s t a t e m e n t e x e c u t e s , t h e s t r i n g
"Thank you very much" i s a s s i g n e d t o t h e outputLabel c o n t r o l ’ s T e x t p r o p e r t y . W h e n
t h i s s t a t e m e n t e x e c u t e s , t h e t e x t Thank you very much i s d i s p l a y e d i n t h e L a b e l c o n t r o l .
W A R N I N G ! W h e n w r itin g a s s ig n m e n t s ta te m e n ts , r e m e m b e r th a t th e ite m r e c e iv in g th e v a lu e m u s t b e o n th e le ft s id e o f th e =o p e r a to r . T h e fo llo w in g s ta te m e n t, fo r
e x a m p le , is w r o n g a n d w ill c a u s e a n e r r o r w h e n y o u c o m p ile th e p r o g r a m :
"Thank you very much" = outputLabel;
N O T E :
d
ERROR!
T h e s ta n d a r d n o ta tio n fo r r e fe r r in g to a c o n tr o l’s p r o p e r ty in c o d e is :
ControlName.PropertyName
83
84
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
L e t’s lo o k a t a n e x a m p le a p p lic a tio n th a t u s e s a L a b e l c o n tr o l to d is p la y o u tp u t. M a k e
s u r e y o u h a v e d o w n lo a d e d th e s tu d e n t s a m p le p r o g r a m s fr o m th e b o o k ’s c o m p a n io n W e b
s i t e ( a t w w w . p e a r s o n h i g h e r e d . c o m / g a d d i s ) . I n t h e Chap02 f o l d e r , y o u w i l l f i n d a p r o j e c t
n a m e d Presidential Trivia. T h e p u r p o s e o f t h e a p p l i c a t i o n i s t o d i s p l a y a t r i v i a q u e s t i o n
a b o u t a fo r m e r U .S . p r e s id e n t. W h e n th e u s e r c lic k s a b u tto n , th e a n s w e r to th e tr iv ia
q u e s tio n is d is p la y e d o n th e fo r m . T h e p r o je c t’s fo r m a p p e a r s a s s h o w n in F ig u r e 2 -5 6 .
F ig u r e 2 -5 6
P r e s id e n t ia l T r iv ia fo r m
questionLabel
answerLabel
showAnswerButton
A s s h o w n in th e fig u r e , th e fo r m h a s th e th r e e c o n tr o ls :
• A L a b e l c o n t r o l n a m e d questionLabel. T h i s l a b e l d i s p l a y s t h e t r i v i a q u e s t i o n .
• A L a b e l c o n t r o l n a m e d answerLabel. T h i s l a b e l i n i t i a l l y a p p e a r s e m p t y , b u t w i l l b e
u s e d to d is p la y th e a n s w e r to th e tr iv ia q u e s tio n .
• A B u t t o n c o n t r o l n a m e d showAnswerButton. W h e n t h e u s e r c l i c k s t h i s b u t t o n , t h e
a n s w e r to th e tr iv ia q u e s tio n is d is p la y e d .
T a b le 2 -2 lis ts th e p r o p e r ty s e ttin g s fo r e a c h c o n tr o l o f w h ic h y o u s h o u ld ta k e n o te .
T a b le 2 -2
C o n t r o l p r o p e r t y s e t t in g s
Co n tro l Name
Co n tro l Typ e
P r o p e r ty S e ttin g s
questionLabel
Lab el
A u to S iz e : F a ls e
B o r d e r S ty le : N o n e
F o n t: M ic r o s o ft S a n s S e r if (S ty le : R e g u la r , S iz e : 1 0 p o in t)
T e x t : What former U.S. president is known for going on
an African safari?
T e x tA lig n : M id d le C e n te r
answerLabel
Lab el
A u to S iz e : F a ls e
B o r d e r S ty le : F ix e d S in g le
F o n t: M ic r o s o ft S a n s S e r if (S ty le : B o ld , S iz e : 1 0 p o in t)
Tex t: (Th e co n ten ts o f th e Tex t p ro p erty h ave b een
e r a s e d .)
T e x tA lig n : M id d le C e n te r
showAnswerButton
Bu tto n
S iz e : 1 1 0 , 2 3
T e x t : Show the Answer
If w e o p e n th e F o r m 1 .c s file in th e c o d e e d ito r , w e s e e th e c o d e s h o w n in F ig u r e 2 -5 7 .
( T o o p e n t h e f i l e i n t h e c o d e w i n d o w , r i g h t - c l i c k F o r m 1 . c s i n t h e Solution Explorer
a n d t h e n s e l e c t View Code. ) N o t i c e t h e m e t h o d n a m e d showAnswerButton_Click.
2 .5
F ig u r e 2 -5 7
L a b e l C o n tr o ls
F o rm 1 .c s c o d e
T h i s i s t h e C l i c k e v e n t h a n d l e r f o r t h e showAnswerButton c o n t r o l . I t c o n t a i n s t h e f o l lo w in g s ta te m e n t:
answerLabel.Text = "Theodore Roosevelt";
W h e n t h i s s t a t e m e n t e x e c u t e s , i t a s s i g n s t h e s t r i n g "Theodore Roosevelt" t o t h e
answerLabel c o n t r o l ’ s T e x t p r o p e r t y . A s a r e s u l t , T h e o d o r e R o o s e v e l t i s d i s p l a y e d i n t h e
la b e l c o n tr o l.
W h e n y o u r u n th e a p p lic a tio n , th e fo r m a p p e a r s a s s h o w n o n th e le ft in F ig u r e 2 -5 8 . C lic k
t h e Show the Answer b u t t o n a n d t h e a n s w e r t o t h e t r i v i a q u e s t i o n a p p e a r s a s s h o w n o n
th e r ig h t in th e fig u r e .
F ig u r e 2 -5 8
T h e Presidentia l Trivia a p p l i c a t i o n r u n n i n g
T h e T e x t P r o p e r t y A c c e p t s S t r in g s O n ly
It is im p o r ta n t to p o in t o u t th a t th e L a b e l c o n tr o l’s T e x t p r o p e r ty c a n a c c e p t s tr in g s o n ly . Y o u
c a n n o t a s s ig n a n u m b e r to th e T e x t p r o p e r ty . F o r e x a m p le , le t’s a s s u m e th a t a n a p p lic a tio n
85
86
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
h a s a L a b e l c o n t r o l n a m e d resultLabel. T h e f o l l o w i n g s t a t e m e n t w i l l c a u s e a n e r r o r b e c a u s e
i t i s a t t e m p t i n g t o s t o r e t h e n u m b e r 5 i n t h e resultLabel c o n t r o l ’ s T e x t p r o p e r t y :
resultLabel.Text = 5;
d
ERROR!
T h is d o e s n o t m e a n th a t y o u c a n n o t d is p la y a n u m b e r in a la b e l, h o w e v e r . If y o u p u t q u o ta tio n m a r k s a r o u n d th e n u m b e r , it b e c o m e s a s tr in g . T h e fo llo w in g s ta te m e n t w ill w o r k :
resultLabel.Text = "5";
C le a r in g a L a b e l
In c o d e , if y o u w a n t to c le a r th e te x t th a t is d is p la y e d in a L a b e l c o n tr o l, s im p ly a s s ig n a n
e m p t y s t r i n g ( "") t o t h e c o n t r o l ’ s T e x t p r o p e r t y , a s s h o w n h e r e :
answerLabel.Text = "";
In T u to r ia l 2 -3 , y o u w ill w o r k w ith s o m e o f th e L a b e l c o n tr o l p r o p e r tie s th a t w e h a v e
d is c u s s e d in th is s e c tio n .
T u t o r ia l 2 -3 :
C r e a t i n g t h e La ngua ge Tra nsla tor A p p l i c a t i o n
VideoNot e
T u to r ia l 2 -3 :
C r e a tin g th e
L anguage
Translator
A p p lic a tio n
In th is tu to r ia l, y o u w ill c r e a te a n a p p lic a tio n th a t d is p la y s th e p h r a s e “ G o o d M o r n in g ”
in d iffe r e n t la n g u a g e s . T h e fo r m w ill h a v e th r e e b u tto n s : o n e fo r Ita lia n , o n e fo r S p a n is h ,
a n d o n e fo r G e r m a n . W h e n th e u s e r c lic k s a n y o f th e s e b u tto n s , th e tr a n s la te d p h r a s e w ill
a p p e a r in a L a b e l c o n tr o l.
S t e p 1 :
S ta r t V is u a l S tu d io a n d b e g in a n e w W in d o w s F o r m s A p p lic a tio n p r o je c t n a m e d
L anguage Translator.
S t e p 2 :
S e t u p th e a p p lic a tio n ’s fo r m a s s h o w n in F ig u r e 2 -5 9 . N o tic e th a t th e fo r m ’s
T e x t p r o p e r t y i s s e t t o L anguage Translator. T h e f o r m h a s t w o L a b e l c o n t r o l s
a n d th r e e B u tto n c o n tr o ls . T h e n a m e s o f th e c o n tr o ls a r e s h o w n in th e fig u r e . A s
y o u p la c e e a c h o f th e c o n tr o ls o n th e fo r m , r e fe r to T a b le 2 -3 fo r th e r e le v a n t
p r o p e r ty s e ttin g s .
F ig u r e 2 -5 9
T h e L a n g u a g e T r a n s la to r fo r m
instructionLabel
translationLabel
italianButton
S t e p 3 :
spanishButton
germanButton
O n c e y o u h a v e th e fo r m a n d its c o n tr o ls s e t u p , y o u c a n c r e a te th e C lic k
e v e n t h a n d l e r s f o r t h e B u t t o n c o n t r o l s . I n t h e D esigner, d o u b l e - c l i c k t h e
italianButton c o n t r o l . T h i s w i l l o p e n t h e c o d e e d i t o r , a n d y o u w i l l s e e a n
e m p t y e v e n t h a n d l e r n a m e d italianButton_Click. W r i t e t h e f o l l o w i n g s t a t e m e n t in s id e th e e v e n t h a n d le r :
translationLabel.Text = "Buongiorno";
2 .5
T a b le 2 -3
L a b e l C o n tr o ls
C o n t r o l p r o p e r t y s e t t in g s
Co n tro l Name
Co n tro l Typ e
P r o p e r ty S e ttin g s
instructionLabel
Lab el
T e x t : Select a language and I will say Good
M orning.
translationLabel
Lab el
A u to S iz e : F a ls e
B o r d e r S ty le : F ix e d S in g le
F o n t: M ic r o s o ft S a n s S e r if (S ty le : B o ld , S iz e :
1 0 p o in t)
Tex t: (Th e co n ten ts o f th e Tex t p ro p erty
h a v e b e e n e r a s e d .)
T e x tA lig n : M id d le C e n te r
italianButton
Bu tto n
T e x t : I talian
spanishButton
Bu tto n
T e x t : Spanish
germanButton
Bu tto n
T e x t : German
S t e p 4 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e spanishButton
c o n tr o l. In th e c o d e e d ito r y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
spanishButton_Click. W r i t e t h e f o l l o w i n g s t a t e m e n t i n s i d e t h e e v e n t h a n d l e r :
translationLabel.Text = "Buenos Dias";
S t e p 5 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e germanButton
c o n tr o l. In th e c o d e e d ito r y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
germanButton_Click. W r i t e t h e f o l l o w i n g s t a t e m e n t i n s i d e t h e e v e n t h a n d l e r :
translationLabel.Text = "Guten Morgen";
S t e p 6 :
T h e fo r m ’s c o d e s h o u ld n o w a p p e a r a s s h o w n in P r o g r a m 2 -1 . N o te th a t th e lin e
n u m b e r s a r e n o t p a r t o f th e c o d e . T h e lin e n u m b e r s a r e s h o w n s o th a t y o u a n d
y o u r in s tr u c to r c a n m o r e e a s ily r e fe r to d iffe r e n t p a r ts o f th e p r o g r a m . T h e lin e s
th a t a p p e a r in b o ld fa c e a r e th e o n e s th a t y o u ty p e d . M a k e s u r e th e c o d e y o u
ty p e d a p p e a r s e x a c tly a s s h o w n h e r e . (D o n ’t fo r g e t th e s e m ic o lo n s !)
P r o g r a m 2 -1
C o m p l e t e d F o r m 1 c o d e f o r t h e La ngua ge Tra nsla tor a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Language_Translator
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
87
88
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
}
35 }
S t e p 7 :
private void italianButton_Click(object sender, EventArgs e)
{
translationLabel.Text = "Buongiorno";
}
private void spanishButton_Click(object sender, EventArgs e)
{
translationLabel.Text = "Buenos Dias";
}
private void germanButton_Click(object sender, EventArgs e)
{
translationLabel.Text = "Guten Morgen";
}
S a v e th e p r o je c t. T h e n , p r e s s th e
k e y o n t h e k e y b o a r d o r c l i c k t h e Start
D ebugging b u t t o n ( ) o n t h e t o o l b a r t o c o m p i l e a n d r u n t h e a p p l i c a t i o n .
N O T E : If y o u ty p e d th e s ta te m e n ts c o r r e c tly in s id e th e e v e n t h a n d le r s , th e
a p p lic a tio n s h o u ld r u n . If y o u d id n o t ty p e th e s ta te m e n ts c o r r e c tly in s id e th e
e v e n t h a n d le r s , a w in d o w w ill a p p e a r r e p o r tin g b u ild e r r o r s . If th a t h a p p e n s ,
c l i c k t h e No b u t t o n i n t h e w i n d o w a n d t h e n c o r r e c t t h e c o d e s o i t a p p e a r s
e x a c tly a s p r e v io u s ly s h o w n .
F ig u r e 2 -6 0 s h o w s th e a p p lic a tio n ’s fo r m w h e n it s ta r ts r u n n in g a n d a fte r y o u h a v e
c lic k e d e a c h o f th e B u tto n c o n tr o ls . A fte r y o u h a v e te s te d e a c h b u tto n , c lo s e th e a p p lic a tio n ’s fo r m .
F ig u r e 2 -6 0
T h e La ngua ge Tra nsla tor a p p l i c a t i o n r u n n i n g
2 .6
M a k in g S e n s e o f In t e lliS e n s e
C h e c k p o in t
2 .6
2 .2 9
I n w h i c h g r o u p o f t h e Toolbox c a n y o u f i n d t h e L a b e l c o n t r o l t o o l ?
2 .3 0
O n c e y o u h a v e p la c e d a L a b e l c o n tr o l o n a fo r m , w h ic h p r o p e r ty d o y o u u s e to s e t
th e te x t th a t y o u w a n t to d is p la y ?
2 .3 1
W h a t p r o p e r ty c a n y o u u s e to c h a n g e th e a p p e a r a n c e o f a L a b e l c o n tr o l’s te x t?
2 .3 2
W h a t is th e d e fa u lt v a lu e o f a la b e l’s B o r d e r S ty le p r o p e r ty ?
2 .3 3
H o w d o y o u
w in d o w ?
2 .3 4
W h a t p r o p e r ty d e te r m in e s w h e th e r a la b e l c a n b e r e s iz e d ?
2 .3 5
W h a t p r o p e r ty d e te r m in e s th e w a y te x t is a lig n e d in a L a b e l c o n tr o l?
2 .3 6
H o w c a n y o u u s e a L a b e l c o n tr o l to d is p la y o u tp u t w h ile a p r o g r a m is r u n n in g ?
2 .3 7
W h a t h a p p e n s if y o u a s s ig n a n e m p ty s tr in g to a c o n tr o l’s T e x t p r o p e r ty in c o d e ?
c h a n g e th e B o r d e r S ty le p r o p e r ty o f a c o n tr o l in
t h e Properties
M a k in g S e n s e o f In t e lliS e n s e
C O N C E P T :
A s y o u ty p e c o d e in th e Vis u a l S tu d io c o d e e d ito r, In te lliS e n s e b o x e s p o p
u p to a s s is t y o u . Yo u c a n u s e th e In te lliS e n s e b o x e s to a u to m a tic a lly
c o m p le te s o m e p r o g r a m m in g s ta te m e n ts a fte r ty p in g o n ly th e fir s t fe w
ch aracters.
In te lliS e n s e is a fe a tu r e o f V is u a l S tu d io th a t p r o v id e s a u to m a tic c o d e c o m p le tio n a s y o u
w r ite p r o g r a m m in g s ta te m e n ts . O n c e y o u le a r n h o w to u s e In te lliS e n s e , it h e lp s y o u w r ite
c o d e fa s te r . If y o u ’v e w o r k e d th r o u g h th e p r e v io u s tu to r ia ls in th is c h a p te r , y o u ’v e a lr e a d y
e n c o u n te r e d In te lliS e n s e . F o r e x a m p le , in S te p 3 o f T u to r ia l 2 -3 , y o u w e r e in s tr u c te d to
w r i t e t h e f o l l o w i n g s t a t e m e n t i n t h e italianButton_Click e v e n t h a n d l e r :
translationLabel.Text = "Buongiorno";
D id y o u n o tic e th a t a s s o o n a s y o u s ta r te d ty p in g th e s ta te m e n t, a b o x p o p p e d u p o n th e
s c r e e n ? T h is is k n o w n a s a n In te lliS e n s e lis t b o x . T h e c o n te n ts o f th e lis t b o x c h a n g e s a s y o u
t y p e . F i g u r e 2 - 6 1 s h o w s t h e I n t e l l i S e n s e l i s t b o x a f t e r y o u h a v e t y p e d t h e c h a r a c t e r s tra.
F ig u r e 2 -6 1
In t e lliS e n s e lis t b o x d is p la y e d
89
90
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
T h e In te lliS e n s e s y s te m is a n tic ip a tin g w h a t y o u a r e a b o u t to ty p e , a n d a s y o u ty p e c h a r a c te r s , th e c o n te n t o f th e lis t b o x is r e d u c e d . T h e lis t b o x s h o w n in F ig u r e 2 -6 1 s h o w s a ll
t h e n a m e s s t a r t i n g w i t h tra t h a t m i g h t b e a c a n d i d a t e f o r t h e s t a t e m e n t y o u a r e t y p i n g .
N o t i c e t h a t translationLabel i s s e l e c t e d i n t h e l i s t b o x . W i t h t h a t i t e m s e l e c t e d , y o u
can p ress th e
k e y o n t h e k e y b o a r d , a n d t h e tra t h a t y o u p r e v i o u s l y t y p e d b e c o m e s
translationLabel.
N e x t, w h e n y o u ty p e a p e r io d , a n In te lliS e n s e lis t p o p s u p s h o w in g e v e r y p r o p e r ty a n d
m e t h o d b e l o n g i n g t o t h e translationLabel c o n t r o l . T y p e te a n d t h e T e x t p r o p e r t y
b e c o m e s s e le c te d , a s s h o w n in F ig u r e 2 -6 2 . W h e n y o u p r e s s th e
k e y to s e le c t th e T e x t
p r o p e r t y , y o u r s t a t e m e n t a u t o m a t i c a l l y b e c o m e s translationLabel.Text. A t t h i s p o i n t ,
y o u c a n c o n tin u e ty p in g u n til y o u h a v e c o m p le te d th e s ta te m e n t.
F ig u r e 2 -6 2
In t e lliS e n s e lis t b o x a ft e r t y p in g “ .t e ”
N o w th a t y o u h a v e a n id e a o f h o w In te lliS e n s e w o r k s , y o u a r e e n c o u r a g e d to
e x p e r im e n t w ith it a s y o u w r ite c o d e in fu tu r e p r o je c ts . W ith a little p r a c tic e , it w ill
b e c o m e in tu itiv e .
2 .7
P ic t u r e B o x C o n t r o ls
C O N C E P T :
A P ic tu r e B o x c o n tr o l d is p la y s a g r a p h ic im a g e o n a fo r m . P ic tu r e B o x
c o n tr o ls h a v e p r o p e r tie s fo r c o n tr o llin g th e w a y th e im a g e is d is p la y e d . A
P ic tu r e B o x c o n tr o l c a n h a v e a C lic k e v e n t h a n d le r th a t r e s p o n d s w h e n th e
u s e r c lic k s th e c o n tr o l a t r u n tim e .
Y o u c a n u s e a P ic tu r e B o x c o n tr o l to d is p la y a g r a p h ic im a g e o n a fo r m . A P ic tu r e B o x
c o n tr o l c a n d is p la y im a g e s th a t h a v e b e e n s a v e d in th e b itm a p , G IF , J P E G , m e ta file , o r
ic o n g r a p h ic s fo r m a ts .
I n t h e Toolbox, t h e P i c t u r e B o x t o o l i s l o c a t e d i n t h e Common Controls g r o u p . W h e n
y o u d o u b le -c lic k th e to o l, a n e m p ty P ic tu r e B o x c o n tr o l is c r e a te d o n th e fo r m , a s s h o w n
in F ig u r e 2 -6 3 . A lth o u g h th e c o n tr o l d o e s n o t y e t d is p la y a n im a g e , it h a s a b o u n d in g
b o x th a t s h o w s its s iz e a n d lo c a tio n , a s w e ll a s s iz in g h a n d le s . W h e n y o u c r e a te
P i c t u r e B o x c o n t r o l s , t h e y a r e a u t o m a t i c a l l y g i v e n d e f a u l t n a m e s s u c h a s pictureBox1,
pictureBox2, a n d s o f o r t h . Y o u s h o u l d a l w a y s c h a n g e t h e d e f a u l t n a m e t o s o m e t h i n g
m o r e m e a n in g fu l.
2 .7
F ig u r e 2 -6 3
P ic t u r e B o x C o n t r o ls
A n e m p t y P ic t u r e B o x c o n t r o l
O n c e y o u h a v e c r e a te d a P ic tu r e B o x c o n tr o l, y o u u s e its Im a g e p r o p e r ty to s p e c ify th e
im a g e th a t it w ill d is p la y . F o llo w th e s e s te p s :
Step 1 :
Step 2 :
F ig u r e 2 -6 4
C l i c k t h e I m a g e p r o p e r t y i n t h e Properties w i n d o w . A n e l l i p s e s b u t t o n ( ) w i l l
a p p e a r, a s s h o w n o n th e le ft in F ig u r e 2 -6 4 .
C l i c k t h e e l l i p s e s b u t t o n a n d t h e Select Resource w i n d o w , s h o w n o n t h e r i g h t
in F ig u r e 2 -6 4 , w ill a p p e a r.
T h e I m a g e p r o p e r t y ’ s Select Resource w i n d o w
Step 3 :
Step 4 :
Step 5 :
I n t h e Select Resource w i n d o w , c l i c k t h e I mport b u t t o n . A n O pen d i a l o g b o x
w i l l a p p e a r . U s e t h e d i a l o g b o x t o l o c a t e a n d s e l e c t t h e i m a g e fi l e t h a t y o u
w a n t to d is p la y .
A f t e r y o u s e l e c t a n i m a g e fi l e , y o u w i l l s e e i t s c o n t e n t s d i s p l a y e d i n t h e Select
Resource w i n d o w . T h i s i n d i c a t e s t h a t t h e i m a g e h a s b e e n i m p o r t e d i n t o t h e
p r o j e c t . F i g u r e 2 - 6 5 s h o w s a n e x a m p l e o f t h e Select Resource w i n d o w a f t e r
w e h a v e s e le c te d a n d im p o r te d a n im a g e .
C l i c k t h e O K b u t t o n i n t h e Select Resource w i n d o w , a n d t h e s e l e c t e d i m a g e w ill a p p e a r in th e P ic tu r e B o x c o n tr o l. F ig u r e 2 -6 6 s h o w s a n e x a m p le .
D e p e n d in g o n th e s iz e o f th e im a g e , y o u m ig h t s e e o n ly p a r t o f it d is p la y e d .
T h is is th e c a s e in F ig u r e 2 -6 6 b e c a u s e th e im a g e is la r g e r th a n th e P ic tu r e B o x
c o n tr o l. Yo u r n e x t s te p is to s e t th e S iz e M o d e p r o p e r ty a n d a d ju s t th e s iz e o f
th e c o n tr o l.
91
92
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
F ig u r e 2 -6 5
A n im a g e s e le c t e d a n d im p o r t e d
F ig u r e 2 -6 6
T h e im a g e d is p la y e d in t h e P ic t u r e B o x c o n t r o l
T h e S iz e M o d e P r o p e r t y
T h e P ic tu r e B o x c o n tr o l’s S iz e M o d e p r o p e r ty s p e c ifie s h o w th e c o n tr o l’s im a g e is to b e
d is p la y e d . It c a n b e s e t to o n e o f th e fo llo w in g v a lu e s :
• No rmal
N o r m a l is th e d e fa u lt v a lu e . T h e im a g e w ill b e p o s itio n e d in th e u p p e r -le ft c o r n e r o f
th e P ic tu r e B o x c o n tr o l. If th e im a g e is to o b ig to fit in th e P ic tu r e B o x c o n tr o l, it w ill
b e c lip p e d .
• Stretch Image
S tr e tc h Im a g e r e s iz e s th e im a g e b o th h o r iz o n ta lly a n d v e r tic a lly to fit in th e P ic tu r e B o x c o n tr o l. If th e im a g e is r e s iz e d m o r e in o n e d ir e c tio n th a n th e o th e r , it w ill
ap p ear stretch ed .
2 .7
P ic t u r e B o x C o n t r o ls
• A u to S iz e
W ith A u to S iz e , th e P ic tu r e B o x c o n tr o l is a u to m a tic a lly r e s iz e d to fit th e s iz e o f th e im a g e .
• Cen terImage
C e n te r Im a g e c e n te r s th e im a g e in th e P ic tu r e B o x c o n tr o l w ith o u t r e s iz in g it.
• Zo o m
Z o o m u n ifo r m ly r e s iz e s th e im a g e to fit in th e P ic tu r e B o x w ith o u t lo s in g its o r ig in a l
a s p e c t r a tio . (A s p e c t r a tio is th e im a g e ’s w id th to h e ig h t r a tio .) T h is c a u s e s th e im a g e
to b e r e s iz e d w ith o u t a p p e a r in g s tr e tc h e d .
F ig u r e 2 -6 7 s h o w s a n e x a m p le o f a n im a g e d is p la y e d in a P ic tu r e B o x c o n tr o l. T h e c o n tr o l’s S iz e M o d e is s e t to Z o o m , s o it c a n b e r e s iz e d w ith o u t a p p e a r in g s tr e tc h e d .
F ig u r e 2 -6 7
A n im a g e r e s iz e d w it h S iz e M o d e s e t t o Z o o m
N O T E : P ic tu r e B o x c o n tr o ls a ls o h a v e a B o r d e r S ty le p r o p e r ty th a t w o r k s ju s t lik e a
L a b e l c o n tr o l’s B o r d e r S ty le p r o p e r ty .
C r e a t in g C lic k a b le Im a g e s
B u tto n s a r e n ’t th e o n ly c o n tr o ls th a t c a n r e s p o n d to C lic k e v e n ts . P ic tu r e B o x c o n tr o ls
c a n , to o . T h a t m e a n s a n a p p lic a tio n c a n d is p la y a n im a g e a n d p e r fo r m s o m e a c tio n w h e n
th e u s e r c lic k s th e im a g e .
T o m a k e a n im a g e c lic k a b le , y o u s im p ly h a v e to c r e a te a C lic k e v e n t h a n d le r fo r th e
P ic tu r e B o x c o n tr o l th a t d is p la y s th e im a g e . Y o u c r e a te a C lic k e v e n t h a n d le r fo r a P ic tu r e B o x
c o n tr o l in th e s a m e w a y th a t y o u c r e a te a C lic k e v e n t h a n d le r fo r a B u tto n c o n tr o l:
• Y o u d o u b l e - c l i c k t h e P i c t u r e B o x c o n t r o l i n t h e D esigner. T h i s c r e a t e s a n e m p t y
C lic k e v e n t h a n d le r in th e fo r m ’s s o u r c e c o d e file .
• In th e c o d e e d ito r y o u w r ite s ta te m e n ts in s id e th e e v e n t h a n d le r th a t y o u w a n t to
e x e c u te w h e n th e im a g e is c lic k e d .
A s a n e x a m p l e , l o o k a t t h e Cat p r o j e c t t h a t i s i n t h e Chap02 f o l d e r o f t h e S t u d e n t S a m p l e
P r o g r a m s th a t a c c o m p a n y th is te x tb o o k . F ig u r e 2 -6 8 s h o w s th e a p p lic a tio n ’s fo r m . T h e
P i c t u r e B o x c o n t r o l ’ s n a m e i s catPictureBox. I t s i m a g e i s t h e C a t . j p g f i l e , w h i c h i s a l s o
f o u n d i n t h e Chap02 f o l d e r o f t h e S t u d e n t S a m p l e P r o g r a m s . T h e S i z e M o d e p r o p e r t y i s
s e t to Z o o m , a n d th e B o r d e r S ty le p r o p e r ty is s e t to F ix e d S in g le .
93
94
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
F ig u r e 2 -6 8
T h e C a t fo rm
O p e n th e F o r m 1 .c s file in th e c o d e e d ito r a n d y o u w ill s e e th a t w e h a v e a lr e a d y c r e a te d a
C l i c k e v e n t h a n d l e r f o r t h e catPictureBox c o n t r o l , a s s h o w n i n F i g u r e 2 - 6 9 . I f y o u r u n t h e
a p p l i c a t i o n a n d c l i c k t h e P i c t u r e B o x , a m e s s a g e b o x w i l l a p p e a r d i s p l a y i n g t h e s t r i n g M eow.
F ig u r e 2 -6 9
C o d e f o r t h e Ca t p r o j e c t ’ s F o r m 1 . c s f i l e
T u to r ia l 2 -4 g iv e s y o u a c h a n c e to p r a c tic e u s in g P ic tu r e B o x c o n tr o ls . In th e tu to r ia l, y o u
w ill c r e a te a n a p p lic a tio n w ith th r e e c lic k a b le P ic tu r e B o x c o n tr o ls , d is p la y in g im a g e s th a t
a r e p r o v id e d in th e S tu d e n t S a m p le P r o g r a m file s th a t a c c o m p a n y th is b o o k .
T u t o r ia l 2 -4 :
C r e a t i n g t h e Fla gs A p p l i c a t i o n
VideoNot e
T u to r ia l 2 -4 :
C r e a tin g th e
Flags
A p p lic a tio n
In th is tu to r ia l, y o u w ill c r e a te a n a p p lic a tio n th a t d is p la y s th e fla g s o f F in la n d , F r a n c e ,
a n d G e r m a n y in P ic tu r e B o x c o n tr o ls . W h e n th e u s e r c lic k s a n y o f th e s e P ic tu r e B o x e s , th e
n a m e o f th a t fla g ’s c o u n tr y w ill a p p e a r in a L a b e l c o n tr o l.
S t e p 1 :
S ta r t V is u a l S tu d io
n a m e d Flags.
a n d
b e g in
a n e w W in d o w s F o r m s A p p lic a tio n
p r o je c t
2 .7
S t e p 2 :
P ic t u r e B o x C o n t r o ls
S e t u p th e a p p lic a tio n ’s fo r m a s s h o w n in F ig u r e 2 -7 0 . N o tic e th a t th e fo r m ’s
T e x t p r o p e r t y i s s e t t o Flags. T h e n a m e s o f t h e c o n t r o l s a r e s h o w n i n t h e f i g u r e .
R e fe r to T a b le 2 -4 fo r e a c h c o n tr o l’s r e le v a n t p r o p e r ty s e ttin g s .
F ig u r e 2 -7 0
T h e F la g s fo r m
instructionLabel
germanyPictureBox
finlandPictureBox
francePictureBox
countryLabel
T a b le 2 -4
C o n t r o l p r o p e r t y s e t t in g s
Co n tro l Name
Co n tro l Typ e
P r o p e r ty S e ttin g s
instructionLabel
Lab el
T e x t : Click a flag to see the name of the country.
finlandPictureBox
P ic tu r e B o x
Im a g e : S e le c t a n d im p o r t th e F in la n d .b m p file
f r o m t h e Chap02 f o l d e r o f t h e S t u d e n t
S a m p le P r o g r a m s .
B o r d e r S ty le : F ix e d S in g le
S iz e M o d e : A u to S iz e
francePictureBox
P ic tu r e B o x
Im a g e : S e le c t a n d im p o r t th e F r a n c e .b m p file
f r o m t h e Chap02 f o l d e r o f t h e S t u d e n t
S a m p le P r o g r a m s .
B o r d e r S ty le : F ix e d S in g le
S iz e M o d e : A u to S iz e
germanyPictureBox
P ic tu r e B o x
Im a g e : S e le c t a n d im p o r t th e G e r m a n y .b m p
f i l e f r o m t h e Chap02 f o l d e r o f t h e S t u d e n t
S a m p le P r o g r a m s .
B o r d e r S ty le : F ix e d S in g le
S iz e M o d e : A u to S iz e
countryLabel
Lab el
A u to S iz e : F a ls e
B o r d e r S ty le : F ix e d S in g le
F o n t: M ic r o s o ft S a n s S e r if (S ty le : B o ld , S iz e :
1 0 p o in t)
Tex t: (Th e co n ten ts o f th e Tex t p ro p erty h ave
b e e n e r a s e d .)
T e x tA lig n : M id d le C e n te r
S t e p 3 :
O n c e y o u h a v e th e fo r m a n d its c o n tr o ls s e t u p , y o u c a n c r e a te th e C lic k e v e n t
h a n d l e r s f o r t h e P i c t u r e B o x c o n t r o l s . I n t h e D esigner, d o u b l e - c l i c k t h e
finlandPictureBox c o n t r o l . T h i s w i l l o p e n t h e c o d e e d i t o r , a n d y o u w i l l s e e
a n e m p t y e v e n t h a n d l e r n a m e d finlandPictureBox_Click. W r i t e t h e f o l l o w in g s ta te m e n t in s id e th e e v e n t h a n d le r :
countryLabel.Text = "Finland";
95
96
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
S t e p 4 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e francePictureBox c o n t r o l . T h i s w i l l o p e n t h e c o d e e d i t o r , a n d y o u w i l l s e e a n e m p t y e v e n t
h a n d l e r n a m e d francePictureBox_Click . W r i t e t h e f o l l o w i n g s t a t e m e n t
in s id e th e e v e n t h a n d le r :
countryLabel.Text = "France";
S t e p 5 .
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e germanyPictureBox c o n t r o l . T h i s w i l l o p e n t h e c o d e e d i t o r , a n d y o u w i l l s e e a n e m p t y e v e n t
h a n d l e r n a m e d germanyPictureBox_Click. W r i t e t h e f o l l o w i n g s t a t e m e n t
in s id e th e e v e n t h a n d le r :
countryLabel.Text = "Germany";
S t e p 6 :
T h e fo r m ’s c o d e s h o u ld n o w a p p e a r a s s h o w n in P r o g r a m 2 -2 . A s w a s m e n tio n e d in th e p r e v io u s tu to r ia l, th e lin e n u m b e r s a r e s h o w n fo r r e fe r e n c e o n ly ,
a n d a r e n o t p a r t o f th e c o d e . T h e lin e s th a t a p p e a r in b o ld fa c e a r e th e o n e s th a t
y o u ty p e d . M a k e s u r e th e c o d e y o u ty p e d a p p e a r s e x a c tly a s s h o w n h e r e . (D o n ’t
fo r g e t th e s e m ic o lo n s !)
P r o g r a m 2 -2
C o m p l e t e d F o r m 1 c o d e f o r t h e Fla gs a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Flags
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void finlandPictureBox_Click(object sender, EventArgs e)
21
{
22
countryLabel.Text = "Finland";
23
}
24
25
private void francePictureBox_Click(object sender, EventArgs e)
26
{
27
countryLabel.Text = "France";
28
}
29
30
private void germanyPictureBox_Click(object sender, EventArgs e)
31
{
32
countryLabel.Text = "Germany";
33
}
34
}
35 }
2 .7
S t e p 7 :
P ic t u r e B o x C o n t r o ls
S a v e th e p r o je c t. T h e n , p r e s s th e
k e y o n t h e k e y b o a r d , o r c l i c k t h e Start
D ebugging b u t t o n ( ) o n t h e t o o l b a r t o c o m p i l e a n d r u n t h e a p p l i c a t i o n .
N O T E : If y o u ty p e d th e s ta te m e n ts c o r r e c tly in s id e th e e v e n t h a n d le r s , th e
a p p lic a tio n s h o u ld r u n . If y o u d id n o t ty p e th e s ta te m e n ts in s id e th e e v e n t h a n d le r s c o r r e c tly , a w in d o w w ill a p p e a r r e p o r tin g b u ild e r r o r s . If th a t h a p p e n s ,
c l i c k t h e No b u t t o n i n t h e w i n d o w , t h e n c o r r e c t t h e c o d e s o i t a p p e a r s e x a c t l y
a s p r e v io u s ly s h o w n .
F ig u r e 2 -7 1 s h o w s th e a p p lic a tio n ’s fo r m w h e n it s ta r ts r u n n in g a n d th e n a fte r
y o u h a v e c lic k e d e a c h o f th e P ic tu r e B o x c o n tr o ls . A fte r y o u h a v e c lic k e d e a c h
fla g to m a k e s u r e th e a p p lic a tio n w o r k s c o r r e c tly , c lo s e th e fo r m .
F ig u r e 2 -7 1
T h e Fla gs a p p l i c a t i o n r u n n i n g
T h e V is ib le P r o p e r t y
M o s t c o n tr o ls h a v e a V is ib le p r o p e r ty th a t d e te r m in e s w h e th e r th e c o n tr o l is v is ib le o n th e
fo r m a t r u n tim e . T h e V is ib le p r o p e r ty is a B o o le a n p r o p e r ty , w h ic h m e a n s it c a n b e s e t o n ly
to th e v a lu e s T r u e o r F a ls e . If a c o n tr o l’s V is ib le p r o p e r ty is s e t to T r u e , th e c o n tr o l w ill b e
v is ib le o n th e fo r m a t r u n tim e . If a c o n tr o l’s V is ib le p r o p e r ty is s e t to F a ls e , h o w e v e r , th e
c o n tr o l w ill n o t b e v is ib le a t r u n tim e . B y d e fa u lt, th e V is ib le p r o p e r ty is s e t to T r u e .
W h e n y o u u s e t h e Properties w i n d o w t o c h a n g e a c o n t r o l ’ s V i s i b l e p r o p e r t y a t d e s i g n
t i m e , t h e c o n t r o l w i l l s t i l l b e v i s i b l e i n t h e D esigner. W h e n y o u r u n t h e a p p l i c a t i o n , h o w e v e r , th e c o n tr o l w ill n o t b e v is ib le o n th e fo r m . F o r e x a m p le , th e im a g e o n th e le ft in
F i g u r e 2 - 7 2 s h o w s a f o r m i n t h e D esigner. T h e P i c t u r e B o x c o n t r o l ’ s V i s i b l e p r o p e r t y i s s e t
t o F a l s e , b u t t h e c o n t r o l c a n s t i l l b e s e e n i n t h e D esigner. T h e i m a g e o n t h e r i g h t s h o w s t h e
fo r m w h ile th e a p p lic a tio n is r u n n in g . A t r u n tim e , th e c o n tr o l is n o t v is ib le .
A c o n tr o l’s V is ib le p r o p e r ty c a n a ls o b e m o d ifie d in c o d e b y a n a s s ig n m e n t s ta te m e n t,
w h ic h m a k e s it p o s s ib le to h id e o r d is p la y a c o n tr o l w h ile th e a p p lic a tio n is r u n n in g . F o r
e x a m p l e , t h e P i c t u r e B o x c o n t r o l s h o w n i n F i g u r e 2 - 7 2 i s n a m e d spiderPictureBox. T h e
f o l l o w i n g s t a t e m e n t s e t s t h e c o n t r o l ’ s V i s i b l e p r o p e r t y t o true:
spiderPictureBox.Visible = true;
97
98
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
F ig u r e 2 -7 2
A P ic t u r e B o x c o n t r o l w it h it s V is ib le p r o p e r t y s e t t o F a ls e
The form in the Designer
The form at run time
The Visible property is set to False.
W h e n t h i s s t a t e m e n t e x e c u t e s , t h e spiderPictureBox c o n t r o l w i l l b e c o m e v i s i b l e . L i k e w i s e , t h e f o l l o w i n g s t a t e m e n t s e t s t h e c o n t r o l ’ s V i s i b l e p r o p e r t y t o false:
spiderPictureBox.Visible = false;
W h e n t h i s s t a t e m e n t e x e c u t e s , t h e spiderPictureBox c o n t r o l w i l l b e c o m e i n v i s i b l e .
N O T E : W h e n y o u w r i t e t h e v a l u e s true a n d false i n c o d e , a s s h o w n i n t h e p r e v i o u s a s s ig n m e n t s ta te m e n t, th e y m u s t b e w r itte n in a ll lo w e r c a s e le tte r s . T h e w o r d s
true a n d false a r e C # k e y w o r d s , a n d a n e r r o r w i l l o c c u r i f y o u d o n ’ t w r i t e t h e m i n
l o w e r c a s e . H o w e v e r , w h e n y o u u s e t h e Properties w i n d o w t o s e t a B o o l e a n p r o p e r t y ,
s u c h a s V is ib le , th e v a lu e s T r u e a n d F a ls e w ill b e s h o w n w ith a n in itia l c a p ita l. T r y
n o t to le t th is in c o n s is te n c y c o n fu s e y o u !
In T u to r ia l 2 -5 , y o u w ill c r e a te a n a p p lic a tio n th a t u s e s th e V is ib le p r o p e r ty o f tw o
P ic tu r e B o x c o n tr o ls to s im u la te a c a r d b e in g flip p e d o v e r .
T u t o r ia l 2 -5 :
C r e a t i n g t h e Ca rd Flip A p p l i c a t i o n
VideoNot e
T u to r ia l 2 -5 :
C r e a tin g th e
Card Flip
A p p lic a tio n
In th is tu to r ia l, y o u w ill c r e a te a n a p p lic a tio n th a t s im u la te s a c a r d b e in g flip p e d o v e r .
W h e n th e a p p lic a tio n r u n s , it w ill d is p la y th e fo r m s h o w n o n th e le ft in F ig u r e 2 -7 3 . T h e
f o r m i n i t i a l l y d i s p l a y s t h e b a c k o f a p o k e r c a r d . W h e n t h e u s e r c l i c k s t h e Show the Card
Face b u t t o n , t h e c a r d w i l l b e f l i p p e d o v e r t o s h o w i t s f a c e , a s s h o w n i n t h e f o r m o n t h e
r i g h t . W h e n t h e u s e r c l i c k s t h e Show the Card Back b u t t o n , t h e c a r d i s f l i p p e d b a c k o v e r
to s h o w its b a c k .
2 .7
P ic t u r e B o x C o n t r o ls
T h e s im u la tio n o f th e c a r d b e in g flip p e d w ill b e a c c o m p lis h e d u s in g th e fo llo w in g lo g ic :
• W h e n t h e u s e r c l i c k s t h e Show the Card Face b u t t o n , t h e P i c t u r e B o x s h o w i n g t h e
c a r d ’s b a c k w i l l b e m a d e i n v i s i b l e a n d t h e P i c t u r e B o x s h o w i n g t h e c a r d ’s f a c e w i l l
b e m a d e v is ib le .
• W h e n t h e u s e r c l i c k s t h e Show the Card Back b u t t o n , t h e P i c t u r e B o x s h o w i n g t h e
c a r d ’s f a c e w i l l b e m a d e i n v i s i b l e a n d t h e P i c t u r e B o x s h o w i n g t h e c a r d ’s b a c k w i l l
b e m a d e v is ib le .
F ig u r e 2 -7 3
T h e Ca rd Flip a p p l i c a t i o n
S t e p 1 :
S ta r t V is u a l S tu d io
n a m e d Card Flip.
S t e p 2 :
S e t u p th e a p p lic a tio n ’s fo r m a s s h o w n in F ig u r e 2 -7 4 . N o tic e th a t th e fo r m ’s T e x t
p r o p e r t y i s s e t t o Card Flip. T h e n a m e s o f t h e c o n t r o l s a r e s h o w n i n t h e f i g u r e .
U s e t h e Properties w i n d o w t o m a k e t h e p r o p e r t y s e t t i n g s s h o w n i n T a b l e 2 - 5 . ( I n
p a r t i c u l a r , n o t e t h a t t h e cardBackPictureBox c o n t r o l ’ s V i s i b l e p r o p e r t y i s s e t t o
T r u e , a n d t h e cardFacePictureBox c o n t r o l ’ s V i s i b l e p r o p e r t y i s s e t t o F a l s e . )
F ig u r e 2 -7 4
a n d
b e g in
a n e w W in d o w s F o r m s A p p lic a tio n
p r o je c t
T h e C a r d F lip fo r m
cardBackPictureBox
cardFacePictureBox
showBackButton
showFaceButton
99
100
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
T a b le 2 -5
C o n t r o l p r o p e r t y s e t t in g s
Co n tro l Name
Co n tro l Typ e
P r o p e r ty S e ttin g s
cardBackPictureBox
P ic tu r e B o x
Im a g e : S e le c t a n d im p o r t th e B a c k fa c e _
B l u e . j p g f i l e f r o m t h e Chap02 f o l d e r o f t h e
S tu d e n t S a m p le P r o g r a m s .
S iz e : 1 0 0 , 1 4 0
S iz e M o d e : Z o o m
V is ib le : T r u e
cardFacePictureBox
P ic tu r e B o x
Im a g e : S e le c t a n d im p o r t th e A c e _ S p a d e s .
j p g f i l e f r o m t h e Chap02 f o l d e r o f t h e
S tu d e n t S a m p le P r o g r a m s .
S iz e : 1 0 0 , 1 4 0
S iz e M o d e : Z o o m
V is ib le : F a ls e
showBackButton
Bu tto n
T e x t : Show the Card Back
(M a n u a lly r e s iz e th e b u tto n to
a c c o m m o d a te th e te x t, a s s h o w n in
F ig u r e 2 -7 4 .)
showFaceButton
Bu tto n
T e x t : Show the Card Face ( M a n u a l l y
r e s iz e th e b u tto n to a c c o m m o d a te th e te x t,
a s s h o w n in F ig u r e 2 -7 4 .)
S t e p 3 :
O n c e y o u h a v e th e fo r m a n d its c o n tr o ls s e t u p , y o u c a n c r e a te th e C lic k
e v e n t h a n d l e r s f o r t h e B u t t o n c o n t r o l s . I n t h e D esigner, d o u b l e - c l i c k t h e
showBackButton c o n t r o l . T h i s w i l l o p e n t h e c o d e e d i t o r , a n d y o u w i l l s e e a n
e m p t y e v e n t h a n d l e r n a m e d showBackButton_Click . W r i t e t h e f o l l o w i n g
s ta te m e n ts in s id e th e e v e n t h a n d le r :
cardBackPictureBox.Visible = true;
cardFacePictureBox.Visible = false;
S t e p 4 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e showFaceButton
c o n tr o l. T h is w ill o p e n th e c o d e e d ito r , a n d y o u w ill s e e a n e m p ty e v e n t h a n d le r
n a m e d showFaceButton_Click. W r i t e t h e f o l l o w i n g s t a t e m e n t s i n s i d e t h e
e v e n t h a n d le r :
cardBackPictureBox.Visible = false;
cardFacePictureBox.Visible = true;
S t e p 5 :
T h e fo r m ’s c o d e s h o u ld n o w a p p e a r a s s h o w n in P r o g r a m 2 -3 . R e m e m b e r , th e
lin e n u m b e r s a r e s h o w n fo r r e fe r e n c e o n ly a n d a r e n o t p a r t o f th e c o d e . T h e
lin e s th a t a p p e a r in b o ld fa c e a r e th e o n e s th a t y o u ty p e d . M a k e s u r e th e c o d e
y o u ty p e d a p p e a r s e x a c tly a s s h o w n h e r e . (D o n ’t fo r g e t th e s e m ic o lo n s !)
P r o g r a m 2 -3
C o m p l e t e d F o r m 1 c o d e f o r t h e Ca rd Flip a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
2 .7
P ic t u r e B o x C o n t r o ls
9 using System.Windows.Forms;
10
11 namespace Card_Flip
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void showBackButton_Click(object sender, EventArgs e)
21
{
22
cardBackPictureBox.Visible = true;
23
cardFacePictureBox.Visible = false;
24
}
25
26
private void showFaceButton_Click(object sender, EventArgs e)
27
{
28
cardBackPictureBox.Visible = false;
29
cardFacePictureBox.Visible = true;
30
}
31
}
32 }
S t e p 6 :
S a v e th e p r o je c t. T h e n , p r e s s th e
k e y o n t h e k e y b o a r d , o r c l i c k t h e Start
D ebugging b u t t o n ( ) o n t h e t o o l b a r t o c o m p i l e a n d r u n t h e a p p l i c a t i o n .
T e s t t h e a p p l i c a t i o n b y c l i c k i n g t h e b u t t o n s . W h e n y o u c l i c k t h e Show the Card
Face b u t t o n y o u s h o u l d s e e t h e c a r d ’ s f a c e ( a n d t h e b a c k o f t h e c a r d s h o u l d b e
i n v i s i b l e ) . W h e n y o u c l i c k t h e Show the Card Back b u t t o n y o u s h o u l d s e e t h e
c a r d ’s b a c k (a n d th e c a r d ’s fa c e s h o u ld b e in v is ib le ). W h e n y o u a r e fin is h e d ,
c lo s e th e a p p lic a tio n .
N O T E : If y o u ty p e d th e s ta te m e n ts c o r r e c tly in s id e th e e v e n t h a n d le r s , th e
a p p lic a tio n s h o u ld r u n . If y o u d id n o t ty p e th e s ta te m e n ts in s id e th e e v e n t h a n d le r s c o r r e c tly , a w in d o w w ill a p p e a r r e p o r tin g b u ild e r r o r s . If th a t h a p p e n s ,
c l i c k t h e No b u t t o n i n t h e w i n d o w a n d t h e n c o r r e c t t h e c o d e s o i t a p p e a r s
e x a c tly a s p r e v io u s ly s h o w n .
N O T E : In a d d itio n to P ic tu r e B o x e s , m a n y o th e r ty p e s o f c o n tr o ls h a v e a V is ib le
p r o p e r ty . F o r e x a m p le , y o u c a n m a k e a L a b e l c o n tr o l v is ib le o r in v is ib le b y s e ttin g th e
v a lu e o f its V is ib le p r o p e r ty .
S e q u e n t ia l E x e c u t io n o f S t a t e m e n t s
In T u to r ia l 2 -5 , th e e v e n t h a n d le r s th a t y o u c r e a te d e a c h c o n ta in e d m o r e th a n o n e s ta te m e n t . F o r e x a m p l e , h e r e i s t h e showBackButton_Click m e t h o d :
private void showBackButton_Click(object sender, EventArgs e)
{
cardBackPictureBox.Visible = true;
cardFacePictureBox.Visible = false;
}
101
102
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
T h is m e th o d h a s tw o a s s ig n m e n t s ta te m e n ts . W h e n th e m e th o d e x e c u te s , th e s ta te m e n ts
in th e m e th o d e x e c u te in th e o r d e r th a t th e y a p p e a r , fr o m th e b e g in n in g o f th e m e th o d to
th e e n d o f th e m e th o d . T h is s ta te m e n t e x e c u te s fir s t:
cardBackPictureBox.Visible = true;
T h e n th is s ta te m e n t e x e c u te s :
cardFacePictureBox.Visible = false;
W h e n th e a p p lic a tio n is r u n n in g , h o w e v e r , y o u c a n ’t r e a lly te ll th a t th e s ta te m e n ts a r e e x e c u tin g in th is o r d e r s im p ly b y w a tc h in g th e a c tio n ta k e p la c e o n th e s c r e e n . W h e n y o u c lic k
t h e showBackButton c o n t r o l , t h e C l i c k e v e n t h a n d l e r e x e c u t e s s o q u i c k l y t h a t i t a p p e a r s a s
th o u g h b o th s ta te m e n ts e x e c u te s im u lta n e o u s ly . It’s im p o r ta n t fo r y o u to u n d e r s ta n d , h o w e v e r , th a t th e s ta te m e n ts e x e c u te o n e a t a tim e , in th e o r d e r th a t th e y a p p e a r in th e m e th o d .
In th is p a r tic u la r m e th o d , it d o e s n ’t r e a lly m a tte r w h ic h a s s ig n m e n t s ta te m e n t is w r itte n
fir s t. If w e r e v e r s e th e o r d e r o f th e s ta te m e n ts , w e w ill n o t b e a b le to s e e th e d iffe r e n c e o n
th e s c r e e n b e c a u s e th e a p p lic a tio n e x e c u te s s o q u ic k ly . In m o s t a p p lic a tio n s , h o w e v e r , th e
o r d e r in w h ic h y o u w r ite th e s ta te m e n ts in th e e v e n t h a n d le r s is c r itic a lly im p o r ta n t. In
C h a p te r 3 y o u w ill s ta r t w r itin g e v e n t h a n d le r s th a t p e r fo r m s e v e r a l s te p s , a n d in m o s t
c a s e s , th e s te p s m u s t b e p e r fo r m e d in a s p e c ific o r d e r . O th e r w is e , th e p r o g r a m w ill n o t
p r o d u c e th e c o r r e c t r e s u lts .
C h e c k p o in t
2 .8
2 .3 8
W h a t is a P ic tu r e B o x c o n tr o l u s e d fo r ?
2 .3 9
W h e r e i s t h e P i c t u r e B o x t o o l l o c a t e d i n t h e Toolbox?
2 .4 0
H o w d o y o u d is p la y a n im a g e in th e P ic tu r e B o x ?
2 .4 1
W h a t is th e d e fa u lt v a lu e o f th e P ic tu r e B o x c o n tr o l’s S iz e M o d e p r o p e r ty ?
2 .4 2
H o w d o e s s e ttin g th e S iz e M o d e p r o p e r ty to Z o o m a ffe c t th e im a g e th a t is to b e
d is p la y e d in th e P ic tu r e B o x c o n tr o l?
2 .4 3
H o w d o y o u c r e a te a c lic k a b le im a g e ?
2 .4 4
D o e s th e v a lu e o f a c o n tr o l’s V is ib le p r o p e r ty c h a n g e h o w th e im a g e a p p e a r s a t
r u n tim e a n d d e s ig n tim e ?
C o m m e n t s , B la n k L in e s , a n d In d e n t a t io n
C O N C E P T :
C o m m e n t s a r e b r i e f n o t e s t h a t a r e p l a c e d i n a p r o g r a m ’s s o u r c e c o d e t o
e x p la in h o w p a r ts o f th e p r o g r a m w o r k . P r o g r a m m e r s c o m m o n ly u s e
b la n k lin e s a n d in d e n ta tio n in p r o g r a m c o d e to g iv e th e c o d e v is u a l
o r g a n iz a tio n a n d m a k e it e a s ie r to r e a d .
C o m m e n t s
C o m m e n ts a r e s h o r t n o te s th a t a r e p la c e d in d iffe r e n t p a r ts o f a p r o g r a m , e x p la in in g h o w
th o s e p a r ts o f th e p r o g r a m w o r k . C o m m e n ts a r e n o t in te n d e d fo r th e c o m p ile r . T h e y a r e
in te n d e d fo r a n y p e r s o n w h o is r e a d in g th e c o d e a n d tr y in g to u n d e r s ta n d w h a t it d o e s .
In C # , th e r e a r e th r e e ty p e s o f c o m m e n ts : lin e c o m m e n ts , b lo c k c o m m e n ts , a n d d o c u m e n ta tio n c o m m e n ts . A lin e c o m m e n t a p p e a r s o n o n e lin e in a p r o g r a m . Y o u b e g in a lin e
2 .8
C o m m e n t s , B la n k L in e s , a n d In d e n t a t io n
c o m m e n t w i t h t w o f o r w a r d s l a s h e s ( //) . E v e r y t h i n g w r i t t e n a f t e r t h e s l a s h e s , t o t h e e n d o f
th e lin e , is ig n o r e d b y th e c o m p ile r . T h e fo llo w in g c o d e s a m p le s h o w s h o w w e m ig h t u s e
l i n e c o m m e n t s i n t h e showBackButton_Click e v e n t h a n d l e r f r o m T u t o r i a l 2 - 5 . E a c h l i n e
c o m m e n t e x p la in s w h a t th e v e r y n e x t lin e o f c o d e d o e s .
private void showBackButton_Click(object sender, EventArgs e)
{
// Make the image of the back of the card visible.
cardBackPictureBox.Visible = true;
// Make the image of the face of the card invisible.
cardFacePictureBox.Visible = false;
}
A l i n e c o m m e n t d o e s n o t h a v e t o o c c u p y a n e n t i r e l i n e . A n y t h i n g a p p e a r i n g a f t e r t h e //
s y m b o l, to th e e n d o f th e lin e , is ig n o r e d . S o , a c o m m e n t c a n a p p e a r a fte r a n e x e c u ta b le
s ta te m e n t. T h e fo llo w in g c o d e s a m p le s h o w s a n e x a m p le .
private void showBackButton_Click(object sender, EventArgs e)
{
cardBackPictureBox.Visible = true; // Show the card back.
cardFacePictureBox.Visible = false; // Hide the card face.
}
A b lo c k c o m m e n t c a n o c c u p y m u ltip le c o n s e c u tiv e lin e s in a p r o g r a m . A b lo c k c o m m e n t
s t a r t s w i t h /* ( a f o r w a r d s l a s h f o l l o w e d b y a n a s t e r i s k ) a n d e n d s w i t h */ ( a n a s t e r i s k f o l lo w e d b y a fo r w a r d s la s h ). E v e r y th in g b e tw e e n th e s e m a r k e r s is ig n o r e d . T h e fo llo w in g
c o d e s a m p le s h o w s h o w b lo c k c o m m e n ts m a y b e u s e d .
/*
Click event handler for the showBackButton control.
This method makes the image of the back of the card
visible and makes the image of the card’s face
invisible.
*/
private void showBackButton_Click(object sender, EventArgs e)
{
cardBackPictureBox.Visible = true; // Show the card back.
cardFacePictureBox.Visible = false; // Hide the card face.
}
T h e fir s t fiv e lin e s in th is c o d e s a m p le a r e a b lo c k c o m m e n t th a t e x p la in s w h a t th e
showBackButton_Click m e t h o d d o e s . B l o c k c o m m e n t s m a k e i t e a s i e r t o w r i t e l o n g
e x p la n a tio n s b e c a u s e y o u d o n o t h a v e to m a r k e v e r y lin e w ith a c o m m e n t s y m b o l.
R e m e m b e r th e fo llo w in g a d v ic e w h e n u s in g b lo c k c o m m e n ts :
• B e c a r e f u l n o t t o r e v e r s e t h e b e g i n n i n g s y m b o l ( /*) w i t h t h e e n d i n g s y m b o l ( */) .
• D o n o t fo r g e t th e e n d in g s y m b o l.
E a c h o f th e s e m is ta k e s c a n b e d iffic u lt to tr a c k d o w n a n d w ill p r e v e n t th e p r o g r a m fr o m
c o m p ilin g c o r r e c tly .
T h e th ir d ty p e o f c o m m e n t is k n o w n a s a d o c u m e n ta tio n c o m m e n t. D o c u m e n ta tio n c o m m e n ts a r e u s e d b y p r o fe s s io n a l p r o g r a m m e r s to e m b e d e x te n s iv e d o c u m e n ta tio n in a p r o g r a m ’s s o u r c e c o d e . V is u a l S tu d io c a n e x tr a c t in fo r m a tio n fr o m th e d o c u m e n ta tio n
c o m m e n ts a n d g e n e r a te e x te r n a l d o c u m e n ta tio n file s . S in g le -lin e d o c u m e n ta tio n c o m m e n t s b e g i n w i t h t h r e e f o r w a r d s l a s h e s ( ///) . B l o c k d o c u m e n t a t i o n c o m m e n t s b e g i n w i t h
/** a n d e n d w i t h */. A l t h o u g h d o c u m e n t a t i o n c o m m e n t s a r e u s e f u l f o r p r o f e s s i o n a l p r o g r a m m e r s , w e d o n o t u s e th e m in th is b o o k .
A s a b e g in n in g p r o g r a m m e r , y o u m ig h t r e s is t th e id e a o f w r itin g a lo t o f c o m m e n ts in
y o u r p r o g r a m s . A fte r a ll, it’s a lo t m o r e in te r e s tin g to w r ite c o d e th a t a c tu a lly d o e s s o m e th in g ; h o w e v e r , it’s c r u c ia l th a t y o u ta k e th e e x tr a tim e to w r ite c o m m e n ts . T h e y w ill
103
104
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
a lm o s t c e r ta in ly s a v e y o u tim e in th e fu tu r e w h e n y o u h a v e to m o d ify o r d e b u g th e p r o g r a m . E v e n la r g e a n d c o m p le x p r o g r a m s c a n b e m a d e e a s y to r e a d a n d u n d e r s ta n d if th e y
h ave p ro p er co mmen ts.
U s in g B la n k L in e s a n d In d e n t a t io n t o M a k e Y o u r C o d e
E a s ie r t o R e a d
P r o g r a m m e r s c o m m o n ly u s e b la n k lin e s a n d in d e n ta tio n s in th e ir c o d e to c r e a te a s e n s e o f
v is u a l o r g a n iz a tio n . T h is is s im ila r to th e w a y th a t a u th o r s v is u a lly a r r a n g e th e te x t o n th e
p a g e s o f a b o o k . In s te a d o f w r itin g e a c h c h a p te r a s o n e lo n g s e r ie s o f s e n te n c e s , th e y
b r e a k th e te x t in to p a r a g r a p h s th a t a r e v is u a lly s e p a r a te d o n th e p a g e . T h is d o e s n o t
c h a n g e th e in fo r m a tio n in th e b o o k , b u t it m a k e s it e a s ie r to r e a d .
F o r e x a m p le , in th e fo llo w in g c o d e s a m p le , w e h a v e in s e r te d a b la n k lin e in s id e th e
m e th o d to v is u a lly s e p a r a te th e c o d e in to tw o s e ts o f s ta te m e n ts . T h e b la n k lin e is n o t
r e q u ir e d , b u t it m a k e s th e c o d e e a s ie r fo r h u m a n s to r e a d .
private void showBackButton_Click(object sender, EventArgs e)
{
// Make the image of the back of the card visible.
cardBackPictureBox.Visible = true;
// Make the image of the face of the card invisible.
cardFacePictureBox.Visible = false;
}
P r o g r a m m e r s a ls o u s e in d e n ta tio n to v is u a lly o r g a n iz e c o d e . Y o u m a y h a v e n o tic e d th a t
i n t h e c o d e e d i t o r , a l l t h e s t a t e m e n t s t h a t a p p e a r i n s i d e a s e t o f b r a c e s ( {}) a r e i n d e n t e d .
F o r e x a m p le , a ll th e s ta te m e n ts in s id e a n a m e s p a c e a r e in d e n te d , a ll th e s ta te m e n ts in s id e
a c la s s a r e in d e n te d , a n d a ll th e s ta te m e n ts in s id e a m e th o d a r e in d e n te d . In fa c t, V is u a l
S tu d io is n o r m a lly s e t u p to a u to m a tic a lly in d e n t th e c o d e th a t y o u w r ite in th is fa s h io n .
A lth o u g h th e in d e n ta tio n is n o t r e q u ir e d , it m a k e s y o u r c o d e m u c h e a s ie r to r e a d . B y in d e n tin g th e s ta te m e n ts in s id e a m e th o d , y o u v is u a lly s e t th e m a p a r t. A s a r e s u lt, y o u c a n te ll a t
a g la n c e w h ic h s ta te m e n ts a r e in s id e th e m e th o d . T h e s a m e is tr u e fo r c la s s e s a n d n a m e s p a c e s . T h is p r a c tic e o f in d e n ta tio n is a c o n v e n tio n th a t v ir tu a lly a ll p r o g r a m m e r s fo llo w .
C h e c k p o in t
2 .9
2 .4 5
Wh at p u rp o se d o co mmen ts serve?
2 .4 6
H o w a r e lin e c o m m e n ts a n d b lo c k c o m m e n ts d iffe r e n t?
2 .4 7
W h a t s h o u ld y o u b e c a r e fu l to r e m e m b e r a b o u t th e b e g in n in g a n d e n d in g s y m b o ls
o f b lo c k c o m m e n ts ?
2 .4 8
W h y d o p r o g r a m m e r s in s e r t b la n k lin e s a n d in d e n ta tio n s in th e ir c o d e ?
W r it in g t h e C o d e t o C lo s e a n A p p lic a t io n ’s F o r m
C O N C E P T :
T o c l o s e a n a p p l i c a t i o n ’ s f o r m i n c o d e , y o u u s e t h e s t a t e m e n t this.
Close();
A ll th e a p p lic a tio n s th a t y o u c r e a te d in th is c h a p te r ’s tu to r ia ls r e q u ir e d th e u s e r to c lic k
) to c lo s e th e a p p lic a tio n . T h e s ta n d a r d W in d o w s
th e s ta n d a r d W in d o w s c lo s e b u tto n (
c lo s e b u tto n a p p e a r s in th e u p p e r -r ig h t c o r n e r o f a lm o s t e v e r y w in d o w . In m a n y
2 .1 0
D e a lin g w it h S y n t a x E r r o r s
a p p lic a tio n s , h o w e v e r , y o u w ill w a n t to g iv e th e u s e r a n a lte r n a tiv e w a y to c lo s e th e
a p p l i c a t i o n . F o r e x a m p l e , y o u m i g h t w a n t t o c r e a t e a n Exit b u t t o n t h a t c l o s e s t h e a p p l i c a tio n w h e n it is c lic k e d .
T o c lo s e a n a p p lic a tio n ’s fo r m , y o u e x e c u te th e fo llo w in g s ta te m e n t:
this.Close();
L e t’s lo o k a t a n e x a m p le o f h o w th is s ta te m e n t c a n b e u s e d . F ig u r e 2 -7 5 s h o w s th e fo r m
a n d c o d e f r o m a p r o j e c t n a m e d Exit Button D emo. T h e B u t t o n c o n t r o l t h a t y o u s e e o n
t h e f o r m i s n a m e d exitButton. I n t h e f o r m ’ s c o d e y o u c a n s e e t h a t w e h a v e c r e a t e d a
C lic k e v e n t h a n d le r fo r th e b u tto n . W h e n th e u s e r c lic k s th e b u tto n , it c lo s e s th e fo r m ,
th u s c lo s in g th e a p p lic a tio n .
F ig u r e 2 -7 5
A f o r m w i t h a n Exit b u t t o n
exitButton
The exitButton control’s
Click event handler
2 .1 0
D e a lin g w it h S y n t a x E r r o r s
C O N C E P T :
T h e Vis u a l S tu d io c o d e e d ito r e x a m in e s e a c h s ta te m e n t a s y o u ty p e it a n d
r e p o r ts a n y s y n ta x e r r o r s th a t a r e fo u n d . T h is a llo w s y o u to q u ic k ly
co rrect syn tax erro rs.
W r itin g c o d e r e q u ir e s a lo t o f p r e c is io n . E v e n s m a ll e r r o r s , s u c h a s u s in g a n u p p e r c a s e le tte r w h e r e y o u a r e s u p p o s e d to u s e a lo w e r c a s e le tte r o r fo r g e ttin g to e n d a s ta te m e n t w ith
a s e m ic o lo n , w ill p r e v e n t a n a p p lic a tio n ’s c o d e fr o m c o m p ilin g a n d e x e c u tin g . R e c a ll
fr o m C h a p te r 1 th a t th e s e ty p e s o f m is ta k e s a r e k n o w n a s s y n ta x e r r o r s .
T h e V is u a l S tu d io c o d e e d ito r d o e s a g o o d jo b o f r e p o r tin g s y n ta x e r r o r s s o o n a fte r y o u
ty p e th e m . W h e n y o u e n te r a s ta te m e n t in to th e e d ito r , V is u a l S tu d io a n a ly z e s it, a n d if a
s y n ta x e r r o r is fo u n d , it is u n d e r lin e d w ith a ja g g e d lin e . F ig u r e 2 -7 6 s h o w s a n e x a m p le .
If y o u h o ld th e m o u s e c u r s o r o v e r th e ja g g e d a lin e , a d e s c r ip tio n o f th e e r r o r w ill p o p u p
in a T o o lT ip w in d o w . T h e d e s c r ip tio n u s u a lly g iv e s y o u e n o u g h in fo r m a tio n to d e te r m in e
th e c a u s e o f th e e r r o r a n d h o w to fix it.
105
106
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
F ig u r e 2 -7 6
E r r o r u n d e r lin e d
This jagged line indicates an error.
If a s y n ta x e r r o r e x is ts in a p r o je c t’s c o d e a n d y o u a tte m p t to c o m p ile a n d e x e c u te it (b y
p r e s s in g th e
k e y o n t h e k e y b o a r d , o r c l i c k i n g t h e Start D ebugging b u t t o n ( ) o n t h e
to o lb a r ), y o u w ill s e e th e w in d o w s h o w n in F ig u r e 2 -7 7 , r e p o r tin g b u ild e r r o r s . C lic k th e
N o b u t t o n t o c l o s e t h e w i n d o w , a n d y o u w i l l s e e t h e Error L ist s h o w n i n F i g u r e 2 - 7 8 .
F ig u r e 2 -7 7
F ig u r e 2 -7 8
W in d o w r e p o r t in g b u ild e r r o r s
Error List w i n d o w
N o t i c e t h a t t h e Error L ist w i n d o w s h o w s a d e s c r i p t i o n o f t h e e r r o r , t h e s o u r c e c o d e f i l e
th a t c o n ta in s th e e r r o r , th e lin e n u m b e r a n d c o lu m n n u m b e r o f th e e r r o r , a n d th e n a m e o f
t h e p r o j e c t . I f y o u d o u b l e - c l i c k t h e e r r o r m e s s a g e t h a t i s d i s p l a y e d i n t h e Error L ist w i n d o w , th e c o d e e d ito r w ill h ig h lig h t th e c o d e th a t c a u s e d th e e r r o r .
C h e c k p o in t
2 .4 9
W h a t s ta te m e n t d o y o u u s e to c lo s e a n a p p lic a tio n ’s fo r m in c o d e ?
2 .5 0
H o w c a n y o u te ll th a t V is u a l S tu d io h a s fo u n d a s y n ta x e r r o r ?
2 .5 1
W h a t h a p p e n s if y o u h o ld th e m o u s e c u r s o r o v e r a ja g g e d lin e in th e c o d e e d ito r ?
2 .5 2
W h a t h a p p e n s if y o u a tte m p t to c o m p ile a n d e x e c u te a p r o g r a m th a t c o n ta in s
syn tax erro rs?
R e v ie w Q u e s t io n s
K e y T e r m s
A lp h a b e tic a l b u tto n
a s p e c t r a tio
a s s ig n m e n t o p e r a to r
a s s ig n m e n t s ta te m e n t
A u to S iz e p r o p e r ty
b lo c k c o m m e n t
B o o le a n
B o r d e r S ty le p r o p e r ty
b o u n d in g b o x
b races
c a m e lC a s e
C a te g o r iz e d b u tto n
C lic k e v e n t
d e s ig n tim e
d ia lo g b o x
d o c u m e n ta tio n c o m m e n ts
e v e n t h a n d le r
Fo n t p ro p erty
F o r m 1 .c s file
H ello World
id e n tifie r s
Image p ro p erty
In te lliS e n s e
Lab el co n tro l
lin e c o m m e n t
message b o x
m e th o d c a ll
n amesp ace
P ic tu r e B o x c o n tr o l
P r o g r a m .c s file
r u n tim e
s e m ic o lo n
S iz e M o d e p r o p e r ty
s iz in g h a n d le s
s o u r c e c o d e file
s tr in g
T e x tA lig n p r o p e r ty
V is ib le p r o p e r ty
R e v ie w Q u e s t io n s
M u lt ip le C h o ic e
1 .
A ( n ) _ _ _ _ _ _ _ _ _ _ i s t h e t h i n d o t t e d l i n e t h a t e n c l o s e s a n o b j e c t i n t h e D esigner.
a.
b .
c.
d .
2 .
T h e s m a ll s q u a r e s th a t a p p e a r o n th e r ig h t e d g e , b o tto m e d g e , a n d lo w e r -r ig h t c o r n e r o f a fo r m ’s b o u n d in g b o x a r e c a lle d _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
3 .
b .
c.
d .
Fo rm1
M a in
New1
B la n k
T h e _ _ _ _ _ _ _ _ _ _ p r o p e r ty h o ld s th e te x t th a t is d is p la y e d o n th e fa c e o f th e b u tto n .
a.
b .
c.
d .
5 .
s iz in g h o o k s
fo rm ed ges
b o u n d in g ta g s
s iz in g h a n d le s
_ _ _ _ _ _ _ _ _ _ is th e n a m e o f th e b la n k fo r m th a t V is u a l S tu d io in itia lly c r e a te s in a
n e w p r o je c t.
a.
4 .
s e le c tio n m a r k e r
c o n tr o l b in d e r
b o u n d in g b o x
o b je c t c o n ta in e r
Name
Tex t
Tag
Face
A file th a t c o n ta in s p r o g r a m c o d e is c a lle d a (n ) _ _ _ _ _ _ _ _ _ _ .
a.
b .
d e s tin a tio n c o d e file
e x e c u ta b le file
107
108
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
c.
d .
6 .
A n a m e s p a c e is c o n ta in e r th a t h o ld s _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
7 .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
id e n tifie r
s p e c ifie r
k eywo rd
lite r a l
r u n tim e
d e s ig n tim e
c o d e tim e
p la n n in g
T h e tim e d u r in g w h ic h a n a p p lic a tio n is e x e c u tin g is r e fe r r e d to a s _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
1 4 .
s e m ic o lo n
p e r io d
h yp h en
u n d ersco re
T h e tim e d u r in g w h ic h y o u b u ild th e G U I a n d w r ite th e a p p lic a tio n ’s c o d e is r e fe r r e d
to as __________.
a.
1 3 .
m a n y lin e s o f c o d e
p a r a lle l m e m o r y lo c a tio n s
s tr in g o f c h a r a c te r s
v ir tu a lly a n y th in g
A p ie c e o f d a ta th a t is w r itte n in to a p r o g r a m ’s c o d e is a (n ) _ _ _ _ _ _ _ _ _ _ _ .
a.
1 2 .
m e th o d c a ll
n amesp ace
C lic k e v e n t
e v e n t h a n d le r
A (n ) _ _ _ _ _ _ _ _ _ _ m a r k s th e e n d o f a p r o g r a m m in g s ta te m e n t in C # .
a.
1 1 .
e x a m p le o f a (n )
I n p r o g r a m m i n g w e u s e t h e t e r m string t o m e a n _ _ _ _ _ _ _ _ _ _ .
a.
1 0 .
a c tio n p r o c e s s
e v e n t h a n d le r
r u n tim e p r o c e d u r e
even t meth o d
T h e s t a t e m e n t MessageBox.Show("Hello World") ; i s a n
__________.
a.
9 .
meth o d s
n ames
sp aces
c la s s e s
A (n ) _ _ _ _ _ _ _ _ _ _ is a m e th o d th a t e x e c u te s w h e n a s p e c ific e v e n t ta k e s p la c e w h ile
a n a p p lic a tio n is r u n n in g .
a.
8 .
m a c h in e la n g u a g e file
s o u r c e c o d e file
g o tim e
d e s ig n tim e
e x e c u tio n
r u n tim e
W h e n y o u w a n t to d is p la y te x t o n a fo r m , y o u u s e a _ _ _ _ _ _ _ _ _ _ c o n tr o l.
a.
b .
Bu tto n
P ic tu r e B o x
R e v ie w Q u e s t io n s
c.
d .
1 5 .
T h e _ _ _ _ _ _ _ _ _ _ p r o p e r ty a llo w s y o u to s e t th e fo n t, fo n t s ty le , a n d s iz e o f th e c o n tr o l’s te x t.
a.
b .
c.
d .
1 6 .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
ControlN ame.PropertyN ame
ControlN ame=PropertyN ame
PropertyN ame.ControlN ame
PropertyN ame=ControlN ame
_ _ _ _ _ _ _ _ _ _ is a fe a tu r e o f V is u a l S tu d io th a t p r o v id e s a u to m a tic c o d e c o m p le tio n a s
y o u w r ite p r o g r a m m in g s ta te m e n ts .
a.
b .
c.
d .
2 3 .
e q u a lity s y m b o l
a s s ig n m e n t o p e r a to r
e q u a lity o p e r a to r
p r o p e r ty p o s itio n
T h e s ta n d a r d n o ta tio n fo r r e fe r r in g to a c o n tr o l’s p r o p e r ty in c o d e is _ _ _ _ _ _ _ _ _ _ .
a.
2 2 .
C lic k e v e n t
m e th o d c a ll
a s s ig n m e n t s ta te m e n t
B o o le a n v a lu e
T h e e q u a l s i g n ( =) i s k n o w n a s t h e _ _ _ _ _ _ _ _ _ _ .
a.
2 1 .
T e x tP o s itio n
A u to A lig n
Tex tCen ter
T e x tA lig n
In c o d e , y o u u s e a (n ) _ _ _ _ _ _ _ _ _ _ to s to r e a v a lu e in a c o n tr o l’s p r o p e r ty .
a.
2 0 .
Stretch
A u to S iz e
D im e n s io n
F ix e d
T h e _ _ _ _ _ _ _ _ _ _ p r o p e r ty c a n b e u s e d to c h a n g e th e te x t’s a lig n m e n t in th e la b e l.
a.
1 9 .
B o o le a n
L o g ic a l
B in a r y
Du al
L a b e l c o n tr o ls h a v e a (n ) _ _ _ _ _ _ _ _ _ _ p r o p e r ty th a t c o n tr o ls th e w a y th e y c a n b e
r e s iz e d .
a.
1 8 .
S ty le
A u to S iz e
Tex t
Fo n t
A _ _ _ _ _ _ _ _ _ _ p r o p e r ty c a n b e s e t to o n e o f tw o p o s s ib le v a lu e s : T r u e o r F a ls e .
a.
1 7 .
Lab el
Tex tBo x
Au to Co d e
A u to C o m p le te
In te lliS e n s e
In te lliC o d e
Y o u c a n u s e a (n ) _ _ _ _ _ _ _ _ _ _ c o n tr o l to d is p la y a g r a p h ic im a g e o n a fo r m .
a.
b .
G r a p h ic s
P ic tu r e B o x
109
110
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
c.
d .
2 4 .
O n c e y o u h a v e c r e a te d a P ic tu r e B o x c o n tr o l, y o u u s e its _ _ _ _ _ _ _ _ _ _ p r o p e r ty to
s p e c ify th e im a g e th a t it w ill d is p la y .
a.
b .
c.
d .
2 5 .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b lo c k c o m m e n t
sq u are co mmen t
m u ltilin e c o m m e n t
m a c h in e c o m m e n t
P r o g r a m m e r s c o m m o n ly u s e b la n k lin e s a n d in d e n ta tio n s in th e ir c o d e to c r e a te a
sen se o f __________.
a.
b .
c.
d .
3 1 .
in lin e c o m m e n t
lin e c o m m e n t
fo rward co mmen t
b lo c k c o m m e n t
A _ _ _ _ _ _ _ _ _ _ c a n o c c u p y m u ltip le c o n s e c u tiv e lin e s in a p r o g r a m .
a.
3 0 .
Ren d er
V ie w a b le
V is ib le
Draw
A (a n ) _ _ _ _ _ _ _ _ _ _ a p p e a r s o n o n e lin e in a p r o g r a m .
a.
2 9 .
A s p e c t r a tio
S iz e r a tio
P r o je c tio n r a tio
A r e a r a tio
M o s t c o n tr o ls h a v e a _ _ _ _ _ _ _ _ _ _ p r o p e r ty th a t d e te r m in e s w h e th e r th e c o n tr o l is
v is ib le o n th e fo r m a t r u n tim e .
a.
2 8 .
Ren d erMo d e
DrawMo d e
S iz e M o d e
ImageMo d e
_ _ _ _ _ _ _ _ _ _ is th e im a g e ’s w id th to h e ig h t r a tio .
a.
2 7 .
Image
So u rce
DrawSo u rce
Im a g e L is t
T h e P ic tu r e B o x c o n tr o l’s _ _ _ _ _ _ _ _ _ _ p r o p e r ty s p e c ifie s h o w th e c o n tr o l’s im a g e is
to b e d is p la y e d .
a.
2 6 .
D r a w in g
ImageBo x
lo g ic
v is u a l o r g a n iz a tio n
d o c u m e n ta tio n
p r o g r a m flo w
T o c lo s e a n a p p lic a tio n ’s fo r m in c o d e , y o u u s e th e s ta te m e n t _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
Close();
Close.This();
Close()
this.Close();
R e v ie w Q u e s t io n s
T r u e o r F a ls e
1 .
C h a n g in g a n o b je c t’s T e x t p r o p e r ty a ls o c h a n g e s th e o b je c t’s n a m e .
2 .
W h e n a fo r m is c r e a te d , its T e x t p r o p e r ty is in itia lly s e t to th e s a m e v a lu e a s th e
fo r m ’s n a m e .
3 .
T h e fo r m ’s title is d is p la y e d in th e b a r a lo n g th e to p o f a fo r m .
4 .
C # s o u r c e c o d e file s a lw a y s e n d w ith th e .c s e x te n s io n .
5 .
Y o u a d d y o u r o w n c o d e to th e P r o g a m .c s file a s y o u d e v e lo p a n a p p lic a tio n .
6 .
C # c o d e is o r g a n iz e d a s m e th o d s , w h ic h a r e c o n ta in e d in s id e c la s s e s , w h ic h a r e c o n ta in e d in s id e n a m e s p a c e s .
7 .
In C # c o d e , e a c h o p e n in g b r a c e m u s t h a v e a c o r r e s p o n d in g c lo s in g b r a c e a t s o m e
p o in t la te r in th e p r o g r a m .
8 .
W h e n y o u d o u b l e - c l i c k a c o n t r o l i n t h e D esigner, V i s u a l S t u d i o n o t o n l y c r e a t e s a n
e m p ty e v e n t h a n d le r , b u t it a ls o w r ite s s o m e c o d e th a t y o u d o n ’t s e e , e ls e w h e r e in
th e p r o je c t th a t is n e c e s s a r y fo r th e e v e n t h a n d le r to p r o p e r ly fu n c tio n .
9 .
A L a b e l c o n tr o l’s T e x t p r o p e r ty is in itia lly s e t to th e s a m e v a lu e a s th e L a b e l c o n tr o l’s n a m e .
1 0 .
W h e n a L a b e l c o n tr o l’s A u to S iz e p r o p e r ty is s e t to T r u e , y o u c a n n o t m a n u a lly
c h a n g e th e s iz e o f th e c o n tr o l b y c lic k in g a n d d r a g g in g its b o u n d in g b o x .
1 1 .
B y d e fa u lt, a la b e l’s te x t is a lig n e d w ith th e b o tto m a n d r ig h t e d g e s o f th e la b e l’s
b o u n d in g b o x .
1 2 .
L a b e l c o n tr o ls a r e u s e fu l fo r d is p la y in g o u tp u t w h ile a n a p p lic a tio n is r u n n in g .
1 3 .
T h e a s s ig n m e n t o p e r a to r a s s ig n s th e v a lu e th a t a p p e a r s o n its le ft s id e to th e ite m
th a t a p p e a r s o n its r ig h t s id e .
1 4 .
P ic tu r e B o x c o n tr o ls a ls o h a v e a B o r d e r S ty le p r o p e r ty th a t w o r k s ju s t lik e a L a b e l
c o n tr o l’s B o r d e r S ty le p r o p e r ty .
1 5 .
B u tto n s a r e th e o n ly c o n tr o ls th a t c a n r e s p o n d to C lic k e v e n ts .
1 6 .
T h e V is ib le p r o p e r ty is a B in a r y p r o p e r ty , w h ic h m e a n s it c a n b e s e t o n ly to th e v a lu es 1 an d 0 .
1 7 .
W h e n y o u w r i t e t h e v a l u e s true o r false i n c o d e , t h e y m u s t b e w r i t t e n i n a l l l o w e r c a s e le tte r s .
1 8 .
In C # , th e r e a r e th r e e ty p e s o f c o m m e n ts : lin e c o m m e n ts , b lo c k c o m m e n ts , a n d
d o c u m e n ta tio n c o m m e n ts .
1 9 .
T o c l o s e a n a p p l i c a t i o n ’ s f o r m i n c o d e , y o u u s e t h e s t a t e m e n t Close.This();
2 0 .
T h e V is u a l S tu d io c o d e e d ito r e x a m in e s e a c h s ta te m e n t a s y o u ty p e it, a n d r e p o r ts
an y syn tax erro rs th at are fo u n d .
S h o r t A n s w e r
1 .
W h a t d o e s a b o u n d i n g b o x i n d i c a t e a b o u t a n o b j e c t i n t h e D esigner?
2 .
W h a t h a p p e n s w h e n y o u p o s itio n th e m o u s e c u r s o r o v e r a n e d g e o r c o r n e r o f a
b o u n d in g b o x th a t h a s s iz in g h a n d le s ?
3 .
W h a t d e te r m in e s a n o b je c t’s a p p e a r a n c e a n d o th e r c h a r a c te r is tic s ?
111
112
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
4 .
W h a t i s s h o w n b y e a c h c o l u m n i n t h e Properties w i n d o w ?
5 .
W h a t s te p s m u s t y o u p e r fo r m to c h a n g e a fo r m ’s T e x t p r o p e r ty ?
6 .
W h a t s t e p s m u s t y o u p e r f o r m t o c h a n g e a f o r m ’ s S i z e p r o p e r t y i n t h e Properties
w in d o w ?
7 .
H o w d o y o u m o v e a c o n tr o l to a n e w lo c a tio n o n th e fo r m u s in g th e m o u s e ?
8 .
W h a t s te p s d o y o u p e r fo r m to c h a n g e a B u tto n c o n tr o l’s T e x t p r o p e r ty ?
9 .
B r ie fly d e s c r ib e th e c o n te n ts o f th e F o r m 1 .c s file .
1 0 .
In c o d e , w h a t c h a r a c te r s d o y o u e n c lo s e a s tr in g lite r a l in ?
1 1 .
W h e n c r e a tin g a n e v e n t h a n d le r fo r a b u tto n , is it p o s s ib le to s k ip a s te p b y o p e n in g
th e c o d e e d ito r a n d w r itin g a ll th e e v e n t h a n d le r c o d e y o u r s e lf? W h y o r w h y n o t?
1 2 .
B r ie fly d e s c r ib e th e d iffe r e n c e b e tw e e n d e s ig n tim e a n d r u n tim e .
1 3 .
D e s c r ib e th e a p p e a r a n c e o f a L a b e l c o n tr o l th a t’s B o r d e r S ty le p r o p e r ty is s e t to
F ix e d 3 D .
1 4 .
W h a t d o e s it m e a n w h e n a L a b e l c o n tr o l’s A u to S iz e p r o p e r ty is s e t to T r u e ?
1 5 .
W h a t a r e th e v a lu e s th a t th e T e x tA lig n p r o p e r ty m a y b e s e t to ?
1 6 .
H o w d o y o u c le a r th e te x t th a t is d is p la y e d in a L a b e l c o n tr o l in c o d e ?
1 7 .
W h a t a r e th e d iffe r e n t im a g e fo r m a ts th a t a P ic tu r e B o x c o n tr o l c a n d is p la y ?
1 8 .
L is t th e v a lu e s th a t th e S iz e M o d e p r o p e r ty o f a P ic tu r e B o x c o n tr o l c a n b e s e t to .
1 9 .
W h a t a r e th e th r e e ty p e s o f c o m m e n ts y o u c a n u s e in V is u a l C # ?
2 0 .
H o w d o e s V is u a l S tu d io h e lp y o u to q u ic k ly c o r r e c t s y n ta x e r r o r s ?
A lg o r it h m W o r k b e n c h
1 .
W h a t s t a t e m e n t w o u l d y o u w r i t e t o d i s p l a y Good Afternoon i n a m e s s a g e b o x ?
2 .
W h a t s ta te m e n t w o u ld y o u w r ite to d is p la y y o u r n a m e in a m e s s a g e b o x ?
3 .
S u p p o s e a n a p p l i c a t i o n ’ s G U I h a s a L a b e l c o n t r o l n a m e d dogLabel. W r i t e a s t a t e m e n t t h a t c a u s e s Fido t o b e d i s p l a y e d i n t h e dogLabel c o n t r o l .
4 .
S u p p o s e a n a p p l i c a t i o n ’ s G U I h a s a L a b e l c o n t r o l n a m e d outputLabel. W r i t e a
s ta te m e n t th a t c le a r s a n y te x t th a t h a p p e n s to b e d is p la y e d b y th e c o n tr o l.
5 .
S u p p o s e a n a p p l i c a t i o n ’ s G U I h a s a P i c t u r e B o x c o n t r o l n a m e d myPicture. W r i t e a
s ta te m e n t th a t m a k e s th e c o n tr o l in v is ib le .
P r o g r a m m in g P r o b le m s
1 .
L a tin T r a n s la to r
L o o k a t th e fo llo w in g lis t o f L a tin w o r d s a n d th e ir m e a n in g s :
L a tin
s in is te r
d ex ter
m e d iu m
E n g lis h
le ft
r ig h t
cen ter
P r o g r a m m in g P r o b le m s
C r e a te a n a p p lic a tio n th a t tr a n s la te s th e L a tin w o r d s to E n g lis h . T h e fo r m s h o u ld
h a v e th r e e b u tto n s , o n e fo r e a c h L a tin w o r d . W h e n th e u s e r c lic k s a b u tto n , th e
a p p lic a tio n s h o u ld d is p la y th e E n g lis h tr a n s la tio n in a L a b e l c o n tr o l.
2 .
C lic k a b le N u m b e r Im a g e s
I n t h e Chap02 f o l d e r , i n t h e S t u d e n t S a m p l e P r o g r a m f i l e s , y o u w i l l f i n d t h e i m a g e
file s s h o w n in F ig u r e 2 -7 9 . C r e a te a n a p p lic a tio n th a t d is p la y s th e s e im a g e s in
P ic tu r e B o x c o n tr o ls . T h e a p p lic a tio n s h o u ld p e r fo r m th e fo llo w in g a c tio n s :
VideoNot e
S o lv in g th e
C lic k a b le
Nu mb er
Images
P r o b le m
•
•
•
•
•
W h e n t h e u s e r c l i c k s t h e 1 i m a g e , t h e a p p l i c a t i o n s h o u l d d i s p l a y t h e w o r d O ne
in a m e s s a g e b o x .
W h e n t h e u s e r c l i c k s t h e 2 i m a g e , t h e a p p l i c a t i o n s h o u l d d i s p l a y t h e w o r d Two
in a m e s s a g e b o x .
W h e n t h e u s e r c l i c k s t h e 3 i m a g e , t h e a p p l i c a t i o n s h o u l d d i s p l a y t h e w o r d Three
in a m e s s a g e b o x .
W h e n t h e u s e r c l i c k s t h e 4 i m a g e , t h e a p p l i c a t i o n s h o u l d d i s p l a y t h e w o r d Four
in a m e s s a g e b o x .
W h e n t h e u s e r c l i c k s t h e 5 i m a g e , t h e a p p l i c a t i o n s h o u l d d i s p l a y t h e w o r d Five
in a m e s s a g e b o x .
F ig u r e 2 -7 9
Im a g e file s
One.bmp
3 .
Two.bmp
Three.bmp
Four.bmp
Five.bmp
C a r d Id e n tifie r
In th e S tu d e n t S a m p le P r o g r a m s th a t a c c o m p a n y th is b o o k , y o u w ill fin d a fo ld e r
n a m e d I mages\ Cards\ Poker L arge. I n t h a t f o l d e r y o u w i l l f i n d J P E G i m a g e f i l e s f o r
a c o m p le te d e c k o f p o k e r c a r d s . C r e a te a n a p p lic a tio n w ith fiv e P ic tu r e B o x c o n tr o ls .
E a c h P ic tu r e B o x s h o u ld d is p la y a d iffe r e n t c a r d fr o m th e s e t o f im a g e s . W h e n th e
u s e r c lic k s a n y o f th e P ic tu r e B o x c o n tr o ls , th e n a m e o f th e c a r d s h o u ld b e d is p la y e d
in a L a b e l c o n tr o l. F ig u r e 2 -8 0 s h o w s a n e x a m p le o f th e a p p lic a tio n r u n n in g . T h e
im a g e o n th e le ft s h o w s th e a p p lic a tio n ’s fo r m w h e n it s ta r ts r u n n in g . T h e im a g e o n
th e r ig h t s h o w s th e fo r m a fte r th e u s e r h a s c lic k e d th e tw o o f c lu b s c a r d .
F ig u r e 2 -8 0
Ca rd Identifier a p p l i c a t i o n
113
114
C h a p te r 2
In t r o d u c t io n t o V is u a l C #
4 .
J o k e a n d P u n c h L in e
A jo k e ty p ic a lly h a s tw o p a r ts : a s e tu p a n d a p u n c h lin e . F o r e x a m p le , th is m ig h t b e
th e s e tu p fo r a jo k e :
H ow many programmers does it take to change a lightbulb?
A n d th is is th e p u n c h lin e :
N one. That’s a hardware problem.
T h in k o f y o u r fa v o r ite jo k e a n d id e n tify its s e tu p a n d p u n c h lin e . T h e n , c r e a te a n
a p p lic a tio n th a t h a s a L a b e l a n d tw o b u tto n s o n a fo r m . O n e o f th e b u tto n s s h o u ld
r e a d “ S e t u p ” a n d t h e o t h e r b u t t o n s h o u l d r e a d “ P u n c h l i n e . ” W h e n t h e Setup b u t t o n i s c l i c k e d , d i s p l a y t h e j o k e ’ s s e t u p i n t h e L a b e l c o n t r o l . W h e n t h e Punch line
b u tto n is c lic k e d , d is p la y th e jo k e ’s p u n c h lin e in th e L a b e l c o n tr o l.
5 .
H e a d s o r T a ils
In th e S tu d e n t S a m p le P r o g r a m s th a t a c c o m p a n y th is b o o k y o u w ill fin d a fo ld e r
n a m e d I mages\ Coins t h a t c o n t a i n s i m a g e s s h o w i n g t h e h e a d s a n d t a i l s s i d e s o f a
c o i n . C r e a t e a n a p p l i c a t i o n w i t h a Show H eads b u t t o n a n d a Show Tails b u t t o n .
W h e n t h e u s e r c l i c k s t h e Show H eads b u t t o n , a n i m a g e o f t h e h e a d s s i d e o f a c o i n
s h o u l d a p p e a r . W h e n t h e u s e r c l i c k s t h e Show Tails b u t t o n , a n i m a g e o f t h e t a i l s s i d e
o f a c o in s h o u ld a p p e a r . F ig u r e 2 -8 1 s h o w s e x a m p le s o f h o w th e a p p lic a tio n ’s fo r m
m ig h t a p p e a r .
F ig u r e 2 -8 1
6 .
T h e Hea ds or Ta ils a p p l i c a t i o n
O r io n C o n s te lla tio n
O r i o n i s o n e o f t h e m o s t f a m o u s c o n s t e l l a t i o n s i n t h e n i g h t s k y . I n t h e Chap02
fo ld e r o f th e S tu d e n t S a m p le P r o g r a m s th a t a c c o m p a n y th is b o o k , y o u w ill fin d a n
im a g e file n a m e d O r io n .b m p , w h ic h c o n ta in s a d ia g r a m o f th e O r io n c o n s te lla tio n .
C r e a te a n a p p lic a tio n th a t d is p la y s th e O r io n im a g e in a P ic tu r e B o x c o n tr o l, a s
s h o w n o n th e le ft in F ig u r e 2 -8 2 . T h e a p p lic a tio n s h o u ld h a v e a b u tto n th a t, w h e n
c lic k e d , d is p la y s th e n a m e s o f e a c h o f th e s ta r s , a s s h o w n o n th e r ig h t in F ig u r e 2 -8 2 .
T h e a p p lic a tio n s h o u ld h a v e a n o th e r b u tto n th a t, w h e n c lic k e d , h id e s th e s ta r
n a m e s . T h e n a m e s o f t h e s t a r s a r e Betelgeuse, M eissa, Alnitak, Alnilam, M intaka,
Saiph, a n d Rigel.
H in t: P la c e th e P ic tu r e B o x c o n tr o l w ith th e O r io n im a g e o n th e fo r m . T h e n , p la c e
L a b e l c o n t r o l s c o n t a i n i n g t h e s t a r n a m e s o n t o p o f t h e P i c t u r e B o x . U s e t h e Properties w i n d o w t o s e t e a c h o f t h e L a b e l c o n t r o l ’ s V i s i b l e p r o p e r t y t o F a l s e . T h a t w i l l
c a u s e t h e l a b e l s t o b e i n v i s i b l e w h e n t h e a p p l i c a t i o n r u n s . T h e Show Star N ames
b u t t o n w i l l s e t e a c h o f t h e L a b e l c o n t r o l ’ s V i s i b l e p r o p e r t y t o true, a n d t h e H ide
Star N ames b u t t o n w i l l s e t e a c h o f t h e L a b e l c o n t r o l ’ s V i s i b l e p r o p e r t y t o false.
P r o g r a m m in g P r o b le m s
F ig u r e 2 -8 2
T h e Orion Constella tion a p p l i c a t i o n
115
This page intentionally left blank
C H A P T E R
3
P r o c e s s in g D a t a
T O P I C S
3 .1
R e a d in g In p u t w it h T e x t B o x C o n t r o ls
3 .7
S im p le E x c e p t io n H a n d lin g
3 .2
A F ir s t L o o k a t V a r ia b le s
3 .8
U s in g N a m e d C o n s t a n t s
3 .3
N u m e r ic D a t a T y p e s a n d V a r ia b le s
3 .9
D e c la r in g V a r ia b le s a s F ie ld s
3 .4
P e r fo r m in g C a lc u la t io n s
3 .1 0
U s i n g t h e Math C l a s s
3 .5
In p u t t in g a n d O u t p u t t in g N u m e r ic
V a lu e s
3 .1 1
M o r e G U I D e t a ils
3 .1 2
U s in g t h e D e b u g g e r t o L o c a t e L o g ic
E rro rs
3 .6
3 .1
F o r m a t t in g N u m b e r s w it h t h e
ToString M e t h o d
R e a d in g In p u t w it h T e x t B o x C o n t r o ls
C O N C E P T :
T h e T e x tB o x c o n tr o l is a r e c ta n g u la r a r e a th a t c a n a c c e p t k e y b o a r d in p u t
fro m th e u ser.
M a n y o f th e p r o g r a m s th a t y o u w ill w r ite fr o m th is p o in t fo r w a r d w ill r e q u ir e th e u s e r to
e n te r d a ta . T h e d a ta e n te r e d b y th e u s e r w ill th e n b e u s e d in s o m e s o r t o f o p e r a tio n . O n e
o f th e p r im a r y c o n tr o ls th a t y o u w ill u s e to g e t d a ta fr o m th e u s e r is th e T e x tB o x c o n tr o l.
A T e x tB o x c o n tr o l a p p e a r s a s a r e c ta n g u la r a r e a o n a fo r m . W h e n th e a p p lic a tio n is r u n n in g , th e u s e r c a n ty p e te x t in to a T e x tB o x c o n tr o l. T h e p r o g r a m c a n th e n r e tr ie v e th e te x t
th a t th e u s e r e n te r e d a n d u s e th a t te x t in a n y n e c e s s a r y o p e r a tio n s .
I n t h e Toolbox, t h e T e x t B o x t o o l i s l o c a t e d i n t h e Common Controls g r o u p . W h e n y o u
d o u b le -c lic k th e to o l, a T e x tB o x c o n tr o l is c r e a te d o n th e fo r m , a s s h o w n in F ig u r e 3 -1 .
W h e n y o u c r e a te T e x tB o x c o n tr o ls , th e y a r e a u to m a tic a lly g iv e n d e fa u lt n a m e s s u c h a s
textBox1, textBox2, a n d s o f o r t h . A s y o u l e a r n e d i n C h a p t e r 2 , y o u s h o u l d a l w a y s
c h a n g e a c o n tr o l’s d e fa u lt n a m e to s o m e th in g m o r e m e a n in g fu l.
W h e n th e u s e r ty p e s in to a T e x tB o x c o n tr o l, th e te x t is s to r e d in th e c o n tr o l’s T e x t p r o p e r ty . In c o d e , if y o u w a n t to r e tr ie v e th e d a ta th a t h a s b e e n ty p e d in to a T e x tB o x , y o u
s im p ly r e tr ie v e th e c o n te n ts o f th e c o n tr o l’s T e x t p r o p e r ty .
117
118
C h a p te r 3
P r o c e s s in g D a t a
F ig u r e 3 -1
A T e x tB o x c o n tro l
N O T E : W h e n y o u r e t r i e v e t h e c o n t e n t s o f t h e T e x t p r o p e r t y , y o u always g e t a s t r i n g .
A n y o p e r a tio n th a t c a n b e p e r fo r m e d o n a s tr in g c a n b e p e r fo r m e d o n a c o n tr o l’s
T e x tp r o p e r ty .
L e t’s lo o k a t a n e x a m p le . M a k e s u r e y o u h a v e d o w n lo a d e d th e s tu d e n t s a m p le p r o g r a m s
fr o m th e b o o k ’s c o m p a n io n W e b s ite (a t w w w .p e a r s o n h ig h e r e d .c o m /g a d d is ). In th e
Chap03 f o l d e r , y o u w i l l f i n d a p r o j e c t n a m e d TextBox D emo. F i g u r e 3 - 2 s h o w s t h e
fo r m , w ith m o s t o f th e c o n tr o l n a m e s s p e c ifie d , a n d F ig u r e 3 -3 s h o w s th e fo r m ’s c o d e .
( I n F i g u r e 3 - 3 , t o c o n s e r v e s p a c e o n t h e p a g e , w e h a v e s c r o l l e d p a s t t h e using d i r e c t i v e s
th a t a p p e a r a t th e to p o f th e c o d e file .)
N o t i c e i n F i g u r e 3 - 3 t h a t t h e readInputButton c o n t r o l ’ s C l i c k e v e n t h a n d l e r p e r f o r m s
th e fo llo w in g a s s ig n m e n t s ta te m e n t:
outputLabel.Text = nameTextBox.Text;
T h i s s t a t e m e n t a s s i g n s t h e v a l u e o f t h e nameTextBox c o n t r o l ’ s T e x t p r o p e r t y t o t h e
outputLabel c o n t r o l ’ s T e x t p r o p e r t y . I n o t h e r w o r d s , i t g e t s a n y t e x t t h a t h a s b e e n
e n t e r e d b y t h e u s e r i n t o t h e nameTextBox c o n t r o l a n d d i s p l a y s i t i n t h e outputLabel
c o n tr o l. If y o u r u n th e a p p lic a tio n , F ig u r e 3 -4 s h o w s a n e x a m p le o f h o w th e fo r m a p p e a r s
a f t e r y o u h a v e e n t e r e d Kathryn Smith a n d c l i c k e d t h e readInputButton c o n t r o l .
F ig u r e 3 -2
T h e TextBox Demo a p p l i c a t i o n
nameTextBox
outputLabel
readInputButton
exitButton
3 .1
R e a d in g In p u t w it h T e x t B o x C o n t r o ls
F ig u r e 3 -3
T h e f o r m ’ s c o d e ( e x c l u d i n g t h e using d i r e c t i v e s )
F ig u r e 3 -4
T h e u s e r ’ s n a m e d is p la y e d in t h e la b e l
C le a r in g t h e C o n t e n t s o f a T e x t B o x C o n t r o l
Y o u c a n c le a r th e c o n te n ts o f a T e x tB o x c o n tr o l in th e s a m e w a y th a t y o u c le a r th e c o n t e n t s o f a L a b e l c o n t r o l : y o u a s s i g n a n e m p t y s t r i n g ( "") t o t h e c o n t r o l ’ s T e x t p r o p e r t y .
F o r e x a m p l e , t h e f o l l o w i n g s t a t e m e n t c l e a r s t h e c o n t e n t s o f t h e nameTextBox c o n t r o l :
nameTextBox.Text = "";
W h e n t h i s s t a t e m e n t e x e c u t e s , t h e nameTextBox c o n t r o l w i l l a p p e a r e m p t y o n t h e a p p l i c a tio n ’s fo r m .
C h e c k p o in t
3 .1
W h a t c o n tr o l c a n b e u s e d to g a th e r te x t in p u t fr o m th e u s e r ?
3 .2
In c o d e , h o w d o y o u r e tr ie v e d a ta th a t h a s b e e n ty p e d in to a T e x tB o x c o n tr o l?
3 .3
W h a t ty p e o f d a ta d o e s a c o n tr o l’s T e x t p r o p e r ty a lw a y s c o n ta in ?
3 .4
H o w d o y o u c le a r th e c o n te n ts o f a T e x tB o x c o n tr o l?
119
120
C h a p te r 3
3 .2
P r o c e s s in g D a t a
A F ir s t L o o k a t V a r ia b le s
C O N C E P T :
A v a r ia b le is a s to r a g e lo c a tio n in m e m o r y th a t is r e p r e s e n te d b y a n a m e .
M o s t p r o g r a m s s to r e d a ta in th e c o m p u te r ’s m e m o r y a n d p e r fo r m o p e r a tio n s o n th a t d a ta .
F o r e x a m p le , c o n s id e r th e ty p ic a l o n lin e s h o p p in g e x p e r ie n c e : y o u b r o w s e a W e b s ite a n d a d d
th e ite m s th a t y o u w a n t to p u r c h a s e to th e s h o p p in g c a r t. A s y o u a d d ite m s to th e s h o p p in g
c a r t , d a t a a b o u t t h o s e i t e m s i s s t o r e d i n m e m o r y . T h e n , w h e n y o u c l i c k t h e checkout b u t t o n ,
a p r o g r a m r u n n in g o n th e W e b s ite ’s c o m p u te r c a lc u la te s th e c o s t o f a ll th e ite m s y o u h a v e in
y o u r s h o p p in g c a r t, a p p lic a b le s a le s ta x e s , s h ip p in g c o s ts , a n d th e to ta l o f a ll th e s e c h a r g e s .
W h e n th e p r o g r a m p e r fo r m s th e s e c a lc u la tio n s , it s to r e s th e r e s u lts in th e c o m p u te r ’s m e m o r y .
P r o g r a m s u s e v a r ia b le s to s to r e d a ta in m e m o r y . A v a r ia b le is a s to r a g e lo c a tio n in m e m o r y th a t is r e p r e s e n te d b y a n a m e . F o r e x a m p le , a p r o g r a m th a t m a n a g e s a c o m p a n y ’s
c u s t o m e r m a i l i n g l i s t m i g h t u s e a v a r i a b l e n a m e d lastName t o h o l d a c u s t o m e r ’ s l a s t
n a m e , a v a r i a b l e n a m e d firstName t o h o l d t h e c u s t o m e r ’ s f i r s t n a m e , a v a r i a b l e n a m e d
address t o h o l d t h e c u s t o m e r ’ s m a i l i n g a d d r e s s , a n d s o f o r t h .
In C # , y o u m u s t d e c la r e a v a r ia b le in a p r o g r a m b e fo r e y o u c a n u s e it to s to r e d a ta . Y o u
d o th is w ith a v a r ia b le d e c la r a tio n , w h ic h s p e c ifie s tw o th in g s a b o u t th e v a r ia b le :
1 . T h e v a r ia b le ’s d a ta ty p e , w h ic h is th e ty p e o f d a ta th e v a r ia b le w ill h o ld
2 . T h e v a r ia b le ’s n a m e
A v a r ia b le d e c la r a tio n s ta te m e n t is w r itte n in th is g e n e r a l fo r m a t:
DataType VariableName;
L e t’s ta k e a c lo s e r lo o k a t e a c h o f th e s e .
D a t a T y p e
A v a r ia b le ’s d a ta ty p e in d ic a te s th e ty p e o f d a ta th a t th e v a r ia b le w ill h o ld . B e fo r e y o u d e c la r e
a v a r ia b le , y o u n e e d to th in k a b o u t th e ty p e o f v a lu e th a t w ill b e s to r e d in th e v a r ia b le . F o r
e x a m p le , w ill th e v a r ia b le h o ld a s tr in g o r a n u m b e r ? If it w ill h o ld a n u m b e r , w h a t k in d o f
n u m b e r w ill it b e , a n in te g e r o r a r e a l n u m b e r ? W h e n y o u h a v e d e te r m in e d th e k in d o f d a ta
th a t th e v a r ia b le w ill h o ld , y o u s e le c t o n e o f th e d a ta ty p e s th a t C # p r o v id e s fo r a v a r ia b le .
T h e C # la n g u a g e p r o v id e s m a n y d a ta ty p e s fo r s to r in g fu n d a m e n ta l ty p e s o f d a ta , s u c h a s
s tr in g s , in te g e r s , a n d r e a l n u m b e r s . T h e s e d a ta ty p e s a r e k n o w n a s p r im itiv e d a ta ty p e s .
W e w ill lo o k a t s e v e r a l o f th e m in th is c h a p te r .
V a r ia b le N a m e
A v a r ia b le n a m e id e n tifie s a v a r ia b le in th e p r o g r a m c o d e . W h e n n a m in g a v a r ia b le , y o u
s h o u ld a lw a y s c h o o s e a m e a n in g fu l n a m e th a t in d ic a te s w h a t th e v a r ia b le is u s e d fo r . F o r
e x a m p l e , a v a r i a b l e t h a t h o l d s t h e t e m p e r a t u r e m i g h t b e n a m e d temperature, a n d a
v a r i a b l e t h a t h o l d s a c a r ’ s s p e e d m i g h t b e n a m e d speed. Y o u m a y b e t e m p t e d t o g i v e
v a r i a b l e s s h o r t , n o n d e s c r i p t n a m e s s u c h a s x o r b2, b u t n a m e s s u c h a s t h e s e g i v e n o c l u e
a s to th e p u r p o s e o f th e v a r ia b le .
In a d d itio n , th e r e a r e s o m e s p e c ific r u le s th a t y o u m u s t fo llo w w h e n n a m in g a v a r ia b le .
T h e s a m e r u le s fo r id e n tifie r s th a t a p p ly to c o n tr o l n a m e s a ls o a p p ly to v a r ia b le n a m e s .
W e d is c u s s e d th e s e r u le s in C h a p te r 2 , b u t w e r e v ie w th e m n o w :
• T h e fir s t c h a r a c te r m u s t b e o n e o f th e le tte r s ath r o u g h zo r A th r o u g h Z o r a n
u n d e r s c o r e c h a r a c te r ( _).
3 .2
A F ir s t L o o k a t V a r ia b le s
• A f t e r t h e f i r s t c h a r a c t e r , y o u m a y u s e t h e l e t t e r s a t h r o u g h z o r A t h r o u g h Z, t h e
d ig its 0 th r o u g h 9 , o r u n d e r s c o r e s .
• T h e n a m e c a n n o t c o n ta in s p a c e s .
W h e n n a m in g v a r ia b le s , w e u s e th e s a m e c a m e lC a s e n a m in g c o n v e n tio n th a t w e in tr o d u c e d in C h a p te r 2 fo r c o n tr o l n a m e s . F o r e x a m p le , if w e a r e d e c la r in g a v a r ia b le to h o ld
a n e m p l o y e e ’ s g r o s s p a y , w e m i g h t n a m e i t grossPay. O r , i f a r e d e c l a r i n g a v a r i a b l e t o a
c u s t o m e r n u m b e r , w e m i g h t n a m e i t customerNumber.
string V a r i a b l e s
T h e f i r s t p r i m i t i v e d a t a t y p e w e c o n s i d e r i s t h e string d a t a t y p e . A v a r i a b l e o f t h e string
d a ta ty p e c a n h o ld a n y s tr in g o f c h a r a c te r s , s u c h a s a p e r s o n ’s n a m e , a d d r e s s , p a s s w o r d ,
a n d s o f o r t h . H e r e i s a n e x a m p l e o f a s t a t e m e n t t h a t d e c l a r e s a string v a r i a b l e n a m e d
productDescription:
string productDescription;
A f t e r t h e v a r i a b l e h a s b e e n d e c l a r e d , y o u c a n u s e t h e a s s i g n m e n t o p e r a t o r ( =) t o s t o r e a
v a lu e in th e v a r ia b le . H e r e is a n e x a m p le :
productDescription = "Italian Espresso Machine";
W h e n t h i s s t a t e m e n t e x e c u t e s , t h e s t r i n g l i t e r a l "Italian Espresso Machine" i s a s s i g n e d
t o t h e productDescription v a r i a b l e . W h e n w r i t i n g a n a s s i g n m e n t s t a t e m e n t , r e m e m b e r
th a t th e a s s ig n m e n t o p e r a to r a s s ig n s th e v a lu e th a t a p p e a r s o n its r ig h t s id e to th e v a r ia b le
th a t a p p e a r s o n its le ft s id e .
O n c e y o u h a v e a s s ig n e d a v a lu e to a v a r ia b le , y o u c a n u s e th e v a r ia b le in o th e r o p e r a t i o n s . F o r e x a m p l e , a s s u m e productLabel i s t h e n a m e o f a L a b e l c o n t r o l . T h e f o l l o w i n g s t a t e m e n t a s s i g n s t h e productDescription s t r i n g t o t h e productLabel c o n t r o l ’ s
Tex t p ro p erty:
productLabel.Text = productDescription;
A f t e r t h i s s t a t e m e n t e x e c u t e s , t h e s t r i n g t h a t i s s t o r e d i n t h e productDescription
v a r i a b l e i s d i s p l a y e d i n t h e productLabel c o n t r o l . T h e f o l l o w i n g s t a t e m e n t s h o w s
a n o th e r e x a m p le :
MessageBox.Show(productDescription);
W h e n t h i s s t a t e m e n t e x e c u t e s , t h e s t r i n g t h a t i s s t o r e d i n t h e productDescription v a r i a b le is d is p la y e d in a m e s s a g e b o x .
S t r in g C o n c a t e n a t io n
A c o m m o n o p e r a tio n th a t p e r fo r m e d o n s tr in g s is c o n c a te n a tio n , o r a p p e n d in g o n e s tr in g
to th e e n d o f a n o th e r s tr in g . In C # y o u u s e th e +o p e r a to r to c o n c a te n a te s tr in g s . T h e +
o p e r a to r p r o d u c e s a s tr in g th a t is th e c o m b in a tio n o f th e tw o s tr in g s u s e d a s its o p e r a n d s .
T h e fo llo w in g c o d e s h o w s a n e x a m p le :
string message;
message = "Hello " + "world";
MessageBox.Show(message);
T h e f i r s t s t a t e m e n t d e c l a r e s a string v a r i a b l e n a m e d message. T h e s e c o n d s t a t e m e n t
c o m b i n e s t h e s t r i n g s "Hello " a n d "world" t o p r o d u c e t h e s t r i n g "Hello world". T h e
s t r i n g "Hello world" i s t h e n a s s i g n e d t o t h e message v a r i a b l e . T h e t h i r d s t a t e m e n t d i s p l a y s t h e c o n t e n t s o f t h e message v a r i a b l e i n a m e s s a g e b o x . W h e n t h e m e s s a g e b o x i s
d i s p l a y e d , i t s h o w s t h e s t r i n g H ello world.
121
122
C h a p te r 3
P r o c e s s in g D a t a
L e t ’ s l o o k a t a n a p p l i c a t i o n t h a t f u r t h e r d e m o n s t r a t e s s t r i n g c o n c a t e n a t i o n . I n t h e Chap03
fo ld e r o f th is b o o k ’s s tu d e n t s a m p le p r o g r a m s (a v a ila b le fo r d o w n lo a d a t w w w .p e a r s o n h i g h e r e d . c o m / g a d d i s ) , y o u w i l l f i n d a p r o j e c t n a m e d String Variable D emo. F i g u r e 3 - 5
s h o w s th e fo r m , w ith m o s t o f th e c o n tr o l n a m e s s p e c ifie d , a n d F ig u r e 3 -6 s h o w s th e
fo r m ’s c o d e . (In F ig u r e 3 -6 , to c o n s e r v e s p a c e o n th e p a g e , w e h a v e s c r o lle d p a s t th e
using d i r e c t i v e s t h a t a p p e a r a t t h e t o p o f t h e c o d e f i l e . )
F ig u r e 3 -5
T h e String Va ria ble Demo a p p l i c a t i o n
firstNameTextBox
lastNameTextBox
fullNameLabel
showNameButton
F ig u r e 3 -6
exitButton
T h e f o r m ’ s c o d e ( e x c l u d i n g t h e using d i r e c t i v e s )
1
2
3
In F ig u r e 3 -6 , th r e e s ta te m e n ts in
p o in te d o u t:
1
t h e showNameButton_Click e v e n t h a n d l e r a r e
T h i s s t a t e m e n t i s a v a r i a b l e d e c l a r a t i o n . I t d e c l a r e s a string v a r i a b l e n a m e d
fullName.
2
T h i s s t a t e m e n t a s s i g n s t h e r e s u l t o f a s t r i n g c o n c a t e n a t i o n t o t h e fullName
v a r ia b le . T h e s tr in g th a t is a s s ig n e d to th e v a r ia b le b e g in s w ith th e v a lu e o f th e
firstNameTextBox c o n t r o l ’ s T e x t p r o p e r t y , f o l l o w e d b y a s p a c e ( " ") , f o l l o w e d
b y t h e v a l u e o f t h e lastNameTextBox c o n t r o l ’ s T e x t p r o p e r t y . F o r e x a m p l e , i f t h e
u s e r h a s e n t e r e d Joe i n t o t h e firstNameTextBox c o n t r o l a n d Smith i n t o
t h e lastNameTextBox c o n t r o l , t h i s s t a t e m e n t w i l l a s s i g n t h e s t r i n g "Joe Smith" t o
t h e fullName v a r i a b l e .
3 .2
3
A F ir s t L o o k a t V a r ia b le s
T h i s s t a t e m e n t a s s i g n s t h e fullName v a r i a b l e t o t h e fullNameLabel c o n t r o l ’ s T e x t
p r o p e r t y . A s a r e s u l t , t h e s t r i n g t h a t i s s t o r e d i n t h e fullName v a r i a b l e i s d i s p l a y e d
i n t h e fullNameLabel c o n t r o l .
If y o u r u n th e a p p lic a tio n , F ig u r e 3 -7 s h o w s a n e x a m p le o f h o w th e fo r m a p p e a r s a fte r
y o u h a v e e n t e r e d Chris f o r t h e f i r s t n a m e a n d Jones f o r t h e l a s t n a m e a n d c l i c k e d t h e
showNameButton c o n t r o l .
F ig u r e 3 -7
T h e u s e r ’ s fu ll n a m e d is p la y e d in t h e la b e l
D e c la r in g V a r ia b le s b e fo r e U s in g T h e m
T h e p u r p o s e o f a v a r ia b le d e c la r a tio n s ta te m e n t is to te ll th e c o m p ile r th a t y o u p la n to u s e
a v a r ia b le o f a s p e c ifie d n a m e to s to r e a p a r tic u la r ty p e o f d a ta in th e p r o g r a m . A v a r ia b le
d e c la r a tio n s ta te m e n t c a u s e s th e v a r ia b le to b e c r e a te d in m e m o r y . F o r th is r e a s o n , a
v a r i a b l e ’ s d e c l a r a t i o n s t a t e m e n t m u s t a p p e a r before a n y o t h e r s t a t e m e n t s i n t h e m e t h o d
th a t u s e th e v a r ia b le . T h is m a k e s p e r fe c t s e n s e b e c a u s e y o u c a n n o t s to r e a v a lu e in a
v a r ia b le if th e v a r ia b le h a s n o t b e e n c r e a te d in m e m o r y .
L o c a l V a r ia b le s
N o t i c e t h a t t h e fullName v a r i a b l e i n F i g u r e 3 - 6 i s d e c l a r e d i n s i d e t h e e v e n t h a n d l e r
m e th o d . V a r ia b le s th a t a r e d e c la r e d in s id e a m e th o d a r e k n o w n a s lo c a l v a r ia b le s . A lo c a l
v a r ia b le b e lo n g s to th e m e th o d in w h ic h it is d e c la r e d , a n d o n ly s ta te m e n ts in s id e th a t
m e t h o d c a n a c c e s s t h e v a r i a b l e . ( T h e t e r m local i s m e a n t t o i n d i c a t e t h a t t h e v a r i a b l e c a n
b e u s e d o n ly lo c a lly , w ith in th e m e th o d in w h ic h it is d e c la r e d .)
A n e r r o r w ill o c c u r if a s ta te m e n t in o n e m e th o d tr ie s to a c c e s s a lo c a l v a r ia b le th a t b e lo n g s
to a n o th e r m e th o d . F o r e x a m p le , le t’s g o o v e r th e s a m p le c o d e s h o w n in F ig u r e 3 -8 :
1
T h i s s t a t e m e n t d e c l a r e s a string v a r i a b l e n a m e d myName. T h e v a r i a b l e i s d e c l a r e d
i n s i d e t h e firstButton_Click e v e n t h a n d l e r , s o i t i s l o c a l t o t h a t m e t h o d .
F ig u r e 3 -8
O n e m e t h o d t r y in g t o a c c e s s a v a r ia b le t h a t is lo c a l t o a n o t h e r m e t h o d
1
2
3
ERROR!
123
124
C h a p te r 3
P r o c e s s in g D a t a
2
3
T h i s s t a t e m e n t , w h i c h i s a l s o i n t h e firstButton_Click e v e n t h a n d l e r , a s s i g n s t h e
nameTextBox c o n t r o l ’ s T e x t p r o p e r t y t o t h e myName v a r i a b l e .
T h i s s t a t e m e n t , w h i c h i s i n t h e secondButton_Click e v e n t h a n d l e r , attempts t o
a s s i g n t h e myName v a r i a b l e t o t h e outputLabel c o n t r o l ’ s T e x t p r o p e r t y . T h i s
s t a t e m e n t w i l l n o t w o r k , h o w e v e r , b e c a u s e t h e myName v a r i a b l e i s l o c a l t o t h e
firstButton_Click e v e n t h a n d l e r , a n d s t a t e m e n t s i n t h e secondButton_Click
e v e n t h a n d le r c a n n o t a c c e s s it.
S c o p e o f a V a r ia b le
P r o g r a m m e r s u s e th e te r m s c o p e to d e s c r ib e th e p a r t o f a p r o g r a m in w h ic h a v a r ia b le
m a y b e a c c e s s e d . A v a r ia b le is v is ib le o n ly to s ta te m e n ts in s id e th e v a r ia b le ’s s c o p e .
A lo c a l v a r ia b le ’s s c o p e b e g in s a t th e v a r ia b le ’s d e c la r a tio n a n d e n d s a t th e e n d o f th e
m e th o d in w h ic h th e v a r ia b le is d e c la r e d . A s y o u s a w in th e p r e v io u s e x a m p le , a lo c a l
v a r ia b le c a n n o t b e a c c e s s e d b y s ta te m e n ts th a t a r e o u ts id e th e m e th o d . In a d d itio n , a
lo c a lv a r ia b le c a n n o t b e a c c e s s e d b y c o d e th a t is in s id e th e m e th o d b u t b e fo r e th e v a r ia b le ’s d e c la r a tio n .
L ife t im e o f a V a r ia b le
A v a r ia b le ’s life tim e is th e tim e p e r io d d u r in g w h ic h th e v a r ia b le e x is ts in m e m o r y w h ile
th e p r o g r a m is e x e c u tin g . A lo c a l v a r ia b le is c r e a te d in m e m o r y w h e n th e m e th o d in
w h ic h it is d e c la r e d s ta r ts e x e c u tin g . W h e n th e m e th o d e n d s , a ll th e m e th o d ’s lo c a l v a r ia b le s a r e d e s tr o y e d . S o , a lo c a l v a r ia b le ’s life tim e is th e tim e d u r in g w h ic h th e m e th o d in
w h ic h it is d e c la r e d is e x e c u tin g .
D u p lic a t e V a r ia b le N a m e s
Y o u c a n n o t d e c la r e tw o v a r ia b le s w ith th e s a m e n a m e in th e s a m e s c o p e . F o r e x a m p le , if
y o u d e c l a r e a v a r i a b l e n a m e d productDescription i n a n e v e n t h a n d l e r , y o u c a n n o t
d e c la r e a n o th e r v a r ia b le w ith th a t n a m e in th e s a m e e v e n t h a n d le r . Y o u c a n , h o w e v e r ,
h a v e v a r ia b le s o f th e s a m e n a m e d e c la r e d in d iffe r e n t m e th o d s .
A s s ig n m e n t C o m p a t ib ilit y
Y o u c a n a s s ig n a v a lu e to a v a r ia b le o n ly if th e v a lu e is c o m p a tib le w ith th e v a r ia b le ’s
d a t a t y p e . O n l y s t r i n g s a r e c o m p a t i b l e w i t h t h e string d a t a t y p e , s o a l l t h e a s s i g n m e n t s
in th e fo llo w in g c o d e s a m p le w o r k :
1 // Declare and initialize a string variable.
2 string productDescription = "Chocolate Truffle";
3
4 // Declare another string variable.
5 string myFavoriteProduct;
6
7 // Assign a value to a string variable.
8 myFavoriteProduct = productDescription;
9
10 // Assign a value from a TextBox to a string variable.
11 productDescription = userInputTextBox.Text;
T h e fo llo w in g c o m m e n ts e x p la in th e s e lin e s o f c o d e :
• I n l i n e 2 w e i n i t i a l i z e a string v a r i a b l e w i t h a s t r i n g l i t e r a l . T h i s w o r k s b e c a u s e
s t r i n g l i t e r a l s a r e a s s i g n m e n t c o m p a t i b l e w i t h string v a r i a b l e s .
3 .2
A F ir s t L o o k a t V a r ia b le s
• I n l i n e 8 , w e a s s i g n a string v a r i a b l e t o a n o t h e r string v a r i a b l e . T h i s w o r k s f o r t h e
o b v i o u s r e a s o n t h a t string v a r i a b l e s a r e c o m p a t i b l e w i t h o t h e r string v a r i a b l e s .
• A s s u m e t h a t t h e a p p l i c a t i o n h a s a T e x t B o x c o n t r o l n a m e d userInputTextBox. I n
l i n e 1 1 , w e a s s i g n t h e v a l u e o f t h e T e x t B o x c o n t r o l ’ s T e x t p r o p e r t y t o a string
v a r ia b le . T h is w o r k s b e c a u s e th e v a lu e in a c o n tr o l’s T e x t p r o p e r ty is a lw a y s a
s tr in g .
T h e fo llo w in g c o d e w ill n o t w o r k , h o w e v e r , b e c a u s e it a tte m p ts to a s s ig n a n o n s tr in g
v a l u e t o a string v a r i a b l e :
1 // Declare a string variable.
2 string employeeID;
3
4 // Assign a value to the variable. Will this work?
5 employeeID = 125; d ERROR!
I n l i n e 5 , w e a r e a t t e m p t i n g t o a s s i g n t h e n u m b e r 1 2 5 t o a string v a r i a b l e . N u m b e r s a r e
n o t a s s i g n m e n t c o m p a t i b l e w i t h string v a r i a b l e s , s o t h i s s t a t e m e n t w i l l c a u s e a n e r r o r
w h e n th e c o d e is c o m p ile d .
N O T E : A l t h o u g h y o u c a n n o t s t o r e t h e n u m b e r 1 2 5 i n a string v a r i a b l e , y o u c a n
s t o r e t h e s t r i n g l i t e r a l "125" i n a string v a r i a b l e .
A V a r ia b le H o ld s O n e V a lu e a t a T im e
V a r ia b le s c a n h o ld d iffe r e n t v a lu e s w h ile a p r o g r a m is r u n n in g , b u t th e y c a n h o ld o n ly
o n e v a lu e a t a tim e . W h e n y o u a s s ig n a v a lu e to a v a r ia b le , th a t v a lu e w ill r e m a in in th e
v a r ia b le u n til y o u a s s ig n a d iffe r e n t v a lu e to th e v a r ia b le . F o r e x a m p le , lo o k a t th e fo llo w in g c o d e s a m p le :
1 // Declare a string variable.
2 string productDescription;
3
4 // Assign a value to the variable.
5 productDescription = "Large Medium-Roast Coffee";
6
7 // Display the variable’s value.
8 MessageBox.Show(productDescription);
9
10 // Assign a different value to the variable.
11 productDescription = "Chocolate Truffle";
12
13 // Display the variable’s value.
14 MessageBox.Show(productDescription);
T h e fo llo w in g c o m m e n ts e x p la in w h a t w e d id :
• L i n e 2 d e c l a r e s a string v a r i a b l e n a m e d productDescription.
• L i n e 5 a s s i g n s t h e s t r i n g "Large Medium-Roast Coffee" t o t h e productDescription
v a r ia b le .
• L i n e 8 d i s p l a y s t h e v a l u e o f t h e productDescription v a r i a b l e i n a m e s s a g e b o x .
( T h e m e s s a g e b o x w i l l d i s p l a y L arge M edium-Roast Coffee. )
• L i n e 1 1 a s s i g n s a d i f f e r e n t v a l u e t o t h e productDescription v a r i a b l e . A f t e r t h i s
s t a t e m e n t e x e c u t e s , t h e productDescription v a r i a b l e w i l l h o l d t h e s t r i n g
"Chocolate Truffle".
• L i n e 1 4 d i s p l a y s t h e v a l u e o f t h e productDescription v a r i a b l e i n a m e s s a g e b o x .
( T h e m e s s a g e b o x w i l l d i s p l a y Chocolate Truffle. )
125
126
C h a p te r 3
P r o c e s s in g D a t a
T h is c o d e s a m p le illu s tr a te s tw o im p o r ta n t c h a r a c te r is tic s o f v a r ia b le s :
• A v a r ia b le h o ld s o n ly o n e v a lu e a t a tim e .
• W h e n y o u s to r e a v a lu e in a v a r ia b le , th a t v a lu e r e p la c e s th e p r e v io u s v a lu e th a t w a s
in th e v a r ia b le .
T u to r ia l 3 -1 g iv e s y o u s o m e p r a c tic e u s in g v a r ia b le s . Y o u w ill c r e a te a n a p p lic a tio n th a t
u s e s T e x tB o x c o n tr o ls to g e t in p u t v a lu e s , s to r e s th o s e v a lu e s in v a r ia b le s , a n d u s e s th e
v a r ia b le s in o p e r a tio n s .
T u t o r ia l 3 -1 :
T h e Birth Da te String A p p l i c a t i o n
VideoNot e
T u to r ia l 3 -1 :
T h e Birth
D ate String
A p p lic a tio n
In th is tu to r ia l, y o u c r e a te a n a p p lic a tio n th a t le ts th e u s e r e n te r th e fo llo w in g in fo r m a tio n
a b o u t h is o r h e r b ir th d a te :
•
•
•
•
T h e d a y o f th e w e e k (M o n d a y , T u e s d a y , e tc .)
T h e n a m e o f th e m o n th (J a n u a r y , F e b r u a r y , e tc .)
T h e n u m e r ic d a y o f th e m o n th
Th e year
F ig u r e 3 -9 s h o w s th e a p p lic a tio n ’s fo r m , a lo n g w ith th e n a m e s o f a ll th e c o n tr o ls .
W h e n th e a p p lic a tio n r u n s , th e u s e r e n te r s e a c h p ie c e o f d a ta in to a s e p a r a te T e x tB o x .
W h e n t h e u s e r c l i c k s t h e Show D ate b u t t o n , t h e a p p l i c a t i o n c o n c a t e n a t e s t h e c o n t e n t s
o f t h e T e x t B o x e s i n t o a s t r i n g s u c h a s Friday, June 1, 1990. T h e s t r i n g i s d i s p l a y e d
i n t h e dateOutputLabel c o n t r o l . W h e n t h e u s e r c l i c k s t h e Clear b u t t o n , t h e c o n t e n t s
o f t h e T e x t B o x e s a n d t h e dateOutputLabel c o n t r o l a r e c l e a r e d . T h e Exit b u t t o n
c lo s e s th e a p p lic a tio n ’s fo r m .
F ig u r e 3 -9
T h e Birth Da te String f o r m
dayOfWeekPromptLabel
monthPromptLabel
dayOfWeekTextBox
dayOfmonthPromptLabel
dayOfMonthTextBox
monthTextBox
yearTextBox
yearPromptLabel
dateOutputLabel
showDateButton
clearButton
exitButton
S t e p 1 :
S ta r t V is u a l S tu d io a n d b e g in a n e w W in d o w s F o r m s A p p lic a tio n p r o je c t
n a m e d Birth D ate String.
S t e p 2 :
S e t u p th e a p p lic a tio n ’s fo r m a s s h o w n in F ig u r e 3 -9 . N o tic e th a t th e fo r m ’s
T e x t p r o p e r t y i s s e t t o Birth D ate String. T h e n a m e s o f t h e c o n t r o l s a r e s h o w n
in th e fig u r e . A s y o u p la c e e a c h c o n tr o l o n th e fo r m , r e fe r to T a b le 3 -1 fo r th e
r e le v a n t p r o p e r ty s e ttin g s .
3 .2
T a b le 3 -1
A F ir s t L o o k a t V a r ia b le s
C o n t r o l p r o p e r t y s e t t in g s
Co n tro l Name
Co n tro l Typ e
P r o p e r ty S e ttin g s
dayOfWeekPromptLabel
Lab el
T e x t : Enter the day of the week
monthPromptLabel
Lab el
T e x t : Enter the name of the month
dayOfMonthPromptLabel
Lab el
T e x t : Enter the numeric day of the month
yearPromptLabel
Lab el
T e x t : Enter the year
dayOfWeekTextBox
Tex tBo x
N o p r o p e r tie s c h a n g e d
monthTextBox
Tex tBo x
N o p r o p e r tie s c h a n g e d
dayOfMonthTextBox
Tex tBo x
N o p r o p e r tie s c h a n g e d
yearTextBox
Tex tBo x
N o p r o p e r tie s c h a n g e d
dateOutputLabel
Lab el
A u to S iz e : F a ls e
B o r d e r S ty le : F ix e d S in g le
Tex t: (Th e co n ten ts o f th e Tex t p ro p erty
h a v e b e e n e r a s e d .)
T e x tA lig n : M id d le C e n te r
showDateButton
Bu tto n
T e x t : Show D ate
clearButton
Bu tto n
T e x t : Clear
exitButton
Bu tto n
T e x t : Exit
S t e p 3 :
O n c e y o u h a v e s e t u p th e fo r m w ith its c o n tr o ls , y o u c a n c r e a te th e C lic k
e v e n t h a n d le r s fo r th e B u tto n c o n tr o ls . A t th e e n d o f th is tu to r ia l, P r o g r a m
3 -1 s h o w s th e c o m p le te d c o d e fo r th e fo r m . Y o u w ill b e in s tr u c te d to r e fe r to
P r o g r a m 3 -1 a s y o u w r ite th e e v e n t h a n d le r s . (R e m e m b e r , th e lin e n u m b e r s
th a t a r e s h o w n in P r o g r a m 3 -1 a r e n o t p a r t o f th e p r o g r a m . T h e y a r e s h o w n
fo r r e fe r e n c e o n ly .)
I n t h e Designer, d o u b l e - c l i c k t h e showDateButton c o n t r o l . T h i s w i l l o p e n t h e
c o d e e d i t o r , a n d y o u w i l l s e e a n e m p t y e v e n t h a n d l e r n a m e d showDateButton_
Click. C o m p l e t e t h e showDateButton_Click e v e n t h a n d l e r b y t y p i n g t h e c o d e
s h o w n in lin e s 2 2 – 3 2 in P r o g r a m 3 -1 .
L e t’s ta k e a c lo s e r lo o k a t th e c o d e :
L i n e 2 3 : T h i s s t a t e m e n t d e c l a r e s a string v a r i a b l e n a m e d output.
L in e s 2 6 – 2 9 : T h e s e lin e s a r e a c tu a lly o n e lo n g s ta te m e n t, b r o k e n u p in to m u ltip le lin e s . T h e s ta te m e n t c o n c a te n a te s th e T e x t p r o p e r tie s o f th e T e x tB o x
c o n tr o ls , a lo n g w ith a p p r o p r ia te ly p la c e d c o m m a s a n d s p a c e s , to c r e a te th e
d a t e s t r i n g . T h e r e s u l t i n g s t r i n g i s a s s i g n e d t o t h e output v a r i a b l e .
F o r e x a m p le , s u p p o s e th e u s e r h a s e n te r e d th e fo llo w in g in p u t:
•
•
•
•
Friday i n t h e dayOfWeekTextBox c o n t r o l .
June i n t h e monthTextBox c o n t r o l .
1 i n t h e dayOfMonthTextBox c o n t r o l .
1990 i n t h e yearTextBox c o n t r o l .
T h e c o n c a te n a tio n in th is s ta te m e n t p r o d u c e s th e s tr in g “ J u n e 1 , 1 9 9 0 ” ; it is
a s s i g n e d t o t h e output v a r i a b l e .
L i n e 3 2 : T h i s s t a t e m e n t a s s i g n s t h e output v a r i a b l e t o t h e dateOutputLabel
c o n tr o l’s T e x t p r o p e r ty . W h e n th is s ta te m e n t e x e c u te s , th e c o n te n ts o f th e
output v a r i a b l e a r e d i s p l a y e d i n t h e dateOutputLabel c o n t r o l .
127
128
C h a p te r 3
P r o c e s s in g D a t a
S t e p 4 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e clearButton
c o n tr o l. In th e c o d e e d ito r , y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
clearButton_Click. C o m p l e t e t h e clearButton_Click e v e n t h a n d l e r b y
ty p in g th e c o d e s h o w n in lin e s 3 7 – 4 4 in P r o g r a m 3 -1 .
L e t’s ta k e a c lo s e r lo o k a t th e c o d e :
L i n e s 3 8 – 4 1 : E a c h s t a t e m e n t a s s i g n s a n e m p t y s t r i n g ( "") t o t h e T e x t p r o p e r ty o f o n e o f th e T e x tB o x c o n tr o ls . W h e n th e s e s ta te m e n ts h a v e fin is h e d
e x e c u tin g , th e T e x tB o x c o n tr o ls w ill a p p e a r e m p ty .
L i n e 4 4 : T h i s s t a t e m e n t a s s i g n s a n e m p t y s t r i n g ( "") t o t h e dateOutputLabel
c o n tr o l’s T e x t p r o p e r ty . A fte r th e s ta te m e n t h a s e x e c u te d , th e la b e l a p p e a r s
emp ty.
S t e p 5 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e exitButton
c o n t r o l . I n t h e c o d e e d i t o r , y o u w i l l s e e a n e m p t y e v e n t h a n d l e r n a m e d exitButton_Click. C o m p l e t e t h e exitButton_Click e v e n t h a n d l e r b y t y p i n g
th e c o d e s h o w n in lin e s 4 9 – 5 0 in P r o g r a m 3 -1 .
S t e p 6 :
S a v e t h e p r o j e c t . T h e n , p r e s s t h e F 5 k e y o n t h e k e y b o a r d , o r c l i c k t h e Start
D ebugging b u t t o n ( ) o n t h e t o o l b a r t o c o m p i l e a n d r u n t h e a p p l i c a t i o n .
T h e fo r m w ill a p p e a r a s s h o w n in th e im a g e o n th e le ft in F ig u r e 3 -1 0 . T e s t
t h e a p p l i c a t i o n b y e n t e r i n g v a l u e s i n t o t h e T e x t B o x e s a n d c l i c k i n g t h e Show
D ate b u t t o n . T h e d a t e s h o u l d b e d i s p l a y e d , s i m i l a r t o t h e i m a g e s h o w n
o n t h e r i g h t i n t h e f i g u r e . C l i c k t h e Clear b u t t o n , a n d t h e c o n t e n t s o f t h e
T e x t B o x e s a n d t h e L a b e l c o n t r o l s h o u l d c l e a r . C l i c k t h e Exit b u t t o n a n d t h e
fo r m s h o u ld c lo s e .
F ig u r e 3 -1 0
T h e Birth Da te String a p p l i c a t i o n
P r o g r a m 3 -1
C o m p l e t e d F o r m 1 c o d e f o r t h e Birth Da te String a pplica tion
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Birth_Date_String
3 .2
12 {
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 }
A F ir s t L o o k a t V a r ia b le s
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void showDateButton_Click(object sender, EventArgs e)
{
// Declare a string variable.
string output;
// Concatenate the input and build the output string.
output = dayOfWeekTextBox.Text + ", " +
monthTextBox.Text + " " +
dayOfMonthTextBox.Text + ", " +
yearTextBox.Text;
// Display the output string in the Label control.
dateOutputLabel.Text = output;
}
private void clearButton_Click(object sender, EventArgs e)
{
// Clear the TextBoxes.
dayOfWeekTextBox.Text = "";
monthTextBox.Text = "";
dayOfMonthTextBox.Text = "";
yearTextBox.Text = "";
// Clear the dateOutputLabel control.
dateOutputLabel.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
N O T E : In T u to r ia l 3 -1 , th e s ta te m e n t in lin e s 2 6 – 2 9 s h o w s a n e x a m p le o f h o w y o u
c a n b r e a k u p a s ta te m e n t in to m u ltip le lin e s . Q u ite o fte n , y o u w ill fin d y o u r s e lf w r iti n g s t a t e m e n t s t h a t a r e t o o l o n g t o f i t e n t i r e l y i n s i d e t h e Code w i n d o w . Y o u r c o d e w i l l
b e h a r d t o r e a d i f y o u h a v e t o h o r i z o n t a l l y s c r o l l t h e Code w i n d o w t o v i e w l o n g s t a t e m e n ts . In a d d itio n , if y o u o r y o u r in s tr u c to r c h o o s e s to p r in t y o u r c o d e , th e s ta te m e n ts th a t a r e to o lo n g to fit o n o n e lin e o f th e p a g e w ill w r a p a r o u n d to th e n e x t lin e
a n d m a k e y o u r c o d e lo o k u n o r g a n iz e d . F o r th e s e r e a s o n s , it is u s u a lly b e s t to b r e a k a
lo n g s ta te m e n t in to m u ltip le lin e s .
W h e n ty p in g m o s t s ta te m e n ts , y o u c a n s im p ly p r e s s th e E n te r k e y w h e n y o u r e a c h a n
a p p r o p r ia te p o in t to c o n tin u e th e s ta te m e n t o n th e n e x t lin e . R e m e m b e r , h o w e v e r ,
th a t y o u c a n n o t b r e a k u p a k e y w o r d , a q u o te d s tr in g , o r a n id e n tifie r (s u c h a s a v a r ia b le n a m e o r a c o n tr o l n a m e ).
129
130
C h a p te r 3
P r o c e s s in g D a t a
In it ia liz in g V a r ia b le s
In C # , a v a r ia b le m u s t b e a s s ig n e d a v a lu e b e fo r e it c a n b e u s e d . F o r e x a m p le , lo o k a t
th is c o d e :
string productDescription;
MessageBox.Show(productDescription);
T h i s c o d e d e c l a r e s a string v a r i a b l e n a m e d productDescription a n d t h e n t r i e s t o d i s p la y th e v a r ia b le ’s v a lu e in a m e s s a g e b o x . T h e o n ly p r o b le m is th a t w e h a v e n o t a s s ig n e d
a v a lu e to th e v a r ia b le . W h e n w e c o m p ile th e a p p lic a tio n c o n ta in in g th is c o d e , w e w ill g e t
a n e r r o r m e s s a g e s u c h a s Use of unassigned local variable ‘productD escription’. T h e C #
c o m p ile r w ill n o t c o m p ile c o d e th a t tr ie s to u s e a n u n a s s ig n e d v a r ia b le .
O n e w a y to m a k e s u r e th a t a v a r ia b le h a s b e e n a s s ig n e d a v a lu e is to in itia liz e th e v a r ia b le w ith a v a lu e w h e n y o u d e c la r e it. F o r e x a m p le , th e fo llo w in g s ta te m e n t d e c la r e s a
string v a r i a b l e n a m e d productDescription a n d i m m e d i a t e l y a s s i g n s t h e s t r i n g l i t e r a l
"Chocolate Truffle" t o i t :
string productDescription = "Chocolate Truffle";
W e s a y t h a t t h i s s t a t e m e n t initializes t h e productDescription v a r i a b l e w i t h
"Chocolate Truffle". H e r e i s a n o t h e r e x a m p l e :
th e s tr in g
string lastName = lastNameTextBox.Text;
A s s u m e th a t th is s ta te m e n t b e lo n g s to a n a p p lic a tio n th a t h a s a T e x tB o x n a m e d
lastNameTextBox . T h e s t a t e m e n t d e c l a r e s a string v a r i a b l e n a m e d lastName a n d
i n i t i a l i z e s i t w i t h t h e v a l u e o f t h e lastNameTextBox c o n t r o l ’ s T e x t p r o p e r t y .
D e c la r in g M u lt ip le V a r ia b le s w it h O n e S t a t e m e n t
Y o u c a n d e c la r e m u ltip le v a r ia b le s o f th e s a m e d a ta ty p e w ith o n e d e c la r a tio n s ta te m e n t.
H e r e is a n e x a m p le :
string lastName, firstName, middleName;
T h i s s t a t e m e n t d e c l a r e s t h r e e string v a r i a b l e s n a m e d lastName , firstName , a n d
middleName. N o t i c e t h a t c o m m a s s e p a r a t e t h e v a r i a b l e n a m e s . H e r e i s a n e x a m p l e o f
h o w w e c a n d e c la r e a n d in itia liz e th e v a r ia b le s w ith o n e s ta te m e n t:
string lastName = "Jones", firstName = "Jill", middleName = "Rebecca";
R e m e m b e r , y o u c a n b r e a k u p a lo n g s ta te m e n t s o it s p r e a d s a c r o s s tw o o r m o r e lin e s .
S o m e tim e s y o u w ill s e e lo n g v a r ia b le d e c la r a tio n s w r itte n a c r o s s m u ltip le lin e s ,
lik e th is :
string lastName = "Jones",
firstName = "Jill",
middleName = "Rebecca";
C h e c k p o in t
3 .5
W h a t is th e p u r p o s e o f a v a r ia b le ?
3 .6
G iv e a n e x a m p le o f a v a r ia b le d e c la r a tio n
fa v o r ite fo o d .
th a t w ill s to r e th e n a m e o f y o u r
3 .3
3 .7
N u m e r ic D a t a T y p e s a n d V a r ia b le s
F o r e a c h o f th e fo llo w in g ite m s , d e te r m in e w h e th e r th e d a ta ty p e s h o u ld b e a n
in te g e r , s tr in g , o r r e a l n u m b e r .
a. p et n ame
b . s a le s ta x
c . m a ilin g a d d r e s s
d . v id e o g a m e s c o r e
3 .8
In d ic a te w h e th e r e a c h
e x p la in w h y .
o f th e fo llo w in g is a le g a l v a r ia b le n a m e . If it is n o t,
a . pay_Rate
b . speed of sound
c . totalCost
d . 2ndPlaceName
3 .9
W h a t w ill b e s to r e d
is e x e c u te d ?
in
t h e message v a r i a b l e a f t e r t h e f o l l o w i n g s t a t e m e n t
string message = "He" + "ll" + "o!";
3 .1 0
W h a t is th e life tim e o f a v a r ia b le th a t is d e c la r e d in s id e o f a C lic k e v e n t h a n d le r ?
3 .1 1
A s s u m i n g t h e v a r i a b l e greeting h a s n o t b e e n a s s i g n e d a v a l u e , w h a t w i l l b e t h e
r e s u lt o f th e fo llo w in g s ta te m e n t?
MessageBox.Show(greeting);
3 .1 2
W ill th e fo llo w in g s ta te m e n t c a u s e a n e r r o r ? W h y o r w h y n o t?
string luckyNumber = 7;
3 .1 3
3 .3
W r i t e a s i n g l e d e c l a r a t i o n s t a t e m e n t f o r t h e v a r i a b l e s name, city, a n d state.
N u m e r ic D a t a T y p e s a n d V a r ia b le s
C O N C E P T :
If y o u n e e d to s to r e a n u m b e r in a v a r ia b le a n d u s e th a t n u m b e r in a
m a th e m a tic a l o p e r a tio n , th e v a r ia b le m u s t b e o f a n u m e r ic d a ta ty p e . Y o u
s e le c t a n u m e r ic d a ta ty p e th a t is a p p r o p r ia te fo r th e ty p e o f n u m b e r th a t
yo u n eed to sto re.
I n t h e p r e v i o u s s e c t i o n , y o u r e a d a b o u t string v a r i a b l e s . V a r i a b l e s o f t h e string d a t a
ty p e c a n b e u s e d to s to r e te x t, b u t th e y c a n n o t s to r e n u m e r ic d a ta fo r th e p u r p o s e o f p e r fo r m in g m a th e m a tic a l o p e r a tio n s . If y o u n e e d to s to r e n u m b e r s a n d p e r fo r m m a th e m a tic a l o p e r a tio n s o n th e m , y o u h a v e to u s e a n u m e r ic d a ta ty p e .
T h e C # la n g u a g e p r o v id e s s e v e r a l p r im itiv e d a ta ty p e s . Y o u c a n r e a d a b o u t a ll th e C #
p r im itiv e d a ta ty p e s in A p p e n d ix A . M a n y o f th e d a ta ty p e s p r o v id e d b y C # a r e fo r s p e c ia liz e d p u r p o s e s b e y o n d th e s c o p e o f th is b o o k . W h e n it c o m e s to n u m e r ic d a ta , m o s t o f
th e tim e y o u w ill u s e th e th r e e n u m e r ic p r im itiv e d a ta ty p e s d e s c r ib e d in T a b le 3 -2 .
H e r e a r e e x a m p le s o f d e c la r in g v a r ia b le s o f e a c h d a ta ty p e :
int speed;
double distance;
decimal grossPay;
T h e f i r s t s t a t e m e n t d e c l a r e s a n int v a r i a b l e n a m e d speed. T h e s e c o n d e x a m p l e d e c l a r e s a
double v a r i a b l e n a m e d distance . T h e t h i r d s t a t e m e n t d e c l a r e s a decimal v a r i a b l e
n a m e d grossPay.
131
132
C h a p te r 3
P r o c e s s in g D a t a
T a b le 3 -2
T h e p r im it iv e n u m e r ic d a t a t y p e s t h a t y o u w ill u s e m o s t o ft e n
Data Typ e
D e s c r ip tio n
int
A v a r i a b l e o f t h e int d a t a t y p e c a n h o l d w h o l e n u m b e r s o n l y . F o r
e x a m p l e , a n int variable can hold values such as 42, 0, and −99.
An int variable cannot hold numbers with a fractional part, such
as 22.1 or −4.9.
The int data type is the primary data type for storing integers.
We use it in this book any time we need to store and work with
integers. An int variable uses 32 bits of memory and can hold an
integer number in the range of −2,147,483,648 through
2,147,483,647.
double
A variable of the double data type can hold real numbers, such as
3.5, −87.95, or 3.0. A number that is stored in a double variable
is rounded to 15 digits of precision.
We use variables of the double data type to store any number
that might have a fractional part. The double data type is
especially useful for storing extremely great or extremely
small numbers.
In memory a double variable uses 64 bits of memory. It is stored
in a format that programmers call double precision floating-point
notation. Variables of the double data type can hold numbers in
the range of ±5.0 × 102324 to ±1.7 × 10308.
decimal
A variable of the decimal data type can hold real numbers with
greater precision than the double data type. A number that is
stored in a decimal variable is rounded to 28 digits of precision.
Because decimal variables store real numbers with a great deal of
precision, they are most commonly used in financial applications.
In this book, we typically use the decimal data type when storing
amounts of money.
In memory a decimal variable uses 128 bits of memory. It is
stored in a format that programmers call decimal notation.
Variables of the decimal data type can hold numbers in the range
of ±1.0 × 10228 to ±7.9 × 1028.
N u m e r ic L it e r a ls
You learned in Chapter 2 that a literal is a piece of data written into a program’s code.
When you know, at the time that you are writing a program’s code, that you want to
store a specific value in a variable, you can assign that value as a literal to the variable.
A n u m e r i c l i t e r a l is a number that is written into a program’s code. For example, the following statement declares an int variable named hoursWorked and initializes it with the
value 40:
int hoursWorked = 40;
In this statement, the number 40 is a numeric literal. The following shows another
example:
double temperature = 87.6;
3 .3
N u m e r ic D a t a T y p e s a n d V a r ia b le s
T h i s s t a t e m e n t d e c l a r e s a double v a r i a b l e n a m e d temperature a n d i n i t i a l i z e s i t w i t h t h e
v a lu e 8 7 .6 . T h e n u m b e r 8 7 .6 is a n u m e r ic lite r a l.
W h e n y o u w r ite a n u m e r ic lite r a l in a p r o g r a m ’s c o d e , th e n u m e r ic lite r a l is a s s ig n e d a
d a ta ty p e . In C # , if a n u m e r ic lite r a l is a n in te g e r (n o t w r itte n w ith a d e c im a l p o in t) a n d it
f i t s w i t h i n t h e r a n g e o f a n int ( s e e T a b l e 3 - 2 f o r t h e m i n i m u m a n d m a x i m u m v a l u e s ) ,
t h e n t h e n u m e r i c l i t e r a l i s t r e a t e d a s a n int. A n u m e r i c l i t e r a l t h a t i s t r e a t e d a s a n int i s
c a lle d a n in te g e r lite r a l. F o r e x a m p le , e a c h o f th e fo llo w in g s ta te m e n ts in itia liz e s a v a r ia b le
w ith a n in te g e r lite r a l:
int hoursWorked = 40;
int unitsSold = 650;
int score = −23;
If a n u m e r ic lite r a l is w r itte n w ith a d e c im a l p o in t a n d it fits w ith in th e r a n g e o f a
double ( s e e T a b l e 3 - 2 f o r t h e m i n i m u m a n d m a x i m u m v a l u e s ) , t h e n t h e n u m e r i c l i t e r a l
i s t r e a t e d a s a double. A n u m e r i c l i t e r a l t h a t i s t r e a t e d a s a double i s c a l l e d a double
lite r a l. F o r e x a m p le , e a c h o f th e fo llo w in g s ta te m e n ts in itia liz e s a v a r ia b le w ith a
double l i t e r a l :
double distance = 28.75;
double speed = 87.3;
double temperature = −10.0;
W h e n y o u a p p e n d t h e l e t t e r M o r m t o a n u m e r i c l i t e r a l , i t i s t r e a t e d a s a decimal a n d i s
r e f e r r e d t o a s a decimal l i t e r a l . H e r e a r e s o m e e x a m p l e s :
decimal payRate = 28.75m;
decimal price = 8.95M;
decimal profit = −50m;
T I P : B e c a u s e decimal i s t h e p r e f e r r e d d a t a t y p e f o r s t o r i n g m o n e t a r y a m o u n t s ,
r e m e m b e r i n g t h a t “ m ” s t a n d s f o r “ m o n e y ” m i g h t h e l p y o u t o r e m e m b e r t h a t decimal
l i t e r a l s m u s t e n d w i t h t h e l e t t e r M o r m.
A s s i g n m e n t C o m p a t i b i l i t y f o r int V a r i a b l e s
Y o u c a n a s s i g n int v a l u e s t o int v a r i a b l e s , b u t y o u c a n n o t a s s i g n double o r decimal
v a l u e s t o int v a r i a b l e s . F o r e x a m p l e , l o o k a t t h e f o l l o w i n g d e c l a r a t i o n s :
int hoursWorked = 40; d
int unitsSold = 650m; d
int score = −25.5;
d
This works
ERROR!
ERROR!
T h e f i r s t d e c l a r a t i o n w o r k s b e c a u s e w e a r e i n i t i a l i z i n g a n int v a r i a b l e w i t h a n int v a l u e .
T h e s e c o n d d e c l a r a t i o n c a u s e s a n e r r o r , h o w e v e r , b e c a u s e y o u c a n n o t a s s i g n a decimal
v a l u e t o a n int v a r i a b l e . T h e t h i r d d e c l a r a t i o n a l s o c a u s e s a n e r r o r b e c a u s e y o u c a n n o t
a s s i g n a double v a l u e t o a n int v a r i a b l e .
Y o u c a n n o t a s s i g n a double o r a decimal v a l u e t o a n int v a r i a b l e b e c a u s e s u c h a n
a s s ig n m e n t c o u ld r e s u lt in a lo s s o f d a ta . H e r e a r e th e r e a s o n s :
• T h e double a n d decimal v a l u e s m a y b e f r a c t i o n a l , b u t int v a r i a b l e s c a n h o l d
o n l y i n t e g e r s . I f y o u w e r e a l l o w e d t o s t o r e a f r a c t i o n a l v a l u e i n a n int v a r i a b l e ,
th e fr a c tio n a l p a r t o f th e v a lu e w o u ld h a v e to b e d is c a r d e d .
133
134
C h a p te r 3
P r o c e s s in g D a t a
• T h e double a n d decimal v a l u e s m a y b e m u c h l a r g e r o r m u c h s m a l l e r t h a n a l l o w e d
b y t h e r a n g e o f a n int v a r i a b l e . A double o r a decimal n u m b e r c a n p o t e n t i a l l y b e
s o l a r g e o r s o s m a l l t h a t i t w i l l n o t f i t i n a n int v a r i a b l e .
A s s i g n m e n t C o m p a t i b i l i t y f o r double V a r i a b l e s
Y o u c a n a s s i g n e i t h e r double o r int v a l u e s t o double v a r i a b l e s , b u t y o u c a n n o t a s s i g n
decimal v a l u e s t o double v a r i a b l e s . F o r e x a m p l e , l o o k a t t h e f o l l o w i n g d e c l a r a t i o n s :
double distance = 28.75; d
double speed = 75;
d
double sales = 6500.0m; d
This works
This works
ERROR!
T h e f i r s t d e c l a r a t i o n w o r k s b e c a u s e w e a r e i n i t i a l i z i n g a double v a r i a b l e w i t h a double
v a l u e . T h e s e c o n d d e c l a r a t i o n w o r k s b e c a u s e w e a r e i n i t i a l i z i n g a double v a r i a b l e w i t h a n
int v a l u e . T h e t h i r d d e c l a r a t i o n c a u s e s a n e r r o r , h o w e v e r , b e c a u s e y o u c a n n o t a s s i g n a
decimal v a l u e t o a double v a r i a b l e .
I t m a k e s s e n s e t h a t y o u a r e a l l o w e d t o a s s i g n a n int v a l u e t o a double v a r i a b l e b e c a u s e
a n y n u m b e r t h a t c a n b e s t o r e d a s a n int c a n b e c o n v e r t e d t o a double w i t h n o l o s s o f
d a t a . W h e n y o u a s s i g n a n int v a l u e t o a double v a r i a b l e , t h e int v a l u e i s i m p l i c i t l y
c o n v e r t e d t o a double.
Y o u c a n n o t a s s i g n a decimal v a l u e t o a double v a r i a b l e b e c a u s e t h e decimal d a t a t y p e
a l l o w s f o r m u c h g r e a t e r p r e c i s i o n t h a n t h e double d a t a t y p e . A decimal v a l u e c a n h a v e
u p t o 2 8 d i g i t s o f p r e c i s i o n , w h e r e a s a double c a n p r o v i d e o n l y 1 5 d i g i t s o f p r e c i s i o n .
S t o r i n g a decimal v a l u e i n a double v a r i a b l e c o u l d p o t e n t i a l l y r e s u l t i n a l o s s o f d a t a .
A s s i g n m e n t C o m p a t i b i l i t y f o r decimal V a r i a b l e s
Y o u c a n a s s i g n e i t h e r decimal o r int v a l u e s t o decimal v a r i a b l e s , b u t y o u c a n n o t a s s i g n
double v a l u e s t o decimal v a r i a b l e s . F o r e x a m p l e , l o o k a t t h e f o l l o w i n g d e c l a r a t i o n s :
decimal balance = 9280.73m; d
decimal price = 50;
d
decimal sales = 6500.0;
d
This works
This works
ERROR!
T h e f i r s t d e c l a r a t i o n w o r k s b e c a u s e w e a r e i n i t i a l i z i n g a decimal v a r i a b l e w i t h a decimal
v a l u e . T h e s e c o n d d e c l a r a t i o n w o r k s b e c a u s e w e a r e i n i t i a l i z i n g a decimal v a r i a b l e w i t h
a n int v a l u e . W h e n y o u a s s i g n a n int v a l u e t o a decimal v a r i a b l e , t h e int v a l u e i s
i m p l i c i t l y c o n v e r t e d t o a decimal w i t h n o l o s s o f d a t a . T h e t h i r d d e c l a r a t i o n c a u s e s a n
e r r o r , h o w e v e r , b e c a u s e y o u c a n n o t a s s i g n a double v a l u e t o a decimal v a r i a b l e . A
double v a l u e c a n p o t e n t i a l l y b e m u c h l a r g e r o r m u c h s m a l l e r t h a n a l l o w e d b y t h e r a n g e
o f a decimal.
E x p lic it ly C o n v e r t in g V a lu e s w it h C a s t O p e r a t o r s
L e t’s c o n s id e r a h y p o th e tic a l s itu a tio n . S u p p o s e y o u ’v e w r itte n a n a p p lic a tio n th a t u s e s a
double v a r i a b l e , a n d f o r s o m e r e a s o n , y o u n e e d t o a s s i g n t h e c o n t e n t s o f t h e double
v a r i a b l e t o a n int v a r i a b l e . I n t h i s p a r t i c u l a r s i t u a t i o n , y o u k n o w t h a t t h e double
v a r i a b l e ’ s v a l u e i s s o m e t h i n g t h a t c a n b e s a f e l y c o n v e r t e d t o a n int w i t h o u t a n y l o s s o f
d a ta (s u c h a s 3 .0 , o r 9 8 .0 ). H o w e v e r , th e C # c o m p ile r w ill n o t a llo w y o u to m a k e th e
a s s i g n m e n t b e c a u s e double v a l u e s a r e n o t a s s i g n m e n t c o m p a t i b l e w i t h int v a r i a b l e s .
Is n ’t th e r e a w a y to o v e r r id e th e C # r u le s in th is p a r tic u la r s itu a tio n a n d m a k e th e
a s s ig n m e n t a n y w a y ?
T h e a n s w e r is y e s , th e r e is a w a y . Y o u c a n u s e a c a s t o p e r a to r to e x p lic itly c o n v e r t a v a lu e
fr o m o n e n u m e r ic d a ta ty p e to a n o th e r , e v e n if th e c o n v e r s io n m ig h t r e s u lt in a lo s s o f
3 .3
N u m e r ic D a t a T y p e s a n d V a r ia b le s
d a ta . A c a s t o p e r a to r is th e n a m e o f th e d e s ir e d d a ta ty p e , w r itte n in s id e p a r e n th e s e s a n d
p la c e d to th e le ft o f th e v a lu e th a t y o u w a n t to c o n v e r t. T h e fo llo w in g c o d e
s a m p le d e m o n s tr a te s :
1 // Declare an int variable.
2 int wholeNumber;
3
4 // Declare a double variable.
5 double realNumber = 3.0;
6
7 // Assign the double to the int.
8 wholeNumber = (int)realNumber;
T h e fo llo w in g p o in ts d e s c r ib e th e c o d e :
• L i n e 2 d e c l a r e s a n int v a r i a b l e n a m e d wholeNumber.
• L i n e 5 d e c l a r e s a double v a r i a b l e n a m e d realNumber, i n i t i a l i z e d w i t h t h e v a l u e 3 . 0 .
• L i n e 8 u s e s a c a s t o p e r a t o r t o c o n v e r t t h e v a l u e o f realNumber t o a n int a n d a s s i g n s
t h e c o n v e r t e d v a l u e t o wholeNumber. A f t e r t h i s s t a t e m e n t e x e c u t e s , t h e wholeNumber
v a r ia b le is a s s ig n e d th e v a lu e 3 .
T a b le 3 -3 s h o w s o th e r c o d e e x a m p le s in v o lv in g d iffe r e n t ty p e s o f c a s t o p e r a to r s .
T a b le 3 -3
E x a m p le s o f u s e s o f c a s t o p e r a to r s
C o d e E x a m p le
D e s c r ip tio n
int wholeNumber;
decimal moneyNumber = 4500m;
wholeNumber = (int)moneyNumber;
T h e (int) c a s t o p e r a t o r c o n v e r t s t h e v a l u e o f t h e
moneyNumber v a r i a b l e t o a n int. T h e c o n v e r t e d v a l u e
i s a s s i g n e d t o t h e wholeNumber v a r i a b l e .
double realNumber;
decimal moneyNumber = 625.70m;
realNumber = (double)moneyNumber;
T h e (double) c a s t o p e r a t o r c o n v e r t s t h e v a l u e o f t h e
moneyNumber v a r i a b l e t o a double. T h e c o n v e r t e d
v a l u e i s a s s i g n e d t o t h e realNumber v a r i a b l e .
decimal moneyNumber;
double realNumber = 98.9;
moneyNumber = (decimal)realNumber;
T h e (decimal) c a s t o p e r a t o r c o n v e r t s t h e v a l u e o f t h e
realNumber v a r i a b l e t o a decimal. T h e c o n v e r t e d
v a l u e i s a s s i g n e d t o t h e moneyNumber v a r i a b l e .
W h e n y o u u s e a c a s t o p e r a to r , y o u a r e e s s e n tia lly te llin g th e c o m p ile r th a t y o u k n o w
w h a t y o u a r e d o in g a n d y o u a r e w illin g to a c c e p t th e c o n s e q u e n c e s o f th e c o n v e r s io n . It
is s till p o s s ib le th a t a lo s s o f d a ta c a n o c c u r . F o r e x a m p le , lo o k a t th e fo llo w in g
c o d e s a m p le :
int wholeNumber;
double realNumber = 8.9;
wholeNumber = (int)realNumber;
I n t h i s e x a m p l e , t h e double v a r i a b l e c o n t a i n s a f r a c t i o n a l n u m b e r . W h e n t h e c a s t
o p e r a t o r c o n v e r t s t h e f r a c t i o n a l n u m b e r t o a n int, t h e p a r t o f t h e n u m b e r t h a t a p p e a r s
a fte r th e d e c im a l p o in t is d r o p p e d . T h e p r o c e s s o f d r o p p in g a n u m b e r ’s fr a c tio n a l p a r t
i s c a l l e d t r u n c a t i o n . A f t e r t h i s c o d e e x e c u t e s , t h e wholeNumber v a r i a b l e c o n t a i n s t h e
v a lu e 8 .
It’s im p o r ta n t to r e a liz e th a t w h e n a c a s t o p e r a to r is a p p lie d to a v a r ia b le , it d o e s n o t
c h a n g e th e c o n te n ts o f th e v a r ia b le . T h e c a s t o p e r a to r m e r e ly r e tu r n s th e v a lu e th a t is
s to r e d in th e v a r ia b le , c o n v e r te d to th e s p e c ifie d d a ta ty p e . In th e p r e v io u s c o d e s a m p le ,
w h e n t h e (int) c a s t o p e r a t o r i s a p p l i e d t o t h e realNumber v a r i a b l e , t h e c a s t o p e r a t o r
r e t u r n s t h e v a l u e 8 . T h e realNumber v a r i a b l e r e m a i n s u n c h a n g e d , h o w e v e r , s t i l l c o n t a i n in g th e v a lu e 8 .9 .
135
136
C h a p te r 3
P r o c e s s in g D a t a
C h e c k p o in t
3 .1 4
S p e c ify th e a p p r o p r ia te p r im itiv e n u m e r ic d a ta ty p e to u s e fo r e a c h o f th e fo llo w in g v a lu e s :
a . 2 4 d o lla r s
b . 1 2 b an an as
c . 1 4 .5 in c h e s
d . 8 3 cen ts
e . 2 c o n c e r t tic k e ts
3 .1 5
W h ic h o f th e fo llo w in g v a r ia b le d e c la r a tio n s w ill c a u s e a n e r r o r ? W h y ?
a . decimal payRate = 24m;
b . int playerScore = 1340.5;
c . double boxWidth = 205.25;
d . string lastName = "Holm";
3 .1 6
W r i t e a p r o g r a m m i n g s t a t e m e n t t h a t w i l l c o n v e r t t h e f o l l o w i n g decimal v a r i a b l e
t o a n int a n d s t o r e t h e r e s u l t i n a n int v a r i a b l e n a m e d dollars:
decimal deposit = 976.54m;
3 .1 7
W h a t v a l u e w i l l t h e wholePieces v a r i a b l e c o n t a i n
ex ecu tes?
a fte r th e fo llo w in g c o d e
a . double totalPieces = 6.5;
b . int wholePieces = (int)totalPieces;
3 .4
P e r fo r m in g C a lc u la t io n s
C O N C E P T :
Y o u c a n u s e m a th o p e r a to r s to p e r fo r m s im p le c a lc u la tio n s . M a th
e x p r e s s io n s c a n b e w r itte n u s in g th e m a th o p e r a to r s a n d p a r e n th e s e s a s
g r o u p in g s y m b o ls . T h e r e s u lt o f a m a th e x p r e s s io n c a n b e a s s ig n e d to
a v a r ia b le .
M o s t p r o g r a m s r e q u ir e c a lc u la tio n s o f s o m e s o r t to b e p e r fo r m e d . A p r o g r a m m e r ’s to o ls
fo r p e r fo r m in g c a lc u la tio n s a r e m a th o p e r a to r s . C # p r o v id e s th e m a th o p e r a to r s s h o w n in
T a b le 3 -4 .
T a b le 3 -4
Op erato r
M a th o p e ra to rs
Name o f th e Op erato r
D e s c r ip tio n
+
A d d itio n
Ad d s two n u mb ers
−
S u b tr a c tio n
Su b tracts o n e n u mb er fro m an o th er
*
M u ltip lic a tio n
M u ltip lie s o n e n u m b e r b y a n o th e r
/
D iv is io n
D iv id e s o n e n u m b e r b y a n o th e r a n d g iv e s th e q u o tie n t
%
M o d u lu s
D iv id e s o n e in te g e r b y a n o th e r a n d g iv e s th e r e m a in d e r
P r o g r a m m e r s u s e th e o p e r a to r s s h o w n in T a b le 3 -4 to c r e a te m a th e x p r e s s io n s . A m a th
e x p r e s s io n p e r fo r m s a c a lc u la tio n a n d g iv e s a v a lu e . T h e fo llo w in g is a n e x a m p le o f a
s im p le m a th e x p r e s s io n :
12 * 2
3 .4
P e r fo r m in g C a lc u la t io n s
T h e v a lu e s o n th e r ig h t a n d le ft o f th e *o p e r a to r a r e c a lle d o p e r a n d s . T h e s e a r e v a lu e s
th a t th e * o p e r a to r m u ltip lie s to g e th e r . T h e v a lu e th a t is g iv e n b y th is e x p r e s s io n
is 2 4 .
V a r ia b le s m a y a ls o b e u s e d in a m a th e x p r e s s io n . F o r e x a m p le , s u p p o s e w e h a v e tw o
v a r i a b l e s n a m e d hoursWorked a n d payRate. T h e f o l l o w i n g m a t h e x p r e s s i o n u s e s t h e *
o p e r a t o r t o m u l t i p l y t h e v a l u e i n t h e hoursWorked v a r i a b l e b y t h e v a l u e i n t h e
payRate v a r i a b l e :
hoursWorked * payRate
W h e n w e u s e a m a th e x p r e s s io n to c a lc u la te a v a lu e , w e h a v e to d o s o m e th in g w ith th e
v a lu e . N o r m a lly w e w a n t to s a v e th e v a lu e in m e m o r y s o w e c a n u s e it a g a in in th e p r o g r a m . W e d o th is w ith a n a s s ig n m e n t s ta te m e n t. F o r e x a m p le , s u p p o s e w e h a v e a n o th e r
v a r i a b l e n a m e d grossPay. T h e f o l l o w i n g s t a t e m e n t a s s i g n s t h e v a l u e hoursWorked t i m e s
payRate t o t h e grossPay v a r i a b l e :
grossPay = hoursWorked * payRate
H e r e a r e s o m e o th e r e x a m p le s o f s ta te m e n ts th a t a s s ig n th e r e s u lt o f a m a th e x p r e s s io n to
a v a r ia b le :
total = price + tax;
sale = price - discount;
commission = sales * percent;
half = number / 2;
T h e m o d u l u s o p e r a t o r ( %) p e r f o r m s d i v i s i o n b e t w e e n t w o i n t e g e r s , b u t i n s t e a d o f
r e tu r n in g th e q u o tie n t, it r e tu r n s th e r e m a in d e r . T h e fo llo w in g s ta te m e n t a s s ig n s 2 to
leftOver:
leftOver = 17 % 3;
T h i s s t a t e m e n t a s s i g n s 2 t o leftover b e c a u s e 1 7 d i v i d e d b y 3 i s 5 w i t h a r e m a i n d e r o f 2 .
Y o u w ill n o t u s e th e m o d u lu s o p e r a to r fr e q u e n tly , b u t it is u s e fu l in s o m e s itu a tio n s . It is
c o m m o n ly u s e d in c a lc u la tio n s th a t d e te c t o d d o r e v e n n u m b e r s , d e te r m in e th e d a y o f th e
w e e k , o r m e a s u r e th e p a s s a g e o f tim e a n d in o th e r s p e c ia liz e d o p e r a tio n s .
T h e O r d e r o f O p e r a t io n s
Y o u c a n w r ite m a th e m a tic a l e x p r e s s io n s w ith s e v e r a l o p e r a to r s . T h e fo llo w in g s ta te m e n t
a s s i g n s t h e s u m o f 1 7 , t h e v a r i a b l e x, 2 1 , a n d t h e v a r i a b l e y t o t h e v a r i a b l e answer.
answer = 17 + x + 21 + y;
S o m e e x p r e s s io n s a r e n o t th a t s tr a ig h tfo r w a r d , h o w e v e r . C o n s id e r th e fo llo w in g
statemen t:
outcome = 12 + 6 / 3;
W h a t v a l u e w i l l b e s t o r e d i n outcome? T h e n u m b e r 6 i s u s e d a s a n o p e r a n d f o r b o t h
t h e a d d i t i o n a n d d i v i s i o n o p e r a t o r s . T h e outcome v a r i a b l e c o u l d b e a s s i g n e d e i t h e r 6
o r 1 4 , d e p e n d in g o n w h e n th e d iv is io n ta k e s p la c e . T h e a n s w e r is 1 4 b e c a u s e th e o r d e r
o f o p e r a tio n s d ic ta te s th a t th e d iv is io n o p e r a to r w o r k s b e fo r e th e a d d itio n
o p e r a to r d o e s .
T h e o r d e r o f o p e r a tio n s c a n b e s u m m a r iz e d a s fo llo w s :
1 . P e r fo r m a n y o p e r a tio n s th a t a r e e n c lo s e d in p a r e n th e s e s .
2 . P e r fo r m a n y m u ltip lic a tio n s , d iv is io n s , o r m o d u lu s o p e r a tio n s a s th e y a p p e a r fr o m
le ft to r ig h t.
3 . P e r fo r m a n y a d d itio n s o r s u b tr a c tio n s a s th e y a p p e a r fr o m le ft to r ig h t.
137
138
C h a p te r 3
P r o c e s s in g D a t a
M a th e m a tic a l e x p r e s s io n s a r e e v a lu a te d fr o m le ft to r ig h t. M u ltip lic a tio n a n d d iv is io n a r e
a lw a y s p e r fo r m e d b e fo r e a d d itio n a n d s u b tr a c tio n , s o th e s ta te m e n t
outcome = 12 + 6 / 3;
w o r k s lik e th is :
1 . 6 is d iv id e d b y 3 , y ie ld in g a r e s u lt o f 2 .
2 . 1 2 is a d d e d to 2 , y ie ld in g a r e s u lt o f 1 4 .
It c o u ld b e d ia g r a m m e d a s s h o w n in F ig u r e 3 -1 1 .
T a b le 3 -5 s h o w s s o m e o th e r s a m p le e x p r e s s io n s w ith th e ir v a lu e s .
F ig u r e 3 -1 1
T h e o r d e r o f o p e r a t io n s a t w o r k
outcome = 12 + 6 / 3;
outcome = 12 +
outcome =
T a b le 3 -5
2;
14;
S o m e m a t h e x p r e s s io n s a n d t h e ir v a lu e s
E x p r e s s io n
V a lu e
5 + 2 * 4
1 3
10 / 2 − 3
2
8 + 12 * 2 − 4
2 8
6 − 3 * 2 + 7 − 1
6
G r o u p in g w it h P a r e n t h e s e s
P a r ts o f a m a th e m a tic a l e x p r e s s io n m a y b e g r o u p e d w ith p a r e n th e s e s to fo r c e s o m e o p e r a t io n s t o b e p e r f o r m e d b e f o r e o t h e r s . I n t h e f o llo w in g s t a t e m e n t , t h e v a r ia b le s aa n d ba r e
a d d e d to g e th e r , a n d th e ir s u m is d iv id e d b y 4 :
result = (a + b) / 4;
B u t w h a t if w e le ft th e p a r e n th e s e s o u t, a s s h o w n h e r e ?
result = a + b / 4;
W e w o u ld g e t a d iffe r e n t r e s u lt. W ith o u t th e p a r e n th e s e s , bw o u ld b e d iv id e d b y 4 a n d
t h e r e s u l t a d d e d t o a. T a b l e 3 - 6 s h o w s s o m e m a t h e x p r e s s i o n s t h a t u s e p a r e n t h e s e s
a n d th e ir v a lu e s .
T a b le 3 -6
M o r e e x p r e s s io n s a n d t h e ir v a lu e s
E x p r e s s io n
V a lu e
(5 + 2) * 4
2 8
10 / (5 − 3)
5
8 + 12 * (6 − 2)
5 6
(6 − 3) * (2 + 7) / 3
9
3 .4
P e r fo r m in g C a lc u la t io n s
M ix in g D a t a T y p e s in a M a t h E x p r e s s io n
W h e n y o u p e r fo r m a m a th o p e r a tio n o n tw o o p e r a n d s , th e d a ta ty p e o f th e r e s u lt w ill
d ep en d o n th e d ata typ e o f th e o p eran d s. If th e o p eran d s are o f th e same d ata typ e, th e
r e s u lt w ill a ls o b e o f th a t d a ta ty p e . F o r e x a m p le :
• W h e n a n o p e r a t i o n i s p e r f o r m e d o n t w o int v a l u e s , t h e r e s u l t w i l l b e a n int.
• W h e n a n o p e r a t i o n i s p e r f o r m e d o n t w o double v a l u e s , t h e r e s u l t w i l l b e
a double.
• W h e n a n o p e r a t i o n i s p e r f o r m e d o n t w o decimal v a l u e s , t h e r e s u l t w i l l b e
a decimal.
It’s n o t u n c o m m o n , h o w e v e r , fo r a m a th e x p r e s s io n to h a v e o p e r a n d s o f d iffe r e n t d a ta
t y p e s . C # h a n d l e s o p e r a t i o n s i n v o l v i n g int , double , a n d decimal o p e r a n d s i n t h e
fo llo w in g w a y s :
• W h e n a m a t h e x p r e s s i o n i n v o l v e s a n int a n d a double, t h e int i s t e m p o r a r i l y
c o n v e r t e d t o a double, a n d t h e r e s u l t i s a double.
• W h e n a m a t h e x p r e s s i o n i n v o l v e s a n int a n d a decimal, t h e int i s t e m p o r a r i l y
c o n v e r t e d t o a decimal, a n d t h e r e s u l t i s a decimal.
• M a t h e x p r e s s i o n s i n v o l v i n g a double a n d a decimal a r e n o t a l l o w e d u n l e s s a c a s t
o p e r a to r is u s e d to c o n v e r t o n e o f th e o p e r a n d s .
F o r e x a m p le , s u p p o s e a p a y -c a lc u la tin g p r o g r a m h a s th e fo llo w in g v a r ia b le d e c la r a tio n s :
int hoursWorked; // To hold the number of hours worked
decimal payRate; // To hold the hourly pay rate
decimal grossPay; // To hold the gross pay
T h e n , la te r in th e p r o g r a m th is s ta te m e n t a p p e a r s :
grossPay = hoursWorked * payRate;
T h e m a t h e x p r e s s i o n o n t h e r i g h t s i d e o f t h e = o p e r a t o r m u l t i p l i e s a n int b y a decimal.
W h e n t h e s t a t e m e n t e x e c u t e s , t h e v a l u e o f t h e hoursWorked v a r i a b l e i s t e m p o r a r i l y c o n v e r t e d t o a decimal a n d t h e n m u l t i p l i e d b y t h e payRate v a r i a b l e . T h e r e s u l t i s a decimal
a n d i s a s s i g n e d t o t h e grossPay v a r i a b l e .
W h e n p o s s i b l e , y o u s h o u l d a v o i d m a t h o p e r a t i o n s t h a t u s e a m i x t u r e o f double
a n d decimal o p e r a n d s . C # d o e s n o t a l l o w o p e r a t i o n s i n v o l v i n g t h e s e t w o t y p e s
u n le s s y o u u s e a c a s t o p e r a to r to e x p lic itly c o n v e r t o n e o f th e o p e r a n d s . F o r e x a m p le ,
s u p p o s e a p r o g r a m th a t c a lc u la te s th e c o s t o f a p r o d u c t h a s th e fo llo w in g v a r ia b le
d e c la r a tio n s :
double weight;
// The product weight
decimal pricePerPound; // The price per pound
decimal total;
// The total cost
L a te r in th e p r o g r a m y o u n e e d to c a lc u la te th e to ta l c o s t, lik e th is :
total = weight * pricePerPound; d
ERROR!
T h e c o m p i l e r w i l l n o t a l l o w t h i s s t a t e m e n t b e c a u s e weight i s a double a n d
pricePerPound i s a decimal. T o f i x t h e s t a t e m e n t , y o u c a n i n s e r t a c a s t o p e r a t o r , a s
sh o wn h ere:
total = (decimal)weight * pricePerPound;
T h e c a s t o p e r a t o r c o n v e r t s t h e v a l u e o f t h e weight v a r i a b l e t o a decimal, a n d t h e c o n v e r t e d v a l u e i s m u l t i p l i e d b y pricePerPound. T h e r e s u l t o f t h e e x p r e s s i o n i s a decimal
a n d i s a s s i g n e d t o total.
139
140
C h a p te r 3
P r o c e s s in g D a t a
In t e g e r D iv is io n
W h e n y o u d iv id e a n in te g e r b y a n in te g e r in C # , th e r e s u lt is a lw a y s g iv e n a s a n in te g e r . If
th e r e s u lt h a s a fr a c tio n a l p a r t, it is tr u n c a te d . F o r e x a m p le , lo o k a t th e fo llo w in g c o d e :
int length;
double half;
length = 75;
half = length / 2;
// Declare length as an int
// Declare half as a double
// Assign 75 to length
// Calculate half the length
T h e l a s t s t a t e m e n t d i v i d e s t h e v a l u e o f length b y 2 a n d a s s i g n s t h e r e s u l t t o h a l f . M a t h e m a tic a lly , th e r e s u lt o f 7 5 d iv id e d b y 2 is 3 7 .5 . H o w e v e r , th a t is n o t th e r e s u lt th a t w e g e t
f r o m t h e m a t h e x p r e s s i o n . T h e length v a r i a b l e i s a n int, a n d i t i s b e i n g d i v i d e d b y t h e
n u m e r i c l i t e r a l 2 , w h i c h i s a l s o t r e a t e d a s a n int. T h e r e s u l t o f t h e d i v i s i o n i s t r u n c a t e d ,
w h i c h g i v e s t h e v a l u e 3 7 . T h i s i s t h e v a l u e t h a t i s a s s i g n e d t o t h e half v a r i a b l e . I t d o e s n o t
m a t t e r t h a t t h e half v a r i a b l e i s d e c l a r e d a s a double. T h e f r a c t i o n a l p a r t o f t h e r e s u l t i s
tr u n c a te d b e fo r e th e a s s ig n m e n t ta k e s p la c e .
C o m b in e d A s s ig n m e n t O p e r a t o r s
S o m e tim e s y o u w a n t to in c r e a s e a v a r ia b le ’s v a lu e b y a c e r ta in a m o u n t. F o r e x a m p le , s u p p o s e y o u h a v e a v a r i a b l e n a m e d number a n d y o u w a n t t o i n c r e a s e i t s v a l u e b y 1 . Y o u c a n
a c c o m p lis h th a t w ith th e fo llo w in g s ta te m e n t:
number = number + 1;
T h e e x p r e s s i o n o n t h e r i g h t s i d e o f t h e a s s i g n m e n t o p e r a t o r c a l c u l a t e s t h e v a l u e o f number
p l u s 1 . T h e r e s u l t i s t h e n a s s i g n e d t o number, r e p l a c i n g t h e v a l u e t h a t w a s p r e v i o u s l y
s t o r e d t h e r e . T h i s s t a t e m e n t e f f e c t i v e l y a d d s 1 t o number. F o r e x a m p l e , i f number i s e q u a l
to 6 b e fo r e th is s ta te m e n t e x e c u te s , it is e q u a l to 7 a fte r th e s ta te m e n t e x e c u te s .
S i m i l a r l y , t h e f o l l o w i n g s t a t e m e n t s u b t r a c t s 5 f r o m number:
number = number − 5;
I f number i s e q u a l t o 1 5 b e f o r e t h i s s t a t e m e n t e x e c u t e s , i t i s e q u a l t o 1 0 a f t e r t h e s t a t e m e n t
e x e c u te s . H e r e ’s a n o th e r e x a m p le . T h e fo llo w in g s ta te m e n t d o u b le s th e v a lu e o f th e
number v a r i a b l e :
number = number * 2;
I f number i s e q u a l t o 4 b e f o r e t h i s s t a t e m e n t e x e c u t e s , i t i s e q u a l t o 8 a f t e r t h e s t a t e m e n te x e c u te s .
T h e s e ty p e s o f o p e r a tio n s a r e v e r y c o m m o n in p r o g r a m m in g . F o r c o n v e n ie n c e , C # o ffe r s
a s p e c ia l s e t o f o p e r a to r s k n o w n a s c o m b in e d a s s ig n m e n t o p e r a to r s th a t a r e d e s ig n e d s p e c ific a lly fo r th e s e jo b s . T a b le 3 -7 s h o w s th e c o m b in e d a s s ig n m e n t o p e r a to r s .
T a b le 3 -7
C o m b in e d a s s ig n m e n t o p e r a t o r s
Op erato r
E x a m p le U s a g e
E q u iv a le n c e
+=
x += 5;
x = x + 5;
−=
y −= 2;
y = y − 2;
*=
z *= 10;
z = z * 10;
/=
a /= b;
a = a / b;
%=
c %= 3;
c = c % 3;
3 .5
In p u t t in g a n d O u t p u t t in g N u m e r ic V a lu e s
A s y o u c a n s e e , th e c o m b in e d a s s ig n m e n t o p e r a to r s d o n o t r e q u ir e th e p r o g r a m m e r to
ty p e th e v a r ia b le n a m e tw ic e . A ls o , th e y g iv e a c le a r in d ic a tio n o f w h a t is h a p p e n in g in
th e s ta te m e n t.
C h e c k p o in t
3 .1 8
L is t th e o p e r a n d s fo r th e fo llo w in g m a th e x p r e s s io n :
length * width
3 .1 9
S u m m a r iz e th e m a th e m a tic a l o r d e r o f o p e r a tio n s .
3 .2 0
R e w r ite th e fo llo w in g c o d e s e g m e n t s o th a t it d o e s n o t c a u s e a n e r r o r .
decimal pricePerFoot = 2.99m;
double boardLength = 10.5;
decimal totalCost = boardLength * pricePerFoot;
3 .2 1
A s s u m e result i s a double v a r i a b l e . W h e n t h e f o l l o w i n g s t a t e m e n t e x e c u t e s ,
w h a t v a l u e w i l l b e s t o r e d i n result?
result = 4 + 10 / 2;
3 .2 2
A s s u m e result i s a n int v a r i a b l e . W h e n t h e f o l l o w i n g s t a t e m e n t e x e c u t e s , w h a t
v a l u e w i l l b e s t o r e d i n result?
result = (2 + 5) * 10;
3 .2 3
A s s u m e result i s a double v a r i a b l e . W h e n t h e f o l l o w i n g s t a t e m e n t e x e c u t e s ,
w h a t v a l u e w i l l b e s t o r e d i n result?
result = 5 / 2;
3 .2 4
R e w r ite th e fo llo w in g s ta te m e n ts u s in g c o m b in e d a s s ig n m e n t o p e r a to r s :
a . count = count + 1;
b . amount = amount – 5;
c . radius = radius * 10;
d . length = length / 2;
3 .5
In p u t t in g a n d O u t p u t t in g N u m e r ic V a lu e s
C O N C E P T :
If th e u s e r h a s e n te r e d a n u m b e r in to a T e x tB o x , th e n u m b e r w ill b e s to r e d
a s a s tr in g in th e T e x tB o x ’s T e x t p r o p e r ty . If y o u w a n t to s to r e th a t
n u m b e r in a n u m e r ic v a r ia b le , y o u h a v e to c o n v e r t it to th e a p p r o p r ia te
n u m e r ic d a ta ty p e . W h e n y o u w a n t to d is p la y th e v a lu e o f a n u m e r ic
v a r ia b le in a L a b e l c o n tr o l o r a m e s s a g e b o x , y o u h a v e to c o n v e r t it to
a s tr in g .
G e t t in g a N u m b e r fr o m a T e x t B o x
G r a p h ic a l U s e r In te r fa c e (G U I) a p p lic a tio n s ty p ic a lly u s e T e x tB o x c o n tr o ls to r e a d k e y b o a r d
in p u t. A n y d a ta th a t th e u s e r e n te r s in to a T e x tB o x c o n tr o l is s to r e d in th e c o n tr o l’s T e x t
p r o p e r ty a s a s tr in g , e v e n if it is a n u m b e r . F o r e x a m p le , if th e u s e r e n te r s th e n u m b e r 7 2 in to
a T e x t B o x c o n t r o l , t h e i n p u t i s s t o r e d a s t h e s t r i n g "72" i n t h e c o n t r o l ’ s T e x t p r o p e r t y .
If th e u s e r h a s e n te r e d a n u m e r ic v a lu e in to a T e x tB o x c o n tr o l a n d y o u w a n t to a s s ig n th a t
v a lu e to a n u m e r ic v a r ia b le , y o u h a v e to c o n v e r t th e c o n tr o l’s T e x t p r o p e r ty to th e d e s ir e d
n u m e r ic d a ta ty p e . U n fo r tu n a te ly , y o u c a n n o t u s e a c a s t o p e r a to r to c o n v e r t a s tr in g to a
n u m e r ic ty p e .
141
142
C h a p te r 3
P r o c e s s in g D a t a
T o c o n v e r t a s tr in g to a n y o f th e n u m e r ic d a ta ty p e s , w e u s e a fa m ily o f m e th o d s in th e
. N E T F r a m e w o r k k n o w n a s t h e Parse m e t h o d s . I n c o m p u t e r s c i e n c e , t h e t e r m p a r s e
t y p i c a l l y m e a n s t o a n a l y z e a s t r i n g o f c h a r a c t e r s f o r s o m e p u r p o s e . T h e Parse m e t h o d s
a r e u s e d t o c o n v e r t a s t r i n g t o a s p e c i f i c d a t a t y p e . T h e r e a r e s e v e r a l Parse m e t h o d s i n t h e
. N E T F r a m e w o r k , b u t b e c a u s e w e a r e p r i m a r i l y u s i n g t h e int, double, a n d decimal
n u m e r ic d a ta ty p e s , w e n e e d o n ly th r e e o f th e m :
• W e u s e t h e int.Parse m e t h o d t o c o n v e r t a s t r i n g t o a n int.
• W e u s e t h e double.Parse m e t h o d t o c o n v e r t a s t r i n g t o a double.
• W e u s e t h e decimal.Parse m e t h o d t o c o n v e r t a s t r i n g t o a decimal.
W h e n y o u c a l l o n e o f t h e Parse m e t h o d s , y o u p a s s a p i e c e o f d a t a k n o w n a s a n a r g u m e n t
in to th e m e th o d , a n d th e m e th o d r e tu r n s a p ie c e o f d a ta b a c k to y o u . T h e a r g u m e n t th a t
y o u p a s s to th e m e th o d is th e s tr in g th a t y o u w a n t to c o n v e r t, a n d th e p ie c e o f d a ta th a t
th e m e th o d r e tu r n s b a c k to y o u is th e c o n v e r te d v a lu e . F ig u r e 3 -1 2 illu s tr a te s th is c o n c e p t
u s i n g t h e int.Parse m e t h o d a s a n e x a m p l e .
F ig u r e 3 -1 2
T h e in t .P a r s e m e t h o d
Argument
(the string you want to convert)
An int value is returned
int.Parse(string)
T h e f o l l o w i n g c o d e s a m p l e s h o w s h o w t o u s e t h e int.Parse m e t h o d t o c o n v e r t a
c o n t r o l ’ s T e x t p r o p e r t y t o a n int. A s s u m e t h a t hoursWorkedTextBox i s t h e n a m e o f a
T e x tB o x c o n tr o l.
1 // Declare an int variable to hold the hours worked.
2 int hoursWorked;
3
4 // Get the hours worked from the TextBox.
5 hoursWorked = int.Parse(hoursWorkedTextBox.Text);
L e t ’ s a s s u m e t h a t t h e u s e r h a s e n t e r e d t h e v a l u e 4 0 i n t o t h e hoursWorkedTextBox c o n tr o l. In lin e 5 o f th e c o d e s a m p le , o n th e r ig h t s id e o f th e = o p e r a to r is th e e x p r e s s io n
int.Parse(hoursWorkedTextBox.Text) . T h i s e x p r e s s i o n c a l l s t h e int.Parse
m e t h o d , p a s s i n g t h e v a l u e o f hoursWorkedTextBox.Text a s a n a r g u m e n t . B e c a u s e t h e
u s e r h a s e n t e r e d 4 0 i n t o t h e T e x t B o x , t h e s t r i n g "40" i s t h e v a l u e t h a t i s p a s s e d a s t h e
a r g u m e n t . T h e m e t h o d c o n v e r t s t h e s t r i n g "40" t o t h e int v a l u e 4 0 . T h e int v a l u e 4 0
i s r e t u r n e d f r o m t h e m e t h o d a n d t h e = o p e r a t o r a s s i g n s i t t o t h e hoursWorked v a r i a b l e .
F ig u r e 3 -1 3 illu s tr a te s th is p r o c e s s .
T h e f o l l o w i n g c o d e s a m p l e d e m o n s t r a t e s t h e double.Parse m e t h o d . A s s u m e t h a t
temperatureTextBox i s t h e n a m e o f a T e x t B o x c o n t r o l .
1 // Declare a double variable to hold the temperature.
2 double temperature;
3
4 // Get the temperature from the TextBox.
5 temperature = double.Parse(temperatureTextBox.Text);
L i n e 5 p a s s e s temperatureTextBox.Text a s a n a r g u m e n t t o t h e double.Parse m e t h o d .
T h a t v a l u e i s c o n v e r t e d t o a double, r e t u r n e d f r o m t h e double.parse m e t h o d , a n d
a s s i g n e d t o t h e temperature v a r i a b l e .
T h e f o l l o w i n g c o d e s a m p l e d e m o n s t r a t e s t h e decimal.Parse m e t h o d . A s s u m e t h a t
moneyTextBox i s t h e n a m e o f a T e x t B o x c o n t r o l .
3 .5
F ig u r e 3 -1 3
In p u t t in g a n d O u t p u t t in g N u m e r ic V a lu e s
C o n v e r t i n g T e x t B o x i n p u t t o a n int
The user enters 40 into the
hoursWorkedTextBox control.
The string "40" is stored
in the control’s Text
property.
"40"
40
hoursWorked = int.Parse(hoursWorkedTextBox.Text);
The int value 40 is returned
from the int.Parse method
and assigned to the hoursWorked
variable.
1 // Declare a decimal variable to hold an amount of money.
2 decimal money;
3
4 // Get an amount from the TextBox.
5 money = decimal.Parse(moneyTextBox.Text);
L i n e 5 p a s s e s moneyTextBox.Text a s a n a r g u m e n t t o t h e decimal.Parse m e t h o d . T h a t
v a l u e i s c o n v e r t e d t o a decimal, r e t u r n e d f r o m t h e decimal.parse m e t h o d , a n d a s s i g n e d
t o t h e money v a r i a b l e .
N O T E : If y o u lo o k a t th e to p o f a fo r m ’s s o u r c e c o d e in th e c o d e e d ito r , y o u s h o u ld
s e e a d i r e c t i v e t h a t r e a d s using System;. T h a t d i r e c t i v e i s r e q u i r e d f o r a n y p r o g r a m
t h a t u s e s t h e Parse m e t h o d s .
143
144
C h a p te r 3
P r o c e s s in g D a t a
F ig u r e 3 -1 4
E x c e p t io n r e p o r t e d
F ig u r e 3 -1 5
E x c e p t io n r e p o r t e d
L a te r in th is c h a p te r , y o u w ill le a r n h o w to c a tc h e r r o r s lik e th is a n d p r e v e n t th e p r o g r a m
fr o m h a ltin g .
D is p la y in g N u m e r ic V a lu e s
S u p p o s e a n a p p l i c a t i o n h a s a decimal v a r i a b l e n a m e d grossPay a n d a L a b e l c o n t r o l n a m e d
grossPayLabel. Y o u w a n t t o d i s p l a y t h e v a r i a b l e ’ s v a l u e i n t h e L a b e l c o n t r o l . T o a c c o m p l i s h
t h i s , y o u m u s t s o m e h o w g e t t h e v a l u e o f t h e grossPay v a r i a b l e i n t o t h e grossPayLabel
c o n tr o l’s T e x t p r o p e r ty . T h e fo llo w in g a s s ig n m e n t s ta te m e n t w ill n o t w o r k , h o w e v e r :
grossPayLabel.Text = grossPay; d
ERROR!
Y o u c a n n o t a s s ig n a n u m e r ic v a lu e to a c o n tr o l’s T e x t p r o p e r ty b e c a u s e o n ly s tr in g s c a n
b e a s s ig n e d to th e T e x t p r o p e r ty . If y o u w a n t to d is p la y th e v a lu e o f a n u m e r ic v a r ia b le in
a L a b e l c o n tr o l, y o u h a v e to c o n v e r t th e v a r ia b le ’s v a lu e to a s tr in g .
L u c k i l y , a l l v a r i a b l e s h a v e a ToString m e t h o d t h a t y o u c a n c a l l t o c o n v e r t t h e v a r i a b l e ’ s
v a l u e t o a s t r i n g . Y o u c a l l t h e ToString m e t h o d u s i n g t h e f o l l o w i n g g e n e r a l f o r m a t :
variableName.ToString()
I n t h e g e n e r a l f o r m a t , variableName i s t h e n a m e o f a n y v a r i a b l e . T h e e x p r e s s i o n r e t u r n s
th e v a r ia b le ’s v a lu e a s a s tr in g . H e r e is a c o d e s a m p le th a t d e m o n s tr a te s :
decimal grossPay = 1550.0m;
grossPayLabel.Text = grossPay.ToString();
3 .5
In p u t t in g a n d O u t p u t t in g N u m e r ic V a lu e s
T h e f i r s t s t a t e m e n t d e c l a r e s a decimal v a r i a b l e n a m e d grossPay i n i t i a l i z e d w i t h t h e
v a lu e 1 ,5 5 0 .0 . In th e s e c o n d s ta te m e n t, th e e x p r e s s io n o n th e r ig h t s id e o f th e =o p e r a to r
c a l l s t h e grossPay v a r i a b l e ’ s ToString m e t h o d . T h e m e t h o d r e t u r n s t h e s t r i n g "1550.0".
T h e = o p e r a t o r t h e n a s s i g n s t h e s t r i n g "1550.0" t o t h e grossPayLabel c o n t r o l ’ s T e x t
p r o p e r t y . A s a r e s u l t , t h e v a l u e 1550.0 i s d i s p l a y e d i n t h e grossPayLabel c o n t r o l . T h i s
p r o c e s s is illu s tr a te d in F ig u r e 3 -1 6 .
F ig u r e 3 -1 6
D is p la y in g n u m e r ic d a t a in a L a b e l c o n t r o l
decimal grossPay = 1550.0m;
grossPayLabel.Text = grossPay.ToString();
"1550.0"
c o n v e r t a n u m e r i c v a r i a b l e t o a string b e f o r e p a s s i n g i t t o t h e
MessageBox.Show m e t h o d . T h e f o l l o w i n g e x a m p l e s h o w s h o w a n int v a r i a b l e ’ s v a l u e
c a n b e c o n v e r te d to a s tr in g a n d d is p la y e d in a m e s s a g e b o x :
Y o u
m u s t a ls o
int myNumber = 123;
MessageBox.Show(myNumber.ToString());
T h e f i r s t s t a t e m e n t d e c l a r e s a n int v a r i a b l e n a m e d myNumber, i n i t i a l i z e d w i t h t h e v a l u e
1 2 3 . In th e s e c o n d s ta te m e n t th e fo llo w in g ta k e s p la c e :
• T h e myNumber v a r i a b l e ’ s ToString m e t h o d i s c a l l e d . T h e m e t h o d r e t u r n s t h e s t r i n g
"123".
• T h e s t r i n g "123" i s p a s s e d t o t h e MessageBox.Show m e t h o d . A s a r e s u l t , t h e v a l u e
123 i s d i s p l a y e d i n a m e s s a g e b o x .
I m p lic it S t r in g C o n v e r s io n w it h t h e +O p e r a t o r
In th is c h a p te r , y o u ’v e le a r n e d th a t th e +o p e r a to r h a s tw o u s e s : s tr in g c o n c a te n a tio n a n d
n u m e r ic a d d itio n . If y o u w r ite a n e x p r e s s io n u s in g th e +o p e r a to r a n d b o th o p e r a n d s a r e
s tr in g s , th e +o p e r a to r c o n c a te n a te s th e s tr in g s . If b o th o p e r a n d s a r e n u m b e r s o f c o m p a tib le ty p e s , th e n th e +o p e r a to r a d d s th e tw o n u m b e r s . B u t w h a t h a p p e n s if o n e o p e r a n d is
a s tr in g a n d th e o th e r o p e r a n d is a n u m b e r ? T h e n u m b e r w ill b e im p lic itly c o n v e r te d to a
s tr in g , a n d b o th o p e r a n d s w ill b e c o n c a te n a te d . H e r e ’s a n e x a m p le :
int idNumber = 1044;
string output = "Your ID number is " + idNumber;
I n t h e s e c o n d s t a t e m e n t , t h e string v a r i a b l e output i s i n i t i a l i z e d w i t h t h e s t r i n g "Your
ID number is 1044". H e r e i s a n o t h e r e x a m p l e :
double testScore = 88.5;
MessageBox.Show("Your test score is " + testScore);
T h e s e c o n d s t a t e m e n t d i s p l a y s a m e s s a g e b o x s h o w i n g t h e s t r i n g "Your test score is
88.5".
In T u to r ia l 3 -2 , y o u w ill u s e s o m e o f th e te c h n iq u e s d is c u s s e d in th is s e c tio n . Y o u w ill
c r e a te a n a p p lic a tio n th a t r e a d s n u m e r ic in p u t fr o m T e x tB o x c o n tr o ls , a n d d is p la y s
n u m e r ic o u tp u t in a L a b e l c o n tr o l.
145
146
C h a p te r 3
P r o c e s s in g D a t a
T u t o r ia l 3 -2 :
C a lc u la t in g F u e l E c o n o m y
VideoNot e
T u to r ia l 3 -2 :
C a lc u la tin g
Fu el
Eco n o my
In th e U n ite d S ta te s , a c a r ’s fu e l e c o n o m y is m e a s u r e d in m ile s p e r g a llo n , o r M P G . Y o u
u s e th e fo llo w in g fo r m u la to c a lc u la te a c a r ’s M P G :
M PG = M iles driven ÷ Gallons of gas used
In th is tu to r ia l, y o u w ill c r e a te a n a p p lic a tio n th a t le ts th e u s e r e n te r th e n u m b e r o f m ile s
h e o r s h e h a s d r iv e n a n d th e g a llo n s o f g a s u s e d . T h e a p p lic a tio n w ill c a lc u la te a n d d is p la y
th e c a r ’s M P G .
F ig u r e 3 -1 7 s h o w s th e a p p lic a tio n ’s fo r m , w ith th e n a m e s o f a ll th e c o n tr o ls . W h e n th e
a p p l i c a t i o n r u n s , t h e u s e r e n t e r t h e n u m b e r o f m i l e s d r i v e n i n t o t h e milesTextBox c o n t r o l a n d t h e g a l l o n s o f g a s u s e d i n t o t h e gallonsTextBox c o n t r o l . W h e n t h e u s e r c l i c k s
t h e calculateButton c o n t r o l , t h e a p p l i c a t i o n c a l c u l a t e s t h e c a r ’ s M P G a n d d i s p l a y s t h e
r e s u l t i n t h e mpgLabel c o n t r o l . T h e exitButton c o n t r o l c l o s e s t h e a p p l i c a t i o n ’ s f o r m .
F ig u r e 3 -1 7
T h e Fuel Economy f o r m
milesPromptLabel
milesTextBox
gallonsPromptLabel
gallonsTextBox
mpgLabel
outputDescriptionLabel
calculateButton
exitButton
S t e p 1 :
S ta r t V is u a l S tu d io a n d b e g in a n e w W in d o w s F o r m s A p p lic a tio n p r o je c t
n a m e d Fuel Economy.
S t e p 2 :
S e t u p th e a p p lic a tio n ’s fo r m a s s h o w n in F ig u r e 3 -1 7 . N o tic e th a t th e fo r m ’s
T e x t p r o p e r t y i s s e t t o Fuel Economy. T h e n a m e s o f t h e c o n t r o l s a r e s h o w n
in th e fig u r e . A s y o u p la c e e a c h o f th e c o n tr o ls o n th e fo r m , r e fe r to T a b le 3 -8
fo r th e r e le v a n t p r o p e r ty s e ttin g s .
S t e p 3 :
O n c e y o u h a v e s e t u p th e fo r m w ith its c o n tr o ls , y o u c a n c r e a te th e C lic k e v e n t
h a n d le r s fo r th e B u tto n c o n tr o ls . A t th e e n d o f th is tu to r ia l, P r o g r a m 3 -2 s h o w s
th e c o m p le te d c o d e fo r th e fo r m . Y o u w ill b e in s tr u c te d to r e fe r to P r o g r a m 3 -2
a s y o u w r ite th e e v e n t h a n d le r s . (R e m e m b e r , th e lin e n u m b e r s th a t a r e s h o w n in
P r o g r a m 3 -2 a r e n o t p a r t o f th e p r o g r a m . T h e y a r e s h o w n fo r r e fe r e n c e o n ly .)
I n t h e Designer, d o u b l e - c l i c k t h e calculateButton c o n t r o l . T h i s o p e n s t h e c o d e
e d i t o r , a n d y o u w i l l s e e a n e m p t y e v e n t h a n d l e r n a m e d calculateButton_
Click. C o m p l e t e t h e calculateButton_Click e v e n t h a n d l e r b y t y p i n g t h e c o d e
s h o w n in lin e s 2 2 – 3 8 in P r o g r a m 3 -2 .
L e t’s ta k e a c lo s e r lo o k a t th e c o d e :
L i n e 2 2 : T h i s s t a t e m e n t d e c l a r e s a double v a r i a b l e n a m e d miles. T h i s v a r i a b le is u s e d to h o ld th e n u m b e r o f m ile s d r iv e n .
L i n e 2 3 : T h i s s t a t e m e n t d e c l a r e s a double v a r i a b l e n a m e d gallons. T h i s
v a r ia b le is u s e d to h o ld th e n u m b e r o f g a llo n s u s e d .
3 .5
T a b le 3 -8
In p u t t in g a n d O u t p u t t in g N u m e r ic V a lu e s
C o n t r o l p r o p e r t y s e t t in g s
Co n tro l Name
Co n tro l Typ e
P r o p e r ty S e ttin g s
milesPromptLabel
Lab el
T e x t : Enter the number of miles driven:
gasPromptLabel
Lab el
T e x t : Enter the gallons of gas used:
outputDescriptionLabel
Lab el
T e x t : Your car’s M PG:
milesTextBox
Tex tBo x
N o p r o p e r tie s c h a n g e d
gallonsTextBox
Tex tBo x
N o p r o p e r tie s c h a n g e d
mpgLabel
Lab el
A u to S iz e : F a ls e
B o r d e r S ty le : F ix e d S in g le
Tex t: (Th e co n ten ts o f th e Tex t
p r o p e r ty h a v e b e e n e r a s e d .)
T e x tA lig n : M id d le C e n te r
calculateButton
Bu tto n
T e x t : Calculate M PG
exitButton
Bu tto n
T e x t : Exit
L i n e 2 4 : T h i s s t a t e m e n t d e c l a r e s a double v a r i a b l e n a m e d mpg. T h i s v a r i a b l e
is u s e d to h o ld th e M P G , w h ic h w ill b e c a lc u la te d .
L i n e 2 8 : T h i s s t a t e m e n t c o n v e r t s t h e milesTextBox c o n t r o l ’ s T e x t p r o p e r t y
t o a double a n d a s s i g n s t h e r e s u l t t o t h e miles v a r i a b l e .
L i n e 3 2 : T h i s s t a t e m e n t c o n v e r t s t h e gallonsTextBox c o n t r o l ’ s T e x t p r o p e r t y t o a double a n d a s s i g n s t h e r e s u l t t o t h e gallons v a r i a b l e .
L i n e 3 5 : T h i s s t a t e m e n t c a l c u l a t e s M P G . I t d i v i d e s t h e miles v a r i a b l e b y t h e
gallons v a r i a b l e a n d a s s i g n s t h e r e s u l t t o t h e mpg v a r i a b l e .
L i n e 3 8 : T h i s s t a t e m e n t c o n v e r t s t h e mpg v a r i a b l e t o a s t r i n g a n d a s s i g n s t h e
r e s u l t t o t h e mpgLabel c o n t r o l ’ s T e x t p r o p e r t y . T h i s c a u s e s t h e v a l u e o f t h e
mpg v a r i a b l e t o b e d i s p l a y e d i n t h e mpgLabel c o n t r o l .
S t e p 4 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e exitButton
c o n tr o l. In th e c o d e e d ito r y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
exitButton_Click. C o m p l e t e t h e exitButton_Click e v e n t h a n d l e r b y
ty p in g th e c o d e s h o w n in lin e s 4 3 – 4 4 in P r o g r a m 3 -2 .
S t e p 5 :
S a v e th e p r o je c t. T h e n , p r e s s th e
k e y o n t h e k e y b o a r d o r c l i c k t h e Start
D ebugging b u t t o n ( ) o n t h e t o o l b a r t o c o m p i l e a n d r u n t h e a p p l i c a t i o n . T e s t
th e a p p lic a tio n b y e n te r in g v a lu e s in to th e T e x tB o x e s a n d c lic k in g th e
Calculate M PG b u t t o n . T h e M P G s h o u l d b e d i s p l a y e d , s i m i l a r t o F i g u r e 3 - 1 8 .
C l i c k t h e Exit b u t t o n a n d t h e f o r m s h o u l d c l o s e .
F ig u r e 3 -1 8
T h e Fuel Economy a p p l i c a t i o n
147
148
C h a p te r 3
P r o c e s s in g D a t a
P r o g r a m 3 -2
C o m p l e t e d F o r m 1 c o d e f o r t h e Fuel Economy a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Fuel_Economy
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void calculateButton_Click(object sender, EventArgs e)
21
{
22
double miles;
// To hold miles driven
23
double gallons; // To hold gallons used
24
double mpg;
// To hold MPG
25
26
// Get the miles driven and assign it to
27
// the miles variable.
28
miles = double.Parse(milesTextBox.Text);
29
30
// Get the gallons used and assign it to
31
// the gallons variable.
32
gallons = double.Parse(gallonsTextBox.Text);
33
34
// Calculate MPG.
35
mpg = miles / gallons;
36
37
// Display the MPG in the mpgLabel control.
38
mpgLabel.Text = mpg.ToString();
39
}
40
41
private void exitButton_Click(object sender, EventArgs e)
42
{
43
// Close the form.
44
this.Close();
45
}
46
}
47 }
3 .6
F o r m a t t i n g N u m b e r s w i t h t h e ToString M e t h o d
149
C h e c k p o in t
3 .2 5
W h a t m e t h o d c o n v e r t s t h e s t r i n g l i t e r a l "40" t o a v a l u e o f t h e int d a t a t y p e ?
3 .2 6
W r i t e a s t a t e m e n t t h a t c o n v e r t s e a c h o f t h e f o l l o w i n g string v a l u e s t o t h e decimal
d a t a t y p e u s i n g t h e decimal.Parse m e t h o d .
a . "9.05"
b . grandTotal
c . "50"
d . priceTextBox.Text
3 .2 7
S u p p o s e a n a p p l i c a t i o n h a s a decimal v a r i a b l e n a m e d total a n d a L a b e l c o n t r o l
n a m e d totalLabel . W h a t w i l l b e t h e r e s u l t w h e n t h e f o l l o w i n g a s s i g n m e n t
s ta te m e n t is e x e c u te d ?
totalLabel.Text = total;
3 .2 8
W r ite a s ta te m e n t th a t d is p la y s e a c h
message b o x .
o f th e fo llo w in g n u m e r ic v a r ia b le s in
a
a . grandTotal
d . highScore
c . sum
b . width
3 .2 9
3 .6
W r i t e a s t a t e m e n t t h a t w i l l s t o r e t h e v a l u e o f a n int v a r i a b l e n a m e d result i n t h e
T e x t p r o p e r t y o f a L a b e l c o n t r o l n a m e d resultLabel.
F o r m a t t i n g N u m b e r s w i t h t h e ToString M e t h o d
C O N C E P T :
T h e ToString m e t h o d c a n o p t i o n a l l y f o r m a t a n u m b e r t o a p p e a r i n a
s p e c ific w a y .
W h e n y o u d is p la y la r g e n u m b e r s , y o u u s u a lly w a n t to fo r m a t th e m w ith c o m m a s s o th e y
a r e e a s y to r e a d . F o r e x a m p le , 4 8 7 ,6 3 4 ,7 8 9 .0 is e a s ie r to r e a d th a n 4 8 7 6 3 4 7 8 9 .0 . A ls o ,
w h e n y o u d is p la y a m o u n ts o f m o n e y , y o u u s u a lly w a n t to r o u n d th e m to tw o d e c im a l
p la c e s a n d d is p la y a c u r r e n c y s y m b o l, s u c h a s a d o lla r s ig n ($ ).
W h e n y o u c a l l t h e ToString m e t h o d , y o u c a n o p t i o n a l l y p a s s a f o r m a t t i n g s t r i n g a s a n
a r g u m e n t to th e m e th o d . T h e fo r m a ttin g s tr in g in d ic a te s th a t y o u w a n t th e n u m b e r to
a p p e a r fo r m a tte d in a s p e c ific w a y w h e n it is r e tu r n e d a s a s tr in g fr o m th e m e th o d . F o r
e x a m p l e , w h e n y o u p a s s t h e f o r m a t t i n g s t r i n g "c" t o t h e ToString m e t h o d , t h e n u m b e r i s
r e tu r n e d fo r m a tte d a s c u r r e n c y . A s s u m in g th a t y o u a r e in th e U n ite d S ta te s , n u m b e r s fo r m a tte d a s c u r r e n c y a r e p r e c e d e d b y a d o lla r s ig n ($ ), a r e r o u n d e d to tw o d e c im a l p la c e s , a n d
h a v e c o m m a s e p a r a to r s in s e r te d a s n e c e s s a r y . T h e fo llo w in g c o d e s a m p le d e m o n s tr a te s :
decimal amount = 123456789.45678m;
MessageBox.Show(amount.ToString("c"));
N o t i c e i n t h e s e c o n d s t a t e m e n t t h a t t h e "c" f o r m a t t i n g s t r i n g i s p a s s e d t o t h e amount
v a r i a b l e ’ s ToString m e t h o d . T h e m e s s a g e b o x t h a t t h e s t a t e m e n t d i s p l a y s a p p e a r s a s
s h o w n in F ig u r e 3 -1 9 .
T h e r e a r e s e v e r a l o t h e r f o r m a t s t r i n g s t h a t y o u c a n u s e w i t h t h e ToString m e t h o d , a n d
e a c h p r o d u c e s a d iffe r e n t ty p e o f fo r m a ttin g . T a b le 3 -9 s h o w s a fe w o f th e m .
150
C h a p te r 3
P r o c e s s in g D a t a
F ig u r e 3 -1 9
A n u m b e r fo rm a tte d a s c u rre n c y
T a b le 3 -9
A fe w o f t h e fo r m a t t in g s t r in g s
F o r m a t S tr in g
D e s c r ip tio n
"N" or "n"
N umber format
"F" or "f"
Fixed-point scientific format
"E" or "e"
Exponential scientific format
"C" or "c"
Currency format
"P" or "p"
Percent format
N u m b e r F o r m a t
N u m b e r f o r m a t ( "n" o r "N") d i s p l a y s n u m e r i c v a l u e s w i t h c o m m a s e p a r a t o r s a n d a d e c i m a l p o in t. B y d e fa u lt, tw o d ig its d is p la y to th e r ig h t o f th e d e c im a l p o in t. N e g a tiv e v a lu e s
are displayed with a leading minus sign. An example is −2,345.67.
F ix e d -P o in t F o r m a t
Fixed-point format ("f" or "F") displays numeric values with no thousands separator and
a decimal point. By default, two digits display to the right of the decimal point. N egative
values are displayed with a leading minus (−) sign. An example is −2345.67.
E x p o n e n t ia l F o r m a t
Exponential format ("e" or "E") displays numeric values in scientific notation. The number
is displayed with a single digit to the left of the decimal point. The letter e appears in front
of the exponent, and the exponent has a leading + or + sign. By default, six digits display to
the right of the decimal point, and a leading minus sign is used if the number is negative.
An example is −2.345670e+003.
C u r r e n c y F o r m a t
Currency format ("c" or "C") displays a leading currency symbol (such as $), digits,
comma separators, and a decimal point. By default, two digits display to the right of the
decimal point. N egative values are surrounded by parentheses. An example of a negative
value is ($2,345.67).
U s in g P e r c e n t F o r m a t
Percent format ("p" or "P") causes the number to be multiplied by 100 and displayed with
a trailing space and % sign. By default, two digits display to the right of the decimal point.
N egative values are displayed with a leading minus sign. For example, the number 0.125
would be formatted as 12.5 % and the number −0.2345 would be formatted as −23.45 %.
3 .6
F o r m a t t i n g N u m b e r s w i t h t h e ToString M e t h o d
S p e c ify in g t h e P r e c is io n
E a c h n u m e r ic fo r m a t s tr in g c a n o p tio n a lly b e fo llo w e d b y a n in te g e r th a t in d ic a te s h o w
m a n y d i g i t s t o d i s p l a y a f t e r t h e d e c i m a l p o i n t . F o r e x a m p l e , t h e f o r m a t "n3" d i s p l a y s
th r e e d ig its a fte r th e d e c im a l p o in t. T a b le 3 -1 0 s h o w s a v a r ie ty o f n u m e r ic fo r m a ttin g
e x a m p le s , b a s e d o n th e N o r th A m e r ic a n lo c a le .
T a b le 3 -1 0
N u m e r ic fo r m a t t in g e x a m p le s ( N o r t h A m e r ic a n lo c a le )
Nu mb er
F o r m a t S tr in g
ToString( ) R e t u r n V a l u e
12.3
"n3"
12.300
12.348
"n2"
12.35
1234567.1
"N"
1,234,567.10
123456.0
"f2"
123456.00
123456.0
"e3"
1.235e+005
.234
"P"
23.40 %
−1234567.8
"C"
($1,234,567.80)
R o u n d in g
R o u n d in g c a n o c c u r w h e n th e n u m b e r o f d ig its y o u h a v e s p e c ifie d a fte r th e d e c im a l p o in t
in th e fo r m a t s tr in g is s m a lle r th a n th e p r e c is io n o f th e n u m e r ic v a lu e . S u p p o s e , fo r e x a m p l e , t h a t t h e v a l u e 1 . 2 3 5 w e r e d i s p l a y e d w i t h a f o r m a t s t r i n g o f "n2". T h e n t h e d i s p l a y e d
v a lu e w o u ld b e 1 .2 4 . If th e n e x t d ig it a fte r th e la s t d is p la y e d d ig it is 5 o r h ig h e r , th e la s t
d i s p l a y e d d i g i t i s r o u n d e d away from zero. T a b l e 3 - 1 1 s h o w s e x a m p l e s o f r o u n d i n g u s i n g
a f o r m a t s t r i n g o f "n2".
T a b le 3 -1 1
R o u n d i n g e x a m p l e s u s i n g t h e "n2" d i s p l a y f o r m a t s t r i n g
Nu mb er
F o rmatted As
1.234
1.23
1.235
1.24
1.238
1.24
−1.234
−1.23
−1.235
−1.24
−1.238
−1.24
U s in g L e a d in g Z e r o s w it h In t e g e r V a lu e s
Y o u c a n u s e t h e "d" o r "D" f o r m a t t i n g s t r i n g s w i t h i n t e g e r s t o s p e c i f y t h e m i n i m u m
w id th fo r d is p la y in g th e n u m b e r . L e a d in g z e r o s a r e in s e r te d if n e c e s s a r y . T a b le 3 -1 2
s h o w s e x a m p le s .
T a b le 3 -1 2
F o r m a t t i n g i n t e g e r s u s i n g t h e "d" o r "D" f o r m a t t i n g s t r i n g s
In te g e r V a lu e
F o r m a t S tr in g
F o rmatted As
23
"d"
23
23
"d4"
0023
1
"d2"
01
151
152
C h a p te r 3
P r o c e s s in g D a t a
In T u to r ia l 3 -3 , y o u w ill c r e a te a n a p p lic a tio n th a t u s e s c u r r e n c y fo r m a ttin g to d is p la y a
d o lla r a m o u n t.
T u t o r ia l 3 -3 :
C r e a t i n g t h e Sa le Price Ca lcula tor A p p l i c a t i o n w i t h C u r r e n c y
F o r m a t t in g
VideoNot e
T u to r ia l 3 -3 :
C r e a tin g th e
Sale Price
Calculator
A p p lic a tio n
w ith
Cu rren cy
F o r m a ttin g
If y o u a r e w r itin g a p r o g r a m th a t w o r k s w ith a p e r c e n ta g e , y o u h a v e to m a k e s u r e th a t th e
p e r c e n ta g e ’s d e c im a l p o in t is in th e c o r r e c t lo c a tio n b e fo r e d o in g a n y m a th w ith th e p e r c e n ta g e . T h is is e s p e c ia lly tr u e w h e n th e u s e r e n te r s a p e r c e n ta g e a s in p u t. M o s t u s e r s w ill
en ter th e n u mb er 5 0 to mean 5 0 p ercen t, 2 0 to mean 2 0 p ercen t, an d so fo rth . Befo re yo u
p e r fo r m a n y c a lc u la tio n s w ith s u c h a p e r c e n ta g e , y o u h a v e to d iv id e it b y 1 0 0 to m o v e its
d e c im a l p o in t to th e le ft tw o p la c e s .
S u p p o s e a r e ta il b u s in e s s is p la n n in g to h a v e a s to r e w id e s a le in w h ic h th e p r ic e s o f a ll
ite m s w ill b e r e d u c e d b y a s p e c ifie d p e r c e n ta g e . In th is tu to r ia l, y o u w ill c r e a te a n a p p lic a tio n to c a lc u la te th e s a le p r ic e o f a n ite m a fte r th e d is c o u n t is s u b tr a c te d . H e r e is th e a lg o r ith m , e x p r e s s e d a s p s e u d o c o d e :
1 . Get the original price of the item.
2 . Get the discount percentage. (For example, 20 is entered for 20 percent.)
3 . D ivide the percentage amount by 100 to move the decimal point to the
correct location.
4 . M ultiply the percentage by the original price. This is the amount of the discount.
5 . Subtract the discount from the original price. This is the sale price.
6 . D isplay the sale price.
F ig u r e 3 -2 0 s h o w s th e a p p lic a tio n ’s fo r m , w ith th e n a m e s o f a ll th e c o n tr o ls . W h e n th e
a p p l i c a t i o n r u n s , t h e u s e r e n t e r s a n i t e m ’ s o r i g i n a l p r i c e i n t o t h e originalPriceTextBox
c o n t r o l a n d t h e d i s c o u n t p e r c e n t a g e i n t o t h e discountPercentageTextBox c o n t r o l .
W h e n t h e u s e r c l i c k s t h e calculateButton c o n t r o l , t h e a p p l i c a t i o n c a l c u l a t e s t h e i t e m ’ s
s a l e p r i c e a n d d i s p l a y s t h e r e s u l t i n t h e salePriceLabel c o n t r o l . T h e exitButton c o n t r o l
c lo s e s th e a p p lic a tio n ’s fo r m .
F ig u r e 3 -2 0
T h e Sa le Price Ca lcula tor f o r m
originalPriceTextBox
discountPercentageTextBox
originalPricePromptLabel
discPercentagePromptLabel
salePriceLabel
outputDescriptionLabel
calculateButton
S t e p 1 :
exitButton
S ta r t V is u a l S tu d io a n d b e g in a n e w W in d o w s F o r m s A p p lic a tio n p r o je c t
n a m e d Sale Price Calculator.
3 .6
S t e p 2 :
F o r m a t t i n g N u m b e r s w i t h t h e ToString M e t h o d
S e t u p th e a p p lic a tio n ’s fo r m , a s s h o w n in F ig u r e 3 -2 0 . N o tic e th a t th e fo r m ’s
T e x t p r o p e r t y i s s e t t o Sale Price Calculator. T h e n a m e s o f t h e c o n t r o l s a r e
s h o w n in th e fig u r e . A s y o u p la c e e a c h o f th e c o n tr o ls o n th e fo r m , r e fe r to
T a b le 3 -1 3 fo r th e r e le v a n t p r o p e r ty s e ttin g s .
T a b le 3 -1 3
C o n t r o l p r o p e r t y s e t t in g s
Co n tro l Name
Co n tro l Typ e
P r o p e r ty S e ttin g s
originalPricePromptLabel
Lab el
T e x t : Enter the item’s original price:
discPercentagePromptLabel
Lab el
T e x t : Enter the discount percentage:
outputDescriptionLabel
Lab el
T e x t : Sale price:
originalPriceTextBox
Tex tBo x
N o p r o p e r tie s c h a n g e d
discountPercentageTextBox
Tex tBo x
N o p r o p e r tie s c h a n g e d
salePriceLabel
Lab el
A u to S iz e : F a ls e
B o r d e r S ty le : F ix e d S in g le
Tex t: (Th e co n ten ts o f th e Tex t
p r o p e r ty h a v e b e e n e r a s e d .)
T e x tA lig n : M id d le C e n te r
calculateButton
Bu tto n
T e x t : Calculate Sale Price
exitButton
Bu tto n
T e x t : Exit
S t e p 3 :
O n c e y o u h a v e s e t u p th e fo r m w ith its c o n tr o ls , y o u c a n c r e a te th e C lic k
e v e n t h a n d le r s fo r th e B u tto n c o n tr o ls . A t th e e n d o f th is tu to r ia l, P r o g r a m
3 -3 s h o w s th e c o m p le te d c o d e fo r th e fo r m . Y o u w ill b e in s tr u c te d to r e fe r to
P r o g r a m 3 -3 a s y o u w r ite th e e v e n t h a n d le r s . (R e m e m b e r , th e lin e n u m b e r s
th a t a r e s h o w n in P r o g r a m 3 -3 a r e n o t p a r t o f th e p r o g r a m . T h e y a r e s h o w n
fo r r e fe r e n c e o n ly .)
I n t h e Designer, d o u b l e - c l i c k t h e calculateButton c o n t r o l . T h i s w i l l o p e n t h e
c o d e e d i t o r , a n d y o u w i l l s e e a n e m p t y e v e n t h a n d l e r n a m e d calculateButton_
Click. C o m p l e t e t h e calculateButton_Click e v e n t h a n d l e r b y t y p i n g t h e
c o d e s h o w n in lin e s 2 2 – 4 3 in P r o g r a m 3 -3 .
L e t’s ta k e a c lo s e r lo o k a t th e c o d e :
L i n e 2 2 : T h i s s t a t e m e n t d e c l a r e s a decimal v a r i a b l e n a m e d originalPrice.
T h is v a r ia b le w ill h o ld th e ite m ’s o r ig in a l p r ic e .
L i n e 2 3 : T h i s s t a t e m e n t d e c l a r e s a decimal v a r i a b l e n a m e d discountPercentage.
T h is v a r ia b le w ill h o ld th e d is c o u n t p e r c e n ta g e .
L i n e 2 4 : T h i s s t a t e m e n t d e c l a r e s a decimal v a r i a b l e n a m e d discountAmount.
T h is v a r ia b le w ill h o ld th e a m o u n t o f d is c o u n t th a t w ill b e ta k e n fr o m th e
ite m ’s o r ig in a l p r ic e . T h is a m o u n t w ill b e c a lc u la te d .
L i n e 2 5 : T h i s s t a t e m e n t d e c l a r e s a decimal v a r i a b l e n a m e d salePrice. T h i s
v a r ia b le w ill h o ld th e ite m ’s s a le p r ic e . T h is a m o u n t w ill b e c a lc u la te d .
L i n e 2 8 : T h i s s t a t e m e n t c o n v e r t s t h e originalPriceTextBox c o n t r o l ’ s T e x t
p r o p e r t y t o a decimal a n d a s s i g n s t h e r e s u l t t o t h e originalPrice v a r i a b l e .
L i n e 3 1 : T h i s s t a t e m e n t c o n v e r t s t h e discountPercentageTextBox c o n t r o l ’ s
T e x t p r o p e r t y t o a decimal a n d a s s i g n s t h e r e s u l t t o t h e discountPercentage
v a r ia b le .
153
154
C h a p te r 3
P r o c e s s in g D a t a
L i n e 3 4 : T h i s s t a t e m e n t d i v i d e s discountPercentage b y 1 0 0 a n d s t o r e s t h e
r e s u l t b a c k i n discountPercentage. T h i s m o v e s t h e d e c i m a l p o i n t i n t h e
discountPercentage v a r i a b l e t o t h e l e f t t w o p l a c e s .
L in e 3 7 : T h is s ta te m e n t c a lc u la te s th e a m o u n t o f th e d is c o u n t. It m u ltip lie s
originalPrice b y discountPercentage a n d a s s i g n s t h e r e s u l t t o
discountAmount.
L in e 4 0 : T h is s ta te m e n t c a lc u la te s th e ite m ’s s a le p r ic e . It s u b tr a c ts th e
discountAmount v a r i a b l e f r o m t h e originalPrice v a r i a b l e a n d a s s i g n s t h e
r e s u l t t o t h e salePrice v a r i a b l e .
L in e 4 3 : T h is s ta te m e n t d is p la y s th e ite m ’s s a le p r ic e a s a c u r r e n c y a m o u n t. It
c o n v e r t s t h e salePrice v a r i a b l e t o a s t r i n g a n d a s s i g n s t h e r e s u l t t o t h e
salePriceLabel c o n t r o l ’ s T e x t p r o p e r t y . N o t i c e t h a t t h e f o r m a t s t r i n g "c"
i s p a s s e d t o t h e salePrice v a r i a b l e ’ s ToString m e t h o d .
S t e p 4 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e exitButton
c o n tr o l. In th e c o d e e d ito r y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
exitButton_Click. C o m p l e t e t h e exitButton_Click e v e n t h a n d l e r b y
ty p in g th e c o d e s h o w n in lin e s 4 8 – 4 9 in P r o g r a m 3 -3 .
S t e p 5 :
S a v e th e p r o je c t. T h e n , p r e s s th e
k e y o n t h e k e y b o a r d o r c l i c k t h e Start
D ebugging b u t t o n ( ) o n t h e t o o l b a r t o c o m p i l e a n d r u n t h e a p p l i c a t i o n .
T e s t th e a p p lic a tio n b y e n te r in g v a lu e s in to th e T e x tB o x e s a n d c lic k in g th e
Calculate Sale Price b u t t o n . T h e s a l e p r i c e i s d i s p l a y e d , s i m i l a r t o F i g u r e 3 - 2 1 .
C l i c k t h e Exit b u t t o n a n d t h e f o r m c l o s e s .
F ig u r e 3 -2 1
T h e Sa le Price Ca lcula tor a p p l i c a t i o n
P r o g r a m 3 -3
C o m p l e t e d F o r m 1 c o d e f o r t h e Sa le Price Ca lcula tor a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
3 .6
F o r m a t t i n g N u m b e r s w i t h t h e ToString M e t h o d
11 namespace Sale_Price_Calculator
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void calculateButton_Click(object sender, EventArgs e)
21
{
22
decimal originalPrice;
// The item’s original price
23
decimal discountPercentage; // The discount percentage
24
decimal discountAmount;
// The amount of discount
25
decimal salePrice;
// The item’s sale price
26
27
// Get the item’s original price.
28
originalPrice = decimal.Parse(originalPriceTextBox.Text);
29
30
// Get the discount percentage.
31
discountPercentage = decimal. Parse(discountPercentageTextBox.Text);
32
33
// Move the percentage’s decimal point left two spaces.
34
discountPercentage = discountPercentage / 100;
35
36
// Calculate the amount of the discount.
37
discountAmount = originalPrice * discountPercentage;
38
39
// Calculate the sale price.
40
salePrice = originalPrice − discountAmount;
41
42
// Display the sale price.
43
salePriceLabel.Text = salePrice.ToString("c");
44
}
45
46
private void exitButton_Click(object sender, EventArgs e)
47
{
48
// Close the form.
49
this.Close();
50
}
51
}
52 }
C h e c k p o in t
3 .3 0
W r ite a p r o g r a m m in g s ta te m e n t th a t d is p la y s th e s tr in g v a lu e o f a v a r ia b le n a m e d
salary i n a m e s s a g e b o x u s i n g c u r r e n c y f o r m a t .
3 .3 1
T h e fo llo w in g v a r ia b le n a m e s g iv e a n in d ic a tio n o f th e d a ta e a c h s to r e s . F o r e a c h
v a r ia b le , s p e c ify th e fo r m a t s tr in g th a t y o u th in k is m o s t a p p r o p r ia te .
a . discountPercentage
b . atomicWeight
c . retailPrice
d . quantityPurchased
e . degreesKelvin
155
156
C h a p te r 3
P r o c e s s in g D a t a
3 .3 2
W h a t v a lu e w ill b e d is p la y e d in th e m e s s a g e b o x w h e n th e fo llo w in g c o d e s e g m e n t
is e x e c u te d ?
double apples = 12.0;
MessageBox.Show(apples.ToString("n0"));
3 .3 3
E x a m in e th e fo llo w in g in te g e r v a r ia b le s a n d s p e c ify th e n u m b e r o f le a d in g z e r o s to
u s e w ith th e do r Dfo r m a t s tr in g s s o th a t a ll th e n u m b e r s a r e e q u a l in w id th .
int valueA = 234, valueB = 56, valueC = 7, valueD = 89123;
3 .3 4
3 .7
W r i t e a p r o g r a m m i n g s t a t e m e n t t h a t u s e s t h e ToString m e t h o d o f a v a r i a b l e
n a m e d millimeters s o t h a t i t d i s p l a y s a p r e c i s i o n o f f o u r d i g i t s a f t e r t h e d e c i m a l
p o in t in fix e d -p o in t s c ie n tific fo r m a t.
S im p le E x c e p t io n H a n d lin g
C O N C E P T :
A n e x c e p tio n is a n u n e x p e c te d e r r o r th a t h a p p e n s w h ile a p r o g r a m is
r u n n in g . If a n e x c e p tio n is n o t h a n d le d b y th e p r o g r a m , th e p r o g r a m w ill
a b r u p tly h a lt.
A n e x c e p tio n is a n u n e x p e c te d e r r o r th a t o c c u r s w h ile a p r o g r a m is r u n n in g , c a u s in g th e
p r o g r a m to h a lt if th e e r r o r is n o t p r o p e r ly d e a lt w ith . E x c e p tio n s a r e u s u a lly c a u s e d b y
c ir c u m s ta n c e s th a t a r e b e y o n d th e p r o g r a m m e r ’s c o n tr o l. F o r e x a m p le , s u p p o s e th e u s e r
h a s e n te r e d a v a lu e in to a T e x tB o x , a n d th a t v a lu e is e x p e c te d to b e a n u m b e r . T h e p r o g r a m u s e s o n e o f t h e Parse m e t h o d s t o c o n v e r t t h e c o n t r o l ’ s T e x t p r o p e r t y t o a n u m e r i c
d a ta ty p e , b u t th e s tr in g c o n ta in s in v a lid c h a r a c te r s a n d it c a n n o t b e c o n v e r te d . T h e
Parse m e t h o d c a n n o t c o n t i n u e , s o a n e x c e p t i o n o c c u r s . ( T o u s e t h e p r o p e r t e r m i n o l o g y , w e s a y th a t a m e th o d th r o w s a n e x c e p tio n w h e n a n u n e x p e c te d e r r o r o c c u r s a n d it
c a n n o t c o n tin u e o p e r a tin g .)
L e t ’ s l o o k a t a n e x a m p l e . I f y o u h a v e c o m p l e t e d t h e Fuel Economy p r o j e c t f r o m T u t o r i a l
3 - 2 , o p e n i t i n V i s u a l S t u d i o a n d t h e n e i t h e r c l i c k t h e Start D ebugging b u t t o n ( ) o r
p ress
t o r u n t h e a p p l i c a t i o n . O n t h e a p p l i c a t i o n ’ s f o r m , e n t e r 300 f o r t h e n u m b e r o f
m ile s d r iv e n a n d th e n e n te r a n o n n u m e r ic s e q u e n c e o f c h a r a c te r s fo r th e g a llo n s o f g a s
u s e d . F i g u r e 3 - 2 2 s h o w s a n e x a m p l e w h e r e t h e u s e r h a s e n t e r e d wxyz. T h e n , c l i c k t h e
Calculate M PG b u t t o n . B e c a u s e t h e i n v a l i d s t r i n g t h a t y o u e n t e r e d f o r t h e g a l l o n s o f g a s
c a n n o t b e c o n v e r t e d t o a double, a n e x c e p t i o n i s t h r o w n . T h e a p p l i c a t i o n s t o p s r u n n i n g
a n d V is u a l S tu d io g o e s in to a s p e c ia l m o d e k n o w n a s b r e a k m o d e . T h e w in d o w s h o w n in
F ig u r e 3 -2 3 is d is p la y e d , a n d th e lin e o f c o d e th a t w a s e x e c u tin g w h e n th e e x c e p tio n w a s
th r o w n is h ig h lig h te d .
F ig u r e 3 -2 2
In v a lid d a t a e n t e r e d fo r g a llo n s
162
C h a p te r 3
P r o c e s s in g D a t a
L i n e 3 0 : T h i s s t a t e m e n t c o n v e r t s t h e test1TextBox c o n t r o l ’ s T e x t p r o p e r t y
t o a double a n d a s s i g n s t h e r e s u l t t o t h e test1 v a r i a b l e .
L i n e 3 1 : T h i s s t a t e m e n t c o n v e r t s t h e test2TextBox c o n t r o l ’ s T e x t p r o p e r t y
t o a double a n d a s s i g n s t h e r e s u l t t o t h e test2 v a r i a b l e .
L i n e 3 2 : T h i s s t a t e m e n t c o n v e r t s t h e test3TextBox c o n t r o l ’ s T e x t p r o p e r t y
t o a double a n d a s s i g n s t h e r e s u l t t o t h e test3 v a r i a b l e .
L i n e 3 5 : T h i s s t a t e m e n t c a l c u l a t e s t h e a v e r a g e o f t h e test1, test2, a n d
test3 v a r i a b l e s a n d a s s i g n s t h e r e s u l t t o t h e average v a r i a b l e .
L i n e 3 9 : T h i s s t a t e m e n t c o n v e r t s t h e average v a r i a b l e t o a s t r i n g a n d a s s i g n s
t h e r e s u l t t o t h e averageLabel c o n t r o l ’ s T e x t p r o p e r t y . N o t i c e t h a t t h e "n1"
f o r m a t s t r i n g i s p a s s e d a s a n a r g u m e n t t o t h e ToString m e t h o d . T h i s c a u s e s
th e n u m b e r to b e r o u n d e d to o n e d e c im a l p o in t.
S t e p 4 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e clearButton
c o n tr o l. In th e c o d e e d ito r y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
clearButton_Click. C o m p l e t e t h e clearButton_Click e v e n t h a n d l e r b y
ty p in g th e c o d e s h o w n in lin e s 5 0 – 5 4 in P r o g r a m 3 -4 .
L i n e s 5 1 – 5 3 : E a c h o f t h e s e s t a t e m e n t s a s s i g n s a n e m p t y s t r i n g ( "") t o t h e
T e x t p r o p e r ty o f o n e o f th e T e x tB o x c o n tr o ls . W h e n th e s e s ta te m e n ts h a v e
fin is h e d e x e c u tin g , th e T e x tB o x c o n tr o ls a p p e a r e m p ty .
L i n e 5 4 : T h i s s t a t e m e n t a s s i g n s a n e m p t y s t r i n g ( "") t o t h e averageLabel c o n tr o l’s T e x t p r o p e r ty . A fte r th e s ta te m e n t h a s e x e c u te d , th e la b e l a p p e a r s e m p ty .
S t e p 5 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e exitButton
c o n tr o l. In th e c o d e e d ito r y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
exitButton_Click. C o m p l e t e t h e exitButton_Click e v e n t h a n d l e r b y
ty p in g th e c o d e s h o w n in lin e s 5 9 – 6 0 in P r o g r a m 3 -4 .
S t e p 6 :
S a v e th e p r o je c t. T h e n , p r e s s th e
k e y o n t h e k e y b o a r d o r c l i c k t h e Start
D ebugging b u t t o n ( ) o n t h e t o o l b a r t o c o m p i l e a n d r u n t h e a p p l i c a t i o n .
F ir s t, te s t th e a p p lic a tio n b y e n te r in g v a lid n u m e r ic v a lu e s in to th e T e x tB o x e s a n d c l i c k i n g t h e Calculate Average b u t t o n . A t e s t a v e r a g e s h o u l d b e
d is p la y e d , s im ila r to th e im a g e s h o w n o n th e le ft in F ig u r e 3 -2 7 .
F ig u r e 3 -2 7
T h e Test Avera ge a p p l i c a t i o n
Test scores entered and
an average displayed.
Invalid input given and
an exception reported.
3 .7
S im p le E x c e p t io n H a n d lin g
N e x t , c l i c k t h e Clear b u t t o n t o c l e a r t h e T e x t B o x e s a n d t h e a v e r a g e . T h e n
e n t e r a n o n n u m e r i c v a l u e f o r t e s t 1 , a n d c l i c k t h e Calculate Average b u t t o n .
A n e x c e p tio n w ill b e th r o w n , a n d y o u s h o u ld s e e th e m e s s a g e b o x s h o w n in
th e im a g e o n th e r ig h t in F ig u r e 3 -2 7 .
C o n tin u e to te s t th e a p p lic a tio n a s y o u w is h . W h e n y o u a r e fin is h e d , c lic k th e
Exit b u t t o n a n d t h e f o r m s h o u l d c l o s e .
P r o g r a m 3 -4
C o m p l e t e d F o r m 1 c o d e f o r t h e Test Avera ge a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Test_Average
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void calculateButton_Click(object sender, EventArgs e)
21
{
22
try
23
{
24
double test1;
// To hold test score #1
25
double test2;
// To hold test score #2
26
double test3;
// To hold test score #3
27
double average; // To hold the average test score
28
29
// Get the three test scores.
30
test1 = double.Parse(test1TextBox.Text);
31
test2 = double.Parse(test2TextBox.Text);
32
test3 = double.Parse(test3TextBox.Text);
33
34
// Calculate the average test score.
35
average = (test1 + test2 + test3) / 3.0;
36
37
// Display the average test score, with
38
// the output rounded to 1 decimal point.
39
averageLabel.Text = average.ToString("n1");
40
}
41
catch (Exception ex)
42
{
43
// Display the default error message.
44
MessageBox.Show(ex.Message);
45
}
46
}
47
163
164
C h a p te r 3
P r o c e s s in g D a t a
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 }
private void clearButton_Click(object sender, EventArgs e)
{
// Clear the input and output controls.
test1TextBox.Text = "";
test2TextBox.Text = "";
test3TextBox.Text = "";
averageLabel.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
C h e c k p o in t
3 .8
3 .3 5
W h a t c a n c a u s e a n a p p lic a tio n to th r o w a n e x c e p tio n ?
3 .3 6
H o w d o y o u g e t o u t o f b r e a k m o d e w h e n a n e x c e p tio n is th r o w n ?
3 .3 7
W h a t k i n d o f c o d e d o e s t h e t r y b l o c k o f a try- catch s t a t e m e n t c o n t a i n ?
3 .3 8
W h a t c a u s e s t h e p r o g r a m t o j u m p t o t h e catch c l a u s e a n d e x e c u t e t h e c a t c h b l o c k
o f a try- catch s t a t e m e n t ?
3 .3 9
H o w c a n y o u d is p la y th e d e fa u lt e r r o r m e s s a g e w h e n a n e x c e p tio n is th r o w n ?
3 .4 0
W r i t e a try- catch s t a t e m e n t f o r a n a p p l i c a t i o n t h a t c a l c u l a t e s t h e s u m o f t w o
w h o le n u m b e r s a n d d is p la y s th e r e s u lt. T h e a p p lic a tio n u s e s tw o T e x tB o x c o n tr o ls
n a m e d value1TextBox a n d value2TextBox t o g a t h e r t h e i n p u t a n d a L a b e l c o n t r o l n a m e d sumLabel t o d i s p l a y t h e r e s u l t .
U s in g N a m e d C o n s t a n t s
C O N C E P T :
A n a m e d c o n s ta n t is a n a m e th a t r e p r e s e n ts a v a lu e th a t c a n n o t b e c h a n g e d
d u r in g th e p r o g r a m ’s e x e c u tio n .
A s s u m e th a t th e fo llo w in g s ta te m e n t a p p e a r s in a b a n k in g p r o g r a m th a t c a lc u la te s d a ta
p e r ta in in g to lo a n s :
amount = balance * 0.069;
In s u c h a p r o g r a m , tw o p o te n tia l p r o b le m s a r is e . F ir s t, it is n o t c le a r to a n y o n e o th e r th a n
th e o r ig in a l p r o g r a m m e r w h a t 0 .0 6 9 is . It a p p e a r s to b e a n in te r e s t r a te , b u t in s o m e s itu a tio n s , th e r e a r e fe e s a s s o c ia te d w ith lo a n p a y m e n ts . H o w c a n th e p u r p o s e o f th is s ta te m e n t b e d e te r m in e d w ith o u t p a in s ta k in g ly c h e c k in g th e r e s t o f th e p r o g r a m ?
T h e s e c o n d p r o b le m o c c u r s if th is n u m b e r is u s e d in o th e r c a lc u la tio n s th r o u g h o u t th e
p r o g r a m a n d m u s t b e c h a n g e d p e r io d ic a lly . A s s u m in g th e n u m b e r is a n in te r e s t r a te , w h a t
if th e r a te c h a n g e s fr o m 6 .9 p e r c e n t to 7 .2 p e r c e n t? T h e p r o g r a m m e r w o u ld h a v e to
search th ro u gh th e so u rce co d e fo r every o ccu rren ce o f th e n u mb er.
3 .9
D e c la r in g V a r ia b le s a s F ie ld s
B o th th e s e p r o b le m s c a n b e a d d r e s s e d b y u s in g n a m e d c o n s ta n ts . A n a m e d c o n s ta n t is a
n a m e th a t r e p r e s e n ts a v a lu e th a t c a n n o t b e c h a n g e d d u r in g th e p r o g r a m ’s e x e c u tio n . T h e
fo llo w in g is a n e x a m p le o f h o w y o u c a n d e c la r e a n a m e d c o n s ta n t in C # :
const double INTEREST_RATE = 0.129;
T h i s s t a t e m e n t d e c l a r e s a n a m e d c o n s t a n t n a m e d INTEREST_RATE i n i t i a l i z e d w i t h t h e v a l u e
0 . 1 2 9 . I t l o o k s l i k e a r e g u l a r v a r i a b l e d e c l a r a t i o n , e x c e p t t h a t t h e w o r d const a p p e a r s
b e fo r e th e d a ta ty p e n a m e a n d th e n a m e o f th e v a r ia b le is w r itte n in u p p e r c a s e c h a r a c te r s .
T h e k e y w o r d const i s a q u a l i f i e r t h a t t e l l s t h e c o m p i l e r t o m a k e t h e v a r i a b l e r e a d o n l y . I f a
s ta te m e n t a tte m p ts to c h a n g e th e c o n s ta n t’s v a lu e , a n e r r o r w ill o c c u r w h e n th e p r o g r a m is
b e in g c o m p ile d . W h e n y o u d e c la r e a n a m e d c o n s ta n t, a n in itia liz a tio n v a lu e is r e q u ir e d .
It is n o t r e q u ir e d th a t th e c o n s ta n t n a m e b e w r itte n in u p p e r c a s e le tte r s , b u t m a n y p r o g r a m m e r s p r e fe r to w r ite th e m th is w a y s o th e y a r e e a s ily d is tin g u is h a b le fr o m r e g u la r
v a r ia b le n a m e s . W h e n y o u a r e r e a d in g a p r o g r a m ’s c o d e a n d y o u s e e a n u p p e r c a s e id e n tifie r , y o u k n o w in s ta n tly th a t it is a c o n s ta n t.
N O T E : W r itin g th e n a m e s o f c o n s ta n ts in u p p e r c a s e le tte r s is tr a d itio n a l in m a n y
p r o g r a m m in g la n g u a g e s , a n d th a t p r a c tic e is fo llo w e d in th is b o o k . W ith in th e C #
c o m m u n ity , s o m e p r o g r a m m e r s a d h e r e to th is p r a c tic e a n d s o m e d o n o t. In th e c la s s r o o m , y o u s h o u ld u s e th e n a m in g c o n v e n tio n th a t y o u r in s tr u c to r p r e fe r s .
A n a d v a n ta g e o f u s in g n a m e d c o n s ta n ts is th a t th e y m a k e p r o g r a m s m o r e s e lf-e x p la n a to r y .
Th e statemen t
amount = balance * 0.069;
can b e ch an ged to read
amount = balance * INTEREST_RATE;
A n e w p r o g r a m m e r c a n r e a d th e s e c o n d s ta te m e n t a n d k n o w w h a t is h a p p e n in g . It is e v id e n t t h a t balance i s b e i n g m u l t i p l i e d b y t h e i n t e r e s t r a t e . A n o t h e r a d v a n t a g e t o t h i s
a p p r o a c h is th a t w id e s p r e a d c h a n g e s c a n e a s ily b e m a d e to th e p r o g r a m . L e t’s s a y th e
in te r e s t r a te a p p e a r s in a d o z e n d iffe r e n t s ta te m e n ts th r o u g h o u t th e p r o g r a m . W h e n th e
r a te c h a n g e s , th e in itia liz a tio n v a lu e in th e d e c la r a tio n o f th e n a m e d c o n s ta n t is th e o n ly
v a lu e th a t n e e d s to b e m o d ifie d . If th e r a te in c r e a s e s to 7 .2 p e r c e n t, th e d e c la r a tio n c a n b e
c h a n g e d to th e fo llo w in g :
const double INTEREST_RATE = 0.072;
T h e n e w v a l u e o f 0 . 0 7 2 w i l l t h e n b e u s e d i n e a c h s t a t e m e n t t h a t u s e s t h e INTEREST_RATE
c o n s ta n t. In T u to r ia l 3 -5 , y o u w ill c r e a te a n a p p lic a tio n th a t u s e s n a m e d c o n s ta n ts .
3 .9
D e c la r in g V a r ia b le s a s F ie ld s
C O N C E P T :
A fie ld is a v a r ia b le th a t is d e c la r e d a t th e c la s s le v e l. A fie ld ’s s c o p e is th e
e n tir e c la s s .
S o fa r in th is c h a p te r , a ll th e v a r ia b le s w ith w h ic h w e h a v e w o r k e d h a v e b e e n lo c a l v a r ia b le s . A lo c a l v a r ia b le is d e c la r e d in s id e a m e th o d a n d is v is ib le o n ly to s ta te m e n ts in th a t
m e th o d . A n o th e r ty p e o f v a r ia b le is a fie ld , w h ic h is a v a r ia b le th a t is d e c la r e d in s id e a
c la s s b u t n o t in s id e o f a n y m e th o d . A fie ld ’s s c o p e is th e e n tir e c la s s , s o w h e n y o u d e c la r e
a fie ld , a ll th e m e th o d s in th e c la s s c a n a c c e s s th e v a r ia b le .
165
166
C h a p te r 3
P r o c e s s in g D a t a
T y p ic a lly , fie ld s a r e d e c la r e d a t th e to p o f a c la s s d e c la r a tio n , b e fo r e a n y m e th o d s .
F ig u r e 3 -2 8 s h o w s w h e r e y o u w o u ld w r ite fie ld d e c la r a tio n s in s id e a fo r m c la s s . W h e n
y o u a r e a b o u t to w r ite a fie ld d e c la r a tio n , y o u c a n in s e r t s o m e b la n k lin e s a fte r th e
c l a s s ’ s o p e n i n g b r a c e ( {) a n d w r i t e t h e f i e l d d e c l a r a t i o n i n t h a t s p a c e .
F ig u r e 3 -2 8
W h e r e t o in s e r t fie ld d e c la r a t io n s
Insert field declarations here.
L e t’s lo o k a t a n e x a m p le o f a fie ld d e c la r a tio n . A s s u m e th a t th e fo llo w in g s ta te m e n t
a p p e a r s in s id e a c la s s d e c la r a tio n b u t n o t in s id e a n y m e th o d s . T h is s ta te m e n t d e c la r e s a n
int f i e l d n a m e d number, i n i t i a l i z e d w i t h t h e v a l u e 0 :
private int number = 0;
F ie ld d e c la r a tio n s a r e w r itte n lik e a n y o th e r v a r ia b le d e c la r a tio n , e x c e p t th a t a n a c c e s s
m o d i f i e r u s u a l l y a p p e a r s b e f o r e t h e d a t a t y p e . I n t h i s e x a m p l e , t h e k e y w o r d private i s
th e a c c e s s m o d ifie r . A n a c c e s s m o d ifie r s p e c ifie s h o w a c la s s m e m b e r c a n b e a c c e s s e d b y
c o d e o u t s i d e t h e c l a s s . W h e n y o u u s e t h e private a c c e s s m o d i f i e r i n a f i e l d d e c l a r a t i o n ,
th e fie ld c a n n o t b e a c c e s s e d b y c o d e o u ts id e th e c la s s . It c a n b e a c c e s s e d o n ly b y th e m e th o d s th a t a r e in s id e th e c la s s .
I t i s a g o o d p r o g r a m m i n g p r a c t i c e t o m a k e f i e l d s private b e c a u s e private f i e l d s a r e h i d d e n fr o m c o d e o u ts id e th e c la s s . T h a t p r e v e n ts c o d e o u ts id e th e c la s s fr o m c h a n g in g th e
v a lu e s o f a c la s s ’s fie ld s a n d h e lp s p r e v e n t b u g s fr o m c r e e p in g in to y o u r p r o g r a m . Y o u
w ill le a r n m o r e a b o u t th is in C h a p te r 1 0 . U n til th e n , if y o u d e c la r e fie ld s in a c la s s , y o u
s h o u l d g e t i n t h e h a b i t o f m a k i n g t h e m private.
N O T E : T h e r e a r e o th e r a c c e s s m o d ifie r s , a s y o u w ill le a r n la te r in th is b o o k . If y o u
d o n ’t w r ite a n a c c e s s m o d ifie r in a fie ld d e c la r a tio n , C # w ill a u to m a tic a lly m a k e th e
f i e l d private. I t i s s t i l l a g o o d i d e a t o w r i t e t h e private a c c e s s m o d i f i e r b e c a u s e i t
m a k e s i t e v i d e n t t o a n y o n e r e a d i n g t h e c o d e t h a t t h e f i e l d i s i n d e e d private.
I n t h e p r e v i o u s f i e l d - d e c l a r a t i o n e x a m p l e , t h e number f i e l d i s i n i t i a l i z e d w i t h t h e v a l u e 0 .
I f a f i e l d i s a v a r i a b l e o f a n u m e r i c d a t a t y p e ( s u c h a s int, double, o r decimal) , i t w i l l b e
in itia liz e d to 0 b y d e fa u lt if y o u d o n o t e x p lic itly in itia liz e it w ith a v a lu e . It is a lw a y s a
g o o d id e a to e x p lic itly in itia liz e a fie ld , h o w e v e r , e v e n if y o u w a n t it to b e g in w ith th e
v a lu e 0 . T h is c le a r ly in d ic a te s th e fie ld ’s s ta r tin g v a lu e fo r a n y o n e r e a d in g th e c o d e .
W A R N I N G ! I f y o u d o n o t i n i t i a l i z e a string f i e l d , i t b e g i n s w i t h a s p e c i a l v a l u e
k n o w n a s null. A n e r r o r w i l l o c c u r i f y o u a t t e m p t t o u s e a string t h a t i s s e t t o null.
3 .9
D e c la r in g V a r ia b le s a s F ie ld s
In a fo r m , fie ld s a r e u s e fu l fo r s to r in g p ie c e s o f d a ta th a t m u s t b e s h a r e d a m o n g th e fo r m ’s
e v e n t h a n d l e r s . F o r e x a m p l e , i n t h e Chap03 f o l d e r o f t h i s b o o k ’ s s t u d e n t s a m p l e p r o g r a m s (a v a ila b le fo r d o w n lo a d a t w w w .p e a r s o n h ig h e r e d .c o m /g a d d is ), y o u w ill fin d a p r o j e c t n a m e d Field D emo. F i g u r e 3 - 2 9 s h o w s t h e a p p l i c a t i o n ’ s f o r m , a l o n g w i t h t h e n a m e s
o f th e B u tto n c o n tr o ls .
F ig u r e 3 -2 9
T h e Field Demo f o r m
showNameButton
chrisButton
carmenButton
P r o g r a m 3 - 5 s h o w s t h e F o r m 1 c o d e . N o t i c e t h a t i n l i n e 1 6 a string v a r i a b l e n a m e d name
i s d e c l a r e d a s a f i e l d a n d i n i t i a l i z e d w i t h t h e v a l u e "Charles". N e x t , l o o k a t t h e b u t t o n
e v e n t h a n d le r s :
• I n t h e showNameButton_Click e v e n t h a n d l e r , l i n e 2 5 d i s p l a y s a m e s s a g e b o x s h o w i n g t h e v a l u e o f t h e name v a r i a b l e .
• I n t h e chrisButton_Click e v e n t h a n d l e r , l i n e 3 0 c h a n g e s t h e v a l u e o f t h e name
v a r i a b l e t o "Chris".
• I n t h e carmenButton_Click e v e n t h a n d l e r , l i n e 3 5 c h a n g e s t h e v a l u e o f t h e name
v a r i a b l e t o "Carmen".
A s y o u c a n s e e , a l l o f t h e e v e n t h a n d l e r s i n t h e F o r m 1 c l a s s h a v e a c c e s s t o t h e name v a r i a b l e . I f y o u r u n t h e a p p l i c a t i o n a n d c l i c k t h e Show N ame b u t t o n , a m e s s a g e b o x w i l l
a p p e a r d i s p l a y i n g Charles, w h i c h i s t h e n a m e f i e l d ’ s i n i t i a l v a l u e . I f y o u c l i c k t h e Change
N ame to Chris b u t t o n a n d t h e n c l i c k t h e Show N ame b u t t o n , a m e s s a g e b o x w i l l a p p e a r
d i s p l a y i n g Chris. I f y o u c l i c k t h e Change N ame to Carmen b u t t o n a n d t h e n c l i c k t h e
Show N ame b u t t o n , a m e s s a g e b o x w i l l a p p e a r d i s p l a y i n g Carmen.
P r o g r a m 3 -5
F o r m 1 c o d e f o r t h e Field Demo a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Field_Demo
12 {
13
public partial class Form1 : Form
14
{
15
// Declare a private field to hold a name.
16
private string name = "Charles";
17
167
168
C h a p te r 3
P r o c e s s in g D a t a
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 }
public Form1()
{
InitializeComponent();
}
private void showNameButton_Click(object sender, EventArgs e)
{
MessageBox.Show(name);
}
private void chrisButton_Click(object sender, EventArgs e)
{
name = "Chris";
}
private void carmenButton_Click(object sender, EventArgs e)
{
name = "Carmen";
}
}
T h e L ife t im e o f a F ie ld in a F o r m C la s s
W h e n y o u d e c la r e a fie ld in a fo r m c la s s , th e fie ld ’s life tim e is th e tim e d u r in g w h ic h th e
fo r m e x is ts . T h is m e a n s th a t th e fie ld w ill e x is t in m e m o r y a s lo n g a s th e fo r m e x is ts . T h is
is d iffe r e n t th a n th e life tim e o f a lo c a l v a r ia b le , w h ic h e x is ts o n ly w h ile th e m e th o d in
w h ic h it is d e c la r e d is e x e c u tin g . L o c a l v a r ia b le s c o m e a n d g o in m e m o r y , b u t a fo r m ’s
fie ld s e x is t a s lo n g a s th e fo r m e x is ts .
Y o u c a n s e e t h i s i n t h e Field D emo a p p l i c a t i o n . T h e name f i e l d i s c r e a t e d i n m e m o r y w h e n
th e F o r m 1 fo r m is c r e a te d , a n d it c o n tin u e s to e x is t a s lo n g a s F o r m 1 e x is ts . W h e n o n e o f
th e e v e n t h a n d le r s s to r e s a v a lu e in th e fie ld , th a t v a lu e r e m a in s in th e fie ld u n til it is
c h a n g e d a g a in , p e r h a p s b y a d iffe r e n t e v e n t h a n d le r . S o , fie ld s g iv e y o u a w a y o f s to r in g
v a lu e s th a t m u s t n o t d is a p p e a r w h e n a p a r tic u la r m e th o d e n d s .
P r e c a u t io n s
A lth o u g h fie ld s m a k e it e a s y to s h a r e d a ta a m o n g th e m e th o d s in a c la s s , y o u s h o u ld b e
c a r e fu l a b o u t u s in g th e m . T h e o v e r u s e o f fie ld s c a n m a k e d e b u g g in g a c la s s ’s c o d e d iffic u lt, e s p e c ia lly if th e c la s s h a s m a n y m e th o d s . If a n in c o r r e c t v a lu e is b e in g s to r e d in a
fie ld , y o u w ill h a v e to tr a c k d o w n e v e r y s ta te m e n t in th e c la s s th a t a c c e s s e s th e fie ld to
d e te r m in e w h e r e th e in c o r r e c t v a lu e is c o m in g fr o m . In m o s t c a s e s , fie ld s s h o u ld b e u s e d
o n ly fo r d a ta th a t m u s t b e s h a r e d a m o n g m u ltip le m e th o d s a n d m u s t c o n tin u e to e x is t in
m e m o r y w h e n th e m e th o d s a r e n o t e x e c u tin g .
C o n s t a n t F ie ld s
A c o n s ta n t fie ld is a fie ld th a t c a n n o t b e c h a n g e d b y a n y s ta te m e n t in th e c la s s . A n e r r o r
w ill o c c u r if th e c o m p ile r fin d s a s ta te m e n t th a t tr ie s to c h a n g e th e v a lu e o f a c o n s ta n t
f i e l d . A c o n s t a n t f i e l d i s d e c l a r e d w i t h t h e const k e y w o r d a n d i n i t i a l i z e d w i t h a v a l u e .
H e r e is a n e x a m p le :
private const decimal INTEREST_RATE = 0.075m;
T h i s s t a t e m e n t d e c l a r e s a c o n s t a n t decimal f i e l d n a m e d INTEREST_RATE, i n i t i a l i z e d
w ith th e v a lu e 0 .0 7 5 . C o n s ta n t fie ld s a r e ty p ic a lly u s e d to r e p r e s e n t u n c h a n g in g v a lu e s
3 .9
D e c la r in g V a r ia b le s a s F ie ld s
th a t a r e n e e d e d b y m a n y o f a c la s s ’s m e th o d s . F o r e x a m p le , s u p p o s e a b a n k in g p r o g r a m
u s e s a c o n s ta n t fie ld to r e p r e s e n t a n in te r e s t r a te . If th e in te r e s t r a te is u s e d in s e v e r a l
m e th o d s , it is e a s ie r to c r e a te a c o n s ta n t fie ld , r a th e r th a n a lo c a l n a m e d c o n s ta n t in
e a c h m e th o d . T h is a ls o s im p lifie s m a in te n a n c e o f th e c o d e . If th e in te r e s t r a te c h a n g e s ,
o n ly th e d e c la r a tio n o f th e c o n s ta n t fie ld h a s to b e c h a n g e d , in s te a d o f s e v e r a l lo c a l
d e c la r a tio n s .
N O T E : B e c a u s e a c o n s ta n t fie ld ’s v a lu e c a n n o t b e c h a n g e d b y o th e r s ta te m e n ts in
th e c la s s , y o u d o n o t h a v e to w o r r y a b o u t m a n y o f th e p o te n tia l d e b u g g in g p r o b le m s
th a t a r e a s s o c ia te d w ith th e o v e r u s e o f r e g u la r , n o n c o n s ta n t fie ld s .
In T u to r ia l 3 -5 , y o u w ill c r e a te a n a p p lic a tio n th a t u s e s a fie ld in a fo r m c la s s to h o ld
d a ta , a s w e ll a s c o n s ta n t fie ld s to r e p r e s e n t n o n c h a n g in g v a lu e s .
T u t o r ia l 3 -5 :
C r e a t i n g t h e Cha nge Counter A p p l i c a t i o n
VideoNot e
T u to r ia l 3 -5 :
C r e a tin g th e
Change
Counter
A p p lic a tio n
I n t h i s t u t o r i a l , y o u w i l l c r e a t e t h e Change Counter a p p l i c a t i o n . T h e a p p l i c a t i o n d i s p l a y s
im a g e s o f fo u r c o in s , h a v in g th e v a lu e s 5 c e n ts , 1 0 c e n ts , 2 5 c e n ts , a n d 5 0 c e n ts . E a c h tim e
th e u s e r c lic k s o n a c o in im a g e , th e v a lu e o f th a t c o in is a d d e d to a to ta l, a n d th e to ta l is
d is p la y e d . F ig u r e 3 -3 0 s h o w s th e a p p lic a tio n ’s fo r m , w ith th e n a m e s o f a ll th e c o n tr o ls .
F ig u r e 3 -3 0
T h e Cha nge Counter f o r m
instructionLabel
tenCentsPictureBox
fiveCentsPictureBox
outputDescriptionLabel
totalLabel
twentyFiveCentsPictureBox
fiftyCentsPictureBox
exitButton
S t e p 1 :
S ta r t V is u a l S tu d io a n d b e g in a n e w W in d o w s F o r m s A p p lic a tio n p r o je c t
n a m e d Sale Price Calculator.
S t e p 2 :
S e t u p th e a p p lic a tio n ’s fo r m a s s h o w n in F ig u r e 3 -3 0 . N o tic e th a t th e fo r m ’s
T e x t p r o p e r t y i s s e t t o Change Counter. T h e n a m e s o f t h e c o n t r o l s a r e s h o w n
in th e fig u r e . A s y o u p la c e e a c h o f th e c o n tr o ls o n th e fo r m , r e fe r to T a b le 3 -1 5
fo r th e r e le v a n t p r o p e r ty s e ttin g s .
169
170
C h a p te r 3
P r o c e s s in g D a t a
T a b le 3 -1 5
C o n t r o l p r o p e r t y s e t t in g s
Co n tro l Name
Co n tro l Typ e
P r o p e r ty S e ttin g s
instructionLabel
Lab el
F o n t: M ic r o s o ft S a n s S e r if (S ty le :
B o ld , S iz e : 1 0 p o in t)
T e x t : Click the Coins
fiveCentsPictureBox
P ic tu r e B o x
Im a g e : S e le c t a n d im p o r t th e
5 c e n t s . p n g f i l e f r o m t h e Chap02 f o l d e r
o f th e S tu d e n t S a m p le P r o g r a m s .
S iz e M o d e : A u to S iz e
tenCentsPictureBox
P ic tu r e B o x
Im a g e : S e le c t a n d im p o r t th e
1 0 c e n t s . p n g f i l e f r o m t h e Chap02
fo ld e r o f th e S tu d e n t S a m p le P r o g r a m s .
S iz e M o d e : A u to S iz e
twentyFiveCentsPictureBox
P ic tu r e B o x
Im a g e : S e le c t a n d im p o r t th e
2 5 c e n t s . p n g f i l e f r o m t h e Chap02
fo ld e r o f th e S tu d e n t S a m p le P r o g r a m s .
S iz e M o d e : A u to S iz e
fiftyCentsPictureBox
P ic tu r e B o x
Im a g e : S e le c t a n d im p o r t th e
5 0 c e n t s . p n g f i l e f r o m t h e Chap02
fo ld e r o f th e S tu d e n t S a m p le P r o g r a m s .
S iz e M o d e : A u to S iz e
outputDescriptionLabel
Lab el
F o n t: M ic r o s o ft S a n s S e r if (S ty le :
B o ld , S iz e : 1 0 p o in t)
T e x t : Total
totalLabel
Lab el
A u to S iz e : F a ls e
B o r d e r S ty le : F ix e d S in g le
Tex t: (Th e co n ten ts o f th e Tex t
p r o p e r ty h a v e b e e n e r a s e d .)
T e x tA lig n : M id d le C e n te r
exitButton
Bu tto n
T e x t : Exit
S t e p 3 :
O n c e y o u h a v e s e t u p th e fo r m w ith its c o n tr o ls , y o u c a n b e g in w r itin g c o d e .
A t th e e n d o f th is tu to r ia l, P r o g r a m 3 -6 s h o w s th e c o m p le te d c o d e fo r th e
fo r m . Y o u w ill b e in s tr u c te d to r e fe r to P r o g r a m 3 -6 a s y o u w r ite th e fo r m ’s
c o d e . (R e m e m b e r , th e lin e n u m b e r s th a t a r e s h o w n in P r o g r a m 3 -6 a r e n o t
p a r t o f th e p r o g r a m . T h e y a r e s h o w n fo r r e fe r e n c e o n ly .)
F ir s t, y o u w r ite th e d e c la r a tio n s fo r th e fie ld s . S w itc h y o u r v ie w to th e c o d e
e d i t o r ( r i g h t - c l i c k Form1. cs i n t h e Solution Explorer a n d s e l e c t View Code
fr o m th e p o p -u p m e n u ). W r ite th e d e c la r a tio n s s h o w n in lin e s 1 6 – 2 3 in
P r o g r a m 3 -6 . L e t’s ta k e a c lo s e r lo o k a t th e c o d e :
L i n e 1 6 : T h i s s t a t e m e n t d e c l a r e s a c o n s t a n t decimal f i e l d n a m e d FIVE_
w ith th e v a lu e 0 .0 5 . T h is c o n s ta n t r e p r e s e n ts th e
v a lu e o f th e 5 -c e n t c o in .
CENTS_VALUE, i n i t i a l i z e d
L i n e 1 7 : T h i s s t a t e m e n t d e c l a r e s a c o n s t a n t decimal f i e l d n a m e d TEN_
CENTS_VALUE, i n i t i a l i z e d w i t h t h e v a l u e 0 . 1 0 . T h i s c o n s t a n t r e p r e s e n t s t h e
v a lu e o f th e 1 0 -c e n t c o in .
3 .9
D e c la r in g V a r ia b le s a s F ie ld s
L i n e 1 8 : T h i s s t a t e m e n t d e c l a r e s a c o n s t a n t decimal f i e l d n a m e d TWENTY_
FIVE_CENTS_VALUE, i n i t i a l i z e d w i t h t h e v a l u e 0 . 2 5 . T h i s c o n s t a n t r e p r e s e n t s
th e v a lu e o f th e 2 5 -c e n t c o in .
L i n e 1 9 : T h i s s t a t e m e n t d e c l a r e s a c o n s t a n t decimal f i e l d n a m e d FIFTY_
CENTS_VALUE, i n i t i a l i z e d w i t h t h e v a l u e 0 . 5 0 . T h i s c o n s t a n t r e p r e s e n t s t h e
v a lu e o f th e 5 0 -c e n t c o in .
L i n e 2 3 : T h i s s t a t e m e n t d e c l a r e s a decimal f i e l d n a m e d total, i n i t i a l i z e d
w ith th e v a lu e 0 . T h is fie ld is u s e d to k e e p th e to ta l v a lu e o f th e c o in s th a t th e
u s e r c lic k s .
S t e p 4 :
N o w , y o u c a n c r e a te th e C lic k e v e n t h a n d le r s fo r th e P ic tu r e B o x c o n tr o ls . S w itc h
y o u r v i e w b a c k t o t h e Designer a n d d o u b l e - c l i c k t h e fiveCentsPictureBox
c o n tr o l. T h is o p e n s th e c o d e e d ito r , a n d y o u w ill s e e a n e m p ty e v e n t h a n d le r
n a m e d fiveCentsPictureBox_Click. C o m p l e t e t h e fiveCentsPictureBox_
Click e v e n t h a n d l e r b y t y p i n g t h e c o d e s h o w n i n l i n e s 3 2 – 3 6 i n P r o g r a m 3 - 6 .
L e t’s ta k e a c lo s e r lo o k a t th e c o d e :
L i n e 3 3 : T h i s s t a t e m e n t a d d s t h e v a l u e o f t h e FIVE_CENTS_VALUE c o n s t a n t t o
t h e total f i e l d .
L i n e 3 6 : T h i s s t a t e m e n t c o n v e r t s t h e total v a r i a b l e t o a s t r i n g a n d a s s i g n s
t h e r e s u l t t o t h e totalLabel c o n t r o l ’ s T e x t p r o p e r t y . T h e "c" f o r m a t s t r i n g
cau ses th e n u mb er to b e fo rmatted as cu rren cy.
S t e p 5 :
S w i t c h y o u r v i e w b a c k t o t h e Designer a n d d o u b l e - c l i c k t h e tenCentsPictureBox
c o n tr o l. T h is o p e n s th e c o d e e d ito r , a n d y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
tenCentsPictureBox_Click. C o m p l e t e t h e tenCentsPictureBox_Click e v e n t
h a n d le r b y ty p in g th e c o d e s h o w n in lin e s 4 1 – 4 5 in P r o g r a m 3 -6 . L e t’s ta k e a c lo s e r
lo o k a t th e c o d e :
L i n e 4 2 : T h i s s t a t e m e n t a d d s t h e v a l u e o f t h e TEN_CENTS_VALUE c o n s t a n t t o
t h e total f i e l d .
L i n e 4 5 : T h i s s t a t e m e n t c o n v e r t s t h e total v a r i a b l e t o a s t r i n g a n d a s s i g n s
t h e r e s u l t t o t h e totalLabel c o n t r o l ’ s T e x t p r o p e r t y . T h e "c" f o r m a t s t r i n g
cau ses th e n u mb er to b e fo rmatted as cu rren cy.
S t e p 6 :
S w itc h
y o u r
v ie w
b a c k
to
th e
D esi gner a n d
d o u b le -c lic k
th e
twentyFiveCentsPictureBox c o n t r o l . T h i s o p e n s t h e c o d e e d i t o r , a n d y o u
w i l l s e e a n e m p t y e v e n t h a n d l e r n a m e d twentyFiveCentsPictureBox_Click.
C o m p l e t e t h e twentyFiveCentsPictureBox_Click e v e n t h a n d l e r b y t y p i n g
th e c o d e s h o w n in lin e s 5 0 – 5 4 in P r o g r a m 3 -6 . L e t’s ta k e a c lo s e r lo o k a t
th e c o d e :
L i n e 5 1 : T h i s s t a t e m e n t a d d s t h e v a l u e o f t h e TWENTY_FIVE_CENTS_VALUE
c o n s t a n t t o t h e total f i e l d .
L i n e 5 4 : T h i s s t a t e m e n t c o n v e r t s t h e total v a r i a b l e t o a s t r i n g a n d a s s i g n s
t h e r e s u l t t o t h e totalLabel c o n t r o l ’ s T e x t p r o p e r t y . T h e "c" f o r m a t s t r i n g
cau ses th e n u mb er to b e fo rmatted as cu rren cy.
S t e p 7 :
S w itc h
y o u r
v ie w
b a c k t o t h e D esi gner a n d d o u b l e - c l i c k t h e
fiftyCentsPictureBox c o n t r o l . T h i s o p e n s t h e c o d e e d i t o r , a n d y o u w i l l s e e
a n e m p t y e v e n t h a n d l e r n a m e d fiftyCentsPictureBox_Click. C o m p l e t e t h e
fiftyCentsPictureBox_Click e v e n t h a n d l e r b y t y p i n g t h e c o d e s h o w n i n
lin e s 5 9 – 6 3 in P r o g r a m 3 -6 . L e t’s ta k e a c lo s e r lo o k a t th e c o d e :
L i n e 6 0 : T h i s s t a t e m e n t a d d s t h e v a l u e o f t h e FIFTY_CENTS_VALUE c o n s t a n t
t o t h e total f i e l d .
171
172
C h a p te r 3
P r o c e s s in g D a t a
L i n e 6 3 : T h i s s t a t e m e n t c o n v e r t s t h e total v a r i a b l e t o a s t r i n g a n d a s s i g n s
t h e r e s u l t t o t h e totalLabel c o n t r o l ’ s T e x t p r o p e r t y . T h e "c" f o r m a t s t r i n g
cau ses th e n u mb er to b e fo rmatted as cu rren cy.
S t e p 8 :
N o w y o u w r i t e t h e e v e n t h a n d l e r f o r t h e Exit b u t t o n . S w i t c h y o u r v i e w b a c k
t o t h e D esigner a n d d o u b l e - c l i c k t h e exitButton c o n t r o l . T h i s o p e n s t h e
c o d e e d i t o r , a n d y o u w i l l s e e a n e m p t y e v e n t h a n d l e r n a m e d exitButton_
Click. C o m p l e t e t h e exitButton_Click e v e n t h a n d l e r b y t y p i n g t h e c o d e
s h o w n in lin e s 6 8 – 6 9 in P r o g r a m 3 -6 .
S t e p 9 :
S a v e th e p r o je c t. T h e n , p r e s s th e
k e y o n t h e k e y b o a r d o r c l i c k t h e Start
D ebugging b u t t o n ( ) o n t h e t o o l b a r t o c o m p i l e a n d r u n t h e a p p l i c a t i o n . T e s t
th e a p p lic a tio n b y c lic k in g th e c o in im a g e s in a n y o r d e r y o u w is h . T h e to ta l
s h o w n o n th e fo r m s h o u ld u p d a te b y th e c o r r e c t a m o u n t e a c h tim e y o u c lic k a
c o i n . W h e n y o u a r e f i n i s h e d , c l i c k t h e Exit b u t t o n a n d t h e f o r m s h o u l d c l o s e .
P r o g r a m 3 -6
C o m p l e t e d F o r m 1 c o d e f o r t h e Cha nge Counter a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Change_Counter
12 {
13
public partial class Form1 : Form
14
{
15
// Constant fields
16
const decimal FIVE_CENTS_VALUE = 0.05m;
17
const decimal TEN_CENTS_VALUE = 0.10m;
18
const decimal TWENTY_FIVE_CENTS_VALUE = 0.25m;
19
const decimal FIFTY_CENTS_VALUE = 0.50m;
20
21
// Field variable to hold the total,
22
// initialized with 0.
23
private decimal total = 0m;
24
25
public Form1()
26
{
27
InitializeComponent();
28
}
29
30
private void fiveCentsPictureBox_Click(object sender, EventArgs e)
31
{
32
// Add the value of 5 cents to the total.
33
total += FIVE_CENTS_VALUE;
34
35
// Display the total, formatted as currency.
36
totalLabel.Text = total.ToString("c");
37
}
38
39
private void tenCentsPictureBox_Click(object sender, EventArgs e)
40
{
41
// Add the value of 10 cents to the total.
3 .1 0
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72 }
U s i n g t h e Math C l a s s
total += TEN_CENTS_VALUE;
// Display the total, formatted as currency.
totalLabel.Text = total.ToString("c");
}
private void twentyFiveCentsPictureBox_Click(object sender, EventArgs e)
{
// Add the value of 25 cents to the total.
total += TWENTY_FIVE_CENTS_VALUE;
// Display the total, formatted as currency.
totalLabel.Text = total.ToString("c");
}
private void fiftyCentsPictureBox_Click(object sender, EventArgs e)
{
// Add the value of 50 cents to the total.
total += FIFTY_CENTS_VALUE;
// Display the total, formatted as currency.
totalLabel.Text = total.ToString("c");
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
C h e c k p o in t
3 .1 0
3 .4 1
W h a t a r e tw o a d v a n ta g e s o f u s in g n a m e d c o n s ta n ts ?
3 .4 2
W r ite a p r o g r a m m in g s ta te m e n t th a t d e c la r e s a n a m e d c o n s ta n t fo r a 1 0 p e r c e n t
d is c o u n t.
3 .4 3
W h e r e s h o u ld y o u p la c e fie ld d e c la r a tio n s in a p r o g r a m ?
3 .4 4
W h a t a c c e s s m o d ifie r s h o u ld y o u u s e w h e n d e c la r in g a fie ld ? W h y ?
3 .4 5
H o w is th e life tim e o f a fie ld d iffe r e n t fr o m th e life tim e o f a lo c a l v a r ia b le ?
3 .4 6
W r ite a p r o g r a m m in g s ta te m e n t th a t d e c la r e s a c o n s ta n t fie ld fo r a 5 .9 p e r c e n t
in te r e s t r a te .
U s i n g t h e Math C l a s s
C O N C E P T :
T h e . N E T F r a m e w o r k ’ s Math c l a s s p r o v i d e s s e v e r a l m e t h o d s f o r
p e r fo r m in g c o m p le x m a th e m a tic a l c a lc u la tio n s .
T h e . N E T F r a m e w o r k p r o v i d e s a c l a s s n a m e d Math, w h i c h c o n t a i n s n u m e r o u s m e t h o d s
th a t a r e u s e fu l fo r p e r fo r m in g a d v a n c e d m a th e m a tic a l o p e r a tio n s . T a b le 3 -1 6 g iv e s a
s u m m a r y o f s e v e r a l o f t h e Math c l a s s m e t h o d s . ( F o r a c o m p r e h e n s i v e l i s t o f a l l t h e
173
174
C h a p te r 3
P r o c e s s in g D a t a
T a b le 3 -1 6
M a n y o f t h e Math c l a s s m e t h o d s
M a th C la s s M e th o d
D e s c r ip tio n
Math.Abs(x )
R e t u r n s t h e a b s o l u t e v a l u e o f x.
Math.Acos(x )
R e t u r n s t h e a r c c o s i n e o f x, in radians. T h e a r g u m e n t x i s
a double, a n d t h e v a l u e t h a t i s r e t u r n e d i s a double.
Math.Asin(x )
R e t u r n s t h e a r c s i n e o f x, in radians. T h e a r g u m e n t x i s a
double, a n d t h e v a l u e t h a t i s r e t u r n e d i s a double.
Math.Atan(x )
R e t u r n s t h e a r c t a n g e n t o f x, in radians. T h e a r g u m e n t x i s
a double, a n d t h e v a l u e t h a t i s r e t u r n e d i s a double.
Math.Ceiling(x )
R e tu r n s th e le a s t in te g e r th a t is g r e a te r th a n o r e q u a l to x
( a decimal o r a double) .
Math.Cos(x )
R e tu r n s th e c o s in e o f xin r a d ia n s . T h e a r g u m e n t xis a
double, a n d t h e v a l u e t h a t i s r e t u r n e d i s a double.
Math.Exp(x )
R e t u r n s ex . T h e a r g u m e n t x i s a double, a n d t h e v a l u e
t h a t i s r e t u r n e d i s a double.
Math.Floor(x )
R e tu r n s th e g r e a te s t in te g e r th a t is le s s th a n o r e q u a l to x
( a decimal o r a double) .
Math.Log(x )
R e t u r n s t h e n a t u r a l l o g a r i t h m o f x. T h e a r g u m e n t x i s a
double, a n d t h e v a l u e t h a t i s r e t u r n e d i s a double.
Math.Log10(x )
R e t u r n s t h e b a s e - 1 0 l o g a r i t h m o f x. T h e a r g u m e n t x i s a
double, a n d t h e v a l u e t h a t i s r e t u r n e d i s a double.
Math.Max(x , y)
R e t u r n s t h e g r e a t e r o f t h e t w o v a l u e s x a n d y.
Math.Min(x , y)
R e t u r n s t h e l e s s e r o f t h e t w o v a l u e s x a n d y.
Math.Pow(x , y)
R e t u r n s t h e v a l u e o f x ( a double) r a i s e d t o t h e p o w e r o f y
( a l s o a double) . T h e v a l u e t h a t i s r e t u r n e d i s a double.
Math.Round(x )
R e t u r n s t h e v a l u e o f x ( a double o r a decimal) r o u n d e d
to th e n e a r e s t in te g e r .
Math.Sin(x )
R e tu r n s th e s in e o f xin r a d ia n s .
Math.Sqrt(x )
R e t u r n s t h e s q u a r e r o o t o f x ( a double) . T h e v a l u e t h a t i s
r e t u r n e d i s a double.
Math.Tan(x )
R e tu r n s th e ta n g e n t o f xin r a d ia n s . T h e a r g u m e n t xis a
double, a n d t h e v a l u e t h a t i s r e t u r n e d i s a double.
Math.Truncate(x )
R e t u r n s t h e i n t e g e r p a r t o f x ( a double o r a decimal) .
m e t h o d s p r o v i d e d b y t h e Math c l a s s a n d m o r e d e t a i l s o n a n y o f t h e m e t h o d s , j u s t s e a r c h
f o r M ath class i n t h e M S D N h e l p s y s t e m . )
T h e s e m e th o d s ty p ic a lly a c c e p t o n e o r m o r e v a lu e s a s a r g u m e n ts , p e r fo r m a m a th e m a tic a l
o p e r a t i o n u s i n g t h e a r g u m e n t s , a n d r e t u r n t h e r e s u l t . F o r e x a m p l e , t h e Math.Pow m e t h o d
r a is e s a n u m b e r to a p o w e r . H e r e is a n e x a m p le o f h o w th e m e th o d is c a lle d :
double result;
result = Math.Sqrt(4.0, 2.0);
T h e m e t h o d t a k e s t w o double a r g u m e n t s . I t r a i s e s t h e f i r s t a r g u m e n t t o t h e p o w e r o f t h e
s e c o n d a r g u m e n t a n d r e t u r n s t h e r e s u l t a s a double. I n t h i s e x a m p l e , 4 . 0 i s r a i s e d t o t h e
p o w e r o f 2 .0 . T h is s ta te m e n t is e q u iv a le n t to th e fo llo w in g a lg e b r a ic s ta te m e n t:
result =
42
3 .1 1
M o r e G U I D e t a ils
T h e f o l l o w i n g c o d e s a m p l e s h o w s a n o t h e r e x a m p l e o f a s t a t e m e n t u s i n g t h e Math.Pow
m e t h o d . I t a s s i g n s 3 t i m e s 6 3 t o x:
double x;
x = 3 * Math.pow(6.0, 3.0);
T h e Math.Sqrt m e t h o d a c c e p t s a n a r g u m e n t a n d r e t u r n s t h e s q u a r e r o o t o f t h e a r g u m e n t. H e r e is a n e x a m p le o f h o w it is u s e d :
double result;
result = Math.Sqrt(16.0);
T h e s t a t e m e n t t h a t c a l l s t h e Math.Sqrt m e t h o d p a s s e s 1 6 . 0 a s a n a r g u m e n t . T h e m e t h o d
r e t u r n s t h e s q u a r e r o o t o f 1 6 . 0 ( a s a double ) , w h i c h i s t h e n a s s i g n e d t o t h e
result v a r i a b l e .
T h e Math.PI a n d Math.E N a m e d C o n s t a n t s
T h e Math c l a s s a l s o p r o v i d e s t w o p r e d e f i n e d n a m e d c o n s t a n t s , Math.PI a n d Math.E,
w h i c h a r e a s s i g n e d m a t h e m a t i c a l v a l u e s f o r pi a n d e. Y o u c a n u s e t h e s e v a r i a b l e s i n e q u a tio n s th a t r e q u ir e th e ir v a lu e s . F o r e x a m p le , th e fo llo w in g s ta te m e n t, w h ic h c a lc u la te s th e
a r e a o f a c i r c l e , u s e s Math.PI.
area = Math.PI * radius * radius;
N O T E : If y o u lo o k a t th e to p o f a fo r m ’s s o u r c e c o d e in th e c o d e e d ito r , y o u s h o u ld
s e e a d i r e c t i v e t h a t r e a d s using System;. T h a t d i r e c t i v e i s r e q u i r e d f o r a n y p r o g r a m
t h a t u s e s t h e Math c l a s s .
C h e c k p o in t
3 .1 1
3 .4 7
W r i t e a p r o g r a m m i n g s t a t e m e n t t h a t u s e s t h e Math.Pow m e t h o d t o s q u a r e t h e
n u m b e r 1 2 a n d s t o r e t h e r e s u l t i n a double v a r i a b l e n a m e d product.
3 .4 8
W h a t m e th o d
tw o v a lu e s ?
o f t h e Math c l a s s c a n
b e u s e d
3 .4 9
W h a t m e th o d
tw o v a lu e s ?
o f t h e Math c l a s s c a n
b e u s e d
to
to
d e te r m in e th e la r g e r o f
d e te r m in e th e s m a lle r o f
M o r e G U I D e t a ils
In C h a p te r 2 , y o u le a r n e d th e b a s ic s o f c r e a tin g a G U I b y p la c in g c o n tr o ls o n a fo r m a n d
s e ttin g v a r io u s p r o p e r tie s . In th is s e c tio n , y o u le a r n to fin e -tu n e m a n y a s p e c ts o f a n a p p lic a tio n ’s G U I.
C o n t r o llin g a F o r m ’s T a b O r d e r
W h e n a n a p p lic a tio n is r u n n in g a n d a fo r m is d is p la y e d , o n e o f th e fo r m ’s c o n tr o ls a lw a y s
h a s th e fo c u s . T h e c o n tr o l h a v in g th e fo c u s is th e o n e th a t r e c e iv e s th e u s e r ’s k e y b o a r d
in p u t. F o r e x a m p le , w h e n a T e x tB o x c o n tr o l h a s th e fo c u s , it r e c e iv e s th e c h a r a c te r s th a t
th e u s e r e n te r s o n th e k e y b o a r d . W h e n a b u tto n h a s th e fo c u s , p r e s s in g th e E n te r k e y
e x e c u te s th e b u tto n ’s C lic k e v e n t h a n d le r .
175
176
C h a p te r 3
P r o c e s s in g D a t a
N O T E : O n ly c o n tr o ls c a p a b le o f r e c e iv in g s o m e s o r t o f in p u t, s u c h a s te x t b o x e s
an d b u tto n s, may h ave th e fo cu s.
Y o u c a n te ll w h ic h c o n tr o l h a s th e fo c u s b y lo o k in g a t th e fo r m a t r u n tim e . W h e n a
T e x tB o x c o n tr o l h a s th e fo c u s , a b lin k in g te x t c u r s o r a p p e a r s in s id e it, o r th e te x t in s id e
th e T e x tB o x c o n tr o l m ig h t a p p e a r h ig h lig h te d . W h e n a b u tto n h a s th e fo c u s , a th in d o tte d
lin e u s u a lly a p p e a r s a r o u n d th e c o n tr o l.
W h e n a n a p p lic a tio n is r u n n in g , p r e s s in g th e T a b k e y c h a n g e s th e fo c u s fr o m o n e c o n tr o l
to a n o th e r . T h e o r d e r in w h ic h c o n tr o ls r e c e iv e th e fo c u s is c a lle d th e ta b o r d e r . W h e n
y o u p la c e c o n tr o ls o n a fo r m in V is u a l C # , th e ta b o r d e r is in th e s a m e s e q u e n c e in w h ic h
y o u c r e a te d th e c o n tr o ls . In m a n y c a s e s th is is th e ta b o r d e r y o u w a n t, b u t s o m e tim e s y o u
r e a r r a n g e c o n tr o ls o n a fo r m , d e le te c o n tr o ls , a n d a d d n e w o n e s . T h e s e m o d ific a tio n s
o fte n le a d to a d is o r g a n iz e d ta b o r d e r , w h ic h c a n c o n fu s e a n d ir r ita te th e u s e r s o f
y o u r a p p lic a tio n .
U s e r s w a n t to ta b s m o o th ly fr o m o n e c o n tr o l to th e n e x t, in a lo g ic a l s e q u e n c e . Y o u c a n
m o d ify th e ta b o r d e r b y c h a n g in g a c o n tr o l’s T a b In d e x p r o p e r ty . T h e T a b In d e x p r o p e r ty
c o n ta in s a n u m e r ic v a lu e , w h ic h in d ic a te s th e c o n tr o l’s p o s itio n in th e ta b o r d e r . W h e n
y o u c r e a te a c o n tr o l, V is u a l C # a u to m a tic a lly a s s ig n s a v a lu e to its T a b In d e x p r o p e r ty .
T h e fir s t c o n tr o l y o u c r e a te o n a fo r m h a s a T a b In d e x o f 0 , th e s e c o n d h a s a T a b In d e x o f
1 , a n d s o fo r th . T h e c o n tr o l w ith a T a b In d e x o f 0 is th e fir s t c o n tr o l in th e ta b o r d e r . T h e
n e x t c o n tr o l in th e ta b o r d e r is th e o n e w ith a T a b In d e x o f 1 . T h e ta b o r d e r c o n tin u e s in
th is s e q u e n c e .
Y o u m a y c h a n g e th e ta b o r d e r o f a fo r m ’s c o n tr o ls b y s e le c tin g th e m , o n e b y o n e , a n d
c h a n g i n g t h e i r T a b I n d e x p r o p e r t y i n t h e Properties w i n d o w . A n e a s i e r m e t h o d , h o w e v e r ,
i s t o c l i c k View o n t h e V i s u a l S t u d i o m e n u b a r a n d t h e n c l i c k Tab O rder. T h i s c a u s e s t h e
fo r m to b e d is p la y e d in ta b o r d e r s e le c tio n m o d e . T h e im a g e o n th e le ft in F ig u r e 3 -3 1
s h o w s a fo r m in th e n o r m a l v ie w , a n d th e im a g e o n th e r ig h t s h o w s th e fo r m in ta b o r d e r
s e le c tio n m o d e . W e h a v e a ls o in s e r te d th e n a m e s o f th e T e x tB o x a n d B u tto n c o n tr o ls in
th e im a g e o n th e r ig h t fo r r e fe r e n c e p u r p o s e s .
F ig u r e 3 -3 1
A fo r m d is p la y e d in t a b o r d e r s e le c t io n m o d e
Normal view
Tab order selection mode
nameTextBox
addressTextBox
cityTextBox
stateTextBox
zipTextBox
clearButton
In ta b o r d e r s e le c tio n m o d e , e a c h c o n tr o l’s e x is tin g T a b In d e x v a lu e is d is p la y e d in a s m a ll
b o x in th e c o n tr o l’s u p p e r -le ft c o r n e r . N o tic e th e fo llo w in g in th e im a g e o n th e r ig h t in
F ig u r e 3 -3 1 :
3 .1 1
M o r e G U I D e t a ils
• T h e nameTextBox c o n t r o l ’ s T a b I n d e x i s 2 .
• T h e addressTextBox c o n t r o l ’ s T a b I n d e x i s 3 .
• T h e cityTextBox c o n t r o l ’ s T a b I n d e x i s 0 .
• T h e stateTextBox c o n t r o l ’ s T a b I n d e x i s 4 .
• T h e zipTextBox c o n t r o l ’ s T a b I n d e x i s 1 .
• T h e clearButton c o n t r o l ’ s T a b I n d e x i s 8 .
N O T E : A lth o u g h th e L a b e l c o n tr o ls h a v e T a b In d e x v a lu e s , th o s e v a lu e s a r e ir r e le v a n t in th is e x a m p le b e c a u s e L a b e l c o n tr o ls c a n n o t r e c e iv e th e fo c u s .
A s y o u lo o k a t F ig u r e 3 -3 1 , th in k a b o u t th e o r d e r in w h ic h th e c o n tr o ls w ill r e c e iv e th e
fo c u s w h e n th e a p p lic a tio n r u n s .
• T h e cityTextBox c o n t r o l h a s t h e l o w e s t T a b I n d e x v a l u e ( 0 ) , s o i t w i l l r e c e i v e t h e
fo c u s fir s t.
• I f y o u p r e s s t h e T a b k e y , t h e f o c u s w i l l j u m p t o t h e zipTextBox c o n t r o l b e c a u s e i t
h a s th e n e x t lo w e s t T a b In d e x v a lu e (1 ).
• P r e s s t h e T a b k e y a g a i n a n d t h e f o c u s w i l l j u m p t o t h e nameTextBox c o n t r o l
(T a b In d e x is s e t to 2 ).
• P r e s s t h e T a b k e y a g a i n a n d t h e f o c u s w i l l j u m p t o t h e addressTextBox c o n t r o l
(T a b In d e x is s e t to 3 ).
• P r e s s t h e T a b k e y a g a i n a n d t h e f o c u s w i l l j u m p t o t h e stateTextBox c o n t r o l
(T a b In d e x is s e t to 4 ).
• P r e s s t h e T a b k e y a g a i n a n d t h e f o c u s w i l l j u m p t o t h e clearButton c o n t r o l
(T a b In d e x is s e t to 8 ).
T h is is a v e r y c o n fu s in g ta b o r d e r a n d s h o u ld b e r e a r r a n g e d . W h e n a fo r m is d is p la y e d
in ta b o r d e r s e le c tio n m o d e , y o u e s ta b lis h a n e w ta b o r d e r b y s im p ly c lic k in g th e c o n tr o ls w ith th e m o u s e in th e o r d e r y o u w a n t. T o fix th e d is o r g a n iz e d ta b o r d e r s h o w n in
F ig u r e 3 -3 1 , w e p e r fo r m th e fo llo w in g :
• F i r s t , c l i c k t h e nameTextBox c o n t r o l . T h e c o n t r o l ’ s T a b I n d e x v a l u e c h a n g e s t o 0 .
• N e x t , c l i c k t h e addressTextBox c o n t r o l . T h e c o n t r o l ’ s T a b I n d e x v a l u e c h a n g e s t o 1 .
• T h e n , c l i c k t h e cityTextBox c o n t r o l . T h e c o n t r o l ’ s T a b I n d e x v a l u e c h a n g e s t o 2 .
• N e x t , c l i c k t h e stateTextBox c o n t r o l . T h e c o n t r o l ’ s T a b I n d e x v a l u e c h a n g e s t o 3 .
• T h e n , c l i c k t h e zipTextBox c o n t r o l . T h e c o n t r o l ’ s T a b I n d e x v a l u e c h a n g e s t o 4 .
• F i n a l l y , c l i c k t h e clearButton c o n t r o l . T h e c o n t r o l ’ s T a b I n d e x v a l u e c h a n g e s t o 5 .
W h e n y o u a r e fin is h e d , e x it ta b o r d e r s e le c tio n m o d e b y p r e s s in g th e E s c k e y . N o w w h e n
th e a p p lic a tio n r u n s , th e fo c u s w ill s h ift s m o o th ly in a n o r d e r th a t m a k e s s e n s e to th e u s e r .
C h a n g i n g t h e F o c u s w i t h t h e Focus M e t h o d
O fte n , y o u w a n t to m a k e s u r e a p a r tic u la r c o n tr o l h a s th e fo c u s . F o r e x a m p le , lo o k a t th e
f o r m s h o w n i n F i g u r e 3 - 3 1 . T h e p u r p o s e o f t h e Clear b u t t o n i s t o c l e a r a n y i n p u t t h a t
th e u s e r h a s e n te r e d a n d r e s e t th e fo r m s o it is r e a d y to a c c e p t a n e w s e t o f in p u t. W h e n
t h e Clear b u t t o n i s c l i c k e d , t h e T e x t B o x c o n t r o l s s h o u l d b e c l e a r e d a n d t h e f o c u s s h o u l d
r e t u r n t o t h e nameTextBox c o n t r o l . T h i s w o u l d m a k e i t u n n e c e s s a r y f o r t h e u s e r t o c l i c k
th e T e x tB o x c o n tr o l in o r d e r to s ta r t e n te r in g a n o th e r s e t o f in fo r m a tio n .
I n c o d e , y o u m o v e t h e f o c u s t o a c o n t r o l b y c a l l i n g t h e Focus m e t h o d . T h e m e t h o d ’ s
g e n e r a l s y n ta x is :
ControlName.Focus();
177
178
C h a p te r 3
P r o c e s s in g D a t a
w h e r e ControlName i s t h e n a m e o f t h e c o n t r o l . F o r i n s t a n c e , y o u m o v e t h e f o c u s t o t h e
nameTextBox c o n t r o l w i t h t h i s s t a t e m e n t :
nameTextBox.Focus();
A f t e r t h e s t a t e m e n t e x e c u t e s , t h e nameTextBox c o n t r o l w i l l h a v e t h e f o c u s . H e r e i s a n
e x a m p l e o f h o w t h e clearButton c o n t r o l ’ s C l i c k e v e n t h a n d l e r c o u l d b e w r i t t e n :
1 private void clearButton_Click(object sender, EventArgs e)
2 {
3
// Clear the TextBox controls.
4
nameTextBox.Text = "";
5
addressTextBox.Text = "";
6
cityTextBox.Text = "";
7
stateTextBox.Text = "";
8
zipTextBox.Text = "";
9
10
// Set the focus to nameTextBox.
11
nameTextBox.Focus();
12 }
T h e s ta te m e n ts in lin e s 4 – 8 c le a r th e c o n te n ts o f th e T e x tB o x c o n tr o ls . T h e n , th e s ta te m e n t i n l i n e 1 1 s e t s t h e f o c u s t o t h e nameTextBox c o n t r o l .
A s s ig n in g K e y b o a r d A c c e s s K e y s t o B u t t o n s
A n a c c e s s k e y , a ls o k n o w n a s a m n e m o n ic , is a k e y th a t is p r e s s e d in c o m b in a tio n w ith th e
A lt k e y to a c c e s s q u ic k ly a c o n tr o l s u c h a s a b u tto n . W h e n y o u a s s ig n a n a c c e s s k e y to a
b u tto n , th e u s e r c a n tr ig g e r a C lic k e v e n t e ith e r b y c lic k in g th e b u tto n w ith th e m o u s e o r
b y u s in g th e a c c e s s k e y . U s e r s w h o a r e q u ic k w ith th e k e y b o a r d p r e fe r to u s e a c c e s s k e y s
in s te a d o f th e m o u s e .
Y o u a s s ig n a n a c c e s s k e y to a b u tto n th r o u g h its T e x t p r o p e r ty . F o r e x a m p le , a s s u m e a n
a p p l i c a t i o n h a s a b u t t o n w h o s e T e x t p r o p e r t y i s s e t t o Exit. Y o u w i s h t o a s s i g n t h e
accessk ey
+
to th e b u tto n s o th e u s e r m a y tr ig g e r th e b u tto n ’s C lic k e v e n t b y
p r e s s in g
+
o n th e k e y b o a r d . T o m a k e th e a s s ig n m e n t, p la c e a n a m p e r s a n d (& )
b e f o r e t h e l e t t e r x i n t h e b u t t o n ’ s T e x t p r o p e r t y : E&xit. F i g u r e 3 - 3 2 s h o w s h o w t h e T e x t
p r o p e r t y a p p e a r s i n t h e Properties w i n d o w .
F ig u r e 3 -3 2
T e x t p r o p e r t y E&xit
3 .1 1
M o r e G U I D e t a ils
A lth o u g h th e a m p e r s a n d is p a r t o f th e B u tto n c o n tr o l’s T e x t p r o p e r ty , it is n o t d is p la y e d
o n t h e b u t t o n . W i t h t h e a m p e r s a n d i n f r o n t o f t h e l e t t e r x, t h e l e t t e r w i l l a p p e a r u n d e r lin e d a s s h o w n in F ig u r e 3 -3 3 . T h is in d ic a te s th a t th e b u tto n m a y b e c lic k e d b y p r e s s in g
+
o n th e k e y b o a r d . (Y o u w ill s e e th e u n d e r lin in g a t d e s ig n tim e . A t r u n tim e ,
h o w e v e r , th e u n d e r lin in g m a y n o t a p p e a r u n til th e u s e r p r e s s e s th e A lt k e y .)
F ig u r e 3 -3 3
B u t t o n c o n t r o l w i t h E&xit T e x t p r o p e r t y
N O T E : A c c e s s k e y s d o n o t d is tin g u is h b e tw e e n u p p e r c a s e a n d lo w e r c a s e c h a r a c te r s .
T h e r e is n o d iffe r e n c e b e tw e e n
+
an d
+
.
S u p p o s e w e s t o r e t h e v a l u e &Exit i n t h e b u t t o n ’ s T e x t p r o p e r t y . T h e a m p e r s a n d i s i n
f r o n t o f t h e l e t t e r E, s o
+
b e c o m e s th e a c c e s s k e y . T h e b u tto n w ill a p p e a r a s s h o w n
in F ig u r e 3 -3 4 .
F ig u r e 3 -3 4
B u t t o n c o n t r o l w i t h &Exit T e x t p r o p e r t y
A s s ig n in g t h e S a m e A c c e s s K e y t o M u lt ip le B u t t o n s
B e c a r e fu l n o t to a s s ig n th e s a m e a c c e s s k e y to tw o o r m o r e b u tto n s o n th e s a m e fo r m . If
tw o o r m o r e b u tto n s s h a r e th e s a m e a c c e s s k e y , a C lic k e v e n t is tr ig g e r e d fo r th e fir s t b u tto n created wh en th e u ser p resses th e access k ey.
D is p la y in g t h e & C h a r a c t e r o n a B u t t o n
I f y o u w a n t t o d i s p l a y a n a m p e r s a n d c h a r a c t e r o n a b u t t o n , u s e t w o a m p e r s a n d s ( &&) i n
th e T e x t p r o p e r ty . U s in g tw o a m p e r s a n d s c a u s e s a s in g le a m p e r s a n d to d is p la y a n d d o e s
n o t d e f i n e a n a c c e s s k e y . F o r e x a m p l e , i f a b u t t o n ’ s T e x t p r o p e r t y i s s e t t o Save && Exit,
th e b u tto n w ill a p p e a r a s s h o w n in F ig u r e 3 -3 5 .
F ig u r e 3 -3 5
B u t t o n c o n t r o l w i t h Save && Exit T e x t p r o p e r t y
A c c e p t B u t t o n s a n d C a n c e l B u t t o n s
A n a c c e p t b u tto n is a b u tto n o n a fo r m th a t is a u to m a tic a lly c lic k e d w h e n th e u s e r p r e s s e s
th e E n te r k e y . A c a n c e l b u tto n is a b u tto n o n a fo r m th a t is a u to m a tic a lly c lic k e d w h e n
th e u s e r p r e s s e s th e E s c k e y . F o r m s h a v e tw o p r o p e r tie s , A c c e p tB u tto n a n d C a n c e lB u tto n ,
w h ic h a llo w y o u to d e s ig n a te a n a c c e p t b u tto n a n d a c a n c e l b u tto n . W h e n y o u s e le c t th e s e
) a p p e a r s , w h ic h d is p la y s
p r o p e r t i e s i n t h e Properties w i n d o w , a d o w n - a r r o w b u t t o n (
a d r o p -d o w n lis t w h e n c lic k e d . T h e lis t c o n ta in s th e n a m e s o f a ll th e b u tto n s o n th e fo r m .
Y o u s e le c t th e b u tto n th a t y o u w a n t to d e s ig n a te a s th e a c c e p t b u tto n o r c a n c e l b u tto n .
A n y b u tto n th a t is fr e q u e n tly c lic k e d s h o u ld p r o b a b ly b e s e le c te d a s th e a c c e p t b u tto n .
T h i s w i l l a l l o w k e y b o a r d u s e r s t o a c c e s s t h e b u t t o n q u i c k l y a n d e a s i l y . Exit o r Cancel b u t to n s a r e lik e ly c a n d id a te s to b e c o m e c a n c e l b u tto n s .
179
180
C h a p te r 3
P r o c e s s in g D a t a
T h e B a c k C o lo r P r o p e r t y
F o r m s a n d m o s t c o n tr o ls h a v e a B a c k C o lo r p r o p e r ty th a t a llo w s y o u to c h a n g e th e
o b j e c t ’ s b a c k g r o u n d c o l o r . W h e n y o u s e l e c t a n o b j e c t ’ s B a c k C o l o r p r o p e r t y i n t h e Properties w i n d o w , a d o w n - a r r o w b u t t o n (
) a p p e a r s , w h ic h d is p la y s a d r o p -d o w n lis t o f
a v a ila b le c o lo r s w h e n c lic k e d , a s s h o w n in F ig u r e 3 -3 6 .
F ig u r e 3 -3 6
D r o p - d o w n lis t o f c o lo r s
T h e d r o p - d o w n l i s t h a s t h r e e t a b s : Custom, Web, a n d System. T h e System t a b l i s t s c o l o r s
d e f i n e d i n t h e c u r r e n t W i n d o w s c o n f i g u r a t i o n . T h e Web t a b l i s t s c o l o r s d i s p l a y e d w i t h
c o n s i s t e n c y i n W e b b r o w s e r s . T h e Custom t a b d i s p l a y s a c o l o r p a l e t t e . S e l e c t a c o l o r f r o m
o n e o f th e ta b s a n d th e o b je c t’s b a c k g r o u n d c o lo r w ill b e s e t to th a t c o lo r .
T h e F o r e C o lo r P r o p e r t y
C o n tr o ls th a t d is p la y te x t h a v e a F o r e C o lo r p r o p e r ty th a t a llo w s y o u to c h a n g e th e c o lo r
o f t h e t e x t . W h e n y o u s e l e c t a c o n t r o l ’ s F o r e C o l o r p r o p e r t y i n t h e Properties w i n d o w , a
d o wn -arro w b u tto n (
) a p p e a r s , w h ic h d is p la y s th e d r o p -d o w n lis t o f a v a ila b le c o lo r s
s h o w n in F ig u r e 3 -3 6 w h e n c lic k e d . S e le c t a c o lo r fr o m o n e o f th e ta b s a n d th e te x t th a t is
d is p la y e d b y th e c o n tr o l w ill b e s e t to th a t c o lo r .
S e t t in g C o lo r s in C o d e
I n a d d i t i o n t o u s i n g t h e Properties w i n d o w , y o u c a n a l s o s e t t h e v a l u e s o f t h e B a c k C o l o r
a n d F o r e C o lo r p r o p e r tie s w ith c o d e . T h e .N E T F r a m e w o r k p r o v id e s n u m e r o u s v a lu e s
th a t r e p r e s e n t c o lo r s a n d c a n b e a s s ig n e d to th e F o r e C o lo r a n d B a c k C o lo r p r o p e r tie s in
c o d e . T h e fo llo w in g a r e a fe w o f th e v a lu e s :
Color.Black
Color.Blue
Color.Cyan
Color.Green
Color.Magenta
Color.Red
Color.White
Color.Yellow
F o r e x a m p l e , a s s u m e a n a p p l i c a t i o n h a s a L a b e l c o n t r o l n a m e d messageLabel. T h e f o l lo w in g c o d e s e ts th e la b e l’s b a c k g r o u n d c o lo r to b la c k a n d fo r e g r o u n d c o lo r to y e llo w :
messageLabel.BackColor = Color.Black;
messageLabel.ForeColor = Color.Yellow;
3 .1 1
M o r e G U I D e t a ils
T h e .N E T F r a m e w o r k a ls o p r o v id e s v a lu e s th a t r e p r e s e n t d e fa u lt c o lo r s o n y o u r s y s te m .
F o r e x a m p l e , t h e v a l u e SystemColors.Control r e p r e s e n t s t h e d e f a u l t c o n t r o l b a c k g r o u n d c o l o r a n d SystemColors.ControlText r e p r e s e n t s t h e d e f a u l t c o n t r o l t e x t c o l o r .
T h e f o l l o w i n g s t a t e m e n t s s e t t h e messageLabel c o n t r o l ’ s b a c k g r o u n d a n d f o r e g r o u n d t o
th e d e fa u lt c o lo r s :
messageLabel.BackColor = SystemColors.Control
messageLabel.ForeColor = SystemColors.ControlText
N O T E : If y o u h a v e a n e v e n t h a n d le r in a fo r m ’s s o u r c e c o d e file a n d y o u w a n t th e
e v e n t h a n d l e r t o c h a n g e t h e f o r m ’ s B a c k C o l o r p r o p e r t y , u s e t h e this k e y w o r d t o
r e fe r to th e fo r m . F o r e x a m p le , th e fo llo w in g s ta te m e n t c h a n g e s th e c o lo r o f th e fo r m
to b lu e :
this.BackColor = Color.Blue;
B a c k g r o u n d Im a g e s fo r F o r m s
In C h a p te r 2 , y o u le a r n e d a b o u t d is p la y in g im a g e s w ith P ic tu r e B o x c o n tr o ls . A n im a g e
c a n a ls o b e d is p la y e d a s th e b a c k g r o u n d fo r a fo r m . F o r m s h a v e a p r o p e r ty n a m e d B a c k g r o u n d Im a g e th a t a llo w s y o u to im p o r t a n d d is p la y a n im a g e o n th e fo r m . If y o u k n o w
h o w to u s e th e P ic tu r e B o x c o n tr o l’s Im a g e p r o p e r ty , th e n y o u a lr e a d y k n o w h o w to u s e a
fo r m ’s B a c k g r o u n d Im a g e p r o p e r ty . T h e y b o th w o r k th e s a m e w a y :
• C l i c k t h e B a c k g r o u n d I m a g e p r o p e r t y i n t h e Properties w i n d o w . A n e l l i p s e s b u t t o n
( ) w ill a p p e a r .
• C l i c k t h e e l l i p s e s b u t t o n a n d t h e Select Resource w i n d o w w i l l a p p e a r .
• I n t h e Select Resource w i n d o w , c l i c k t h e I mport b u t t o n . A n O pen d i a l o g b o x w i l l
a p p e a r . U s e th e d ia lo g b o x to lo c a te a n d s e le c t th e im a g e file th a t y o u w a n t
to d is p la y .
• C l i c k t h e O K b u t t o n i n t h e Select Resource w i n d o w , a n d t h e s e l e c t e d i m a g e w i l l
a p p e a r a s th e fo r m ’s b a c k g r o u n d .
A fo r m ’s B a c k g r o u n d Im a g e L a y o u t p r o p e r ty is s im ila r to th e P ic tu r e B o x c o n tr o l’s
S iz e M o d e p r o p e r ty . It s p e c ifie s h o w th e b a c k g r o u n d im a g e is to b e d is p la y e d . It c a n b e s e t
to o n e o f th e fo llo w in g v a lu e s :
• No n e
T h e im a g e is p o s itio n e d in th e u p p e r -le ft c o r n e r o f th e fo r m . If th e im a g e is to o b ig
to fit in th e fo r m , it is c lip p e d .
• T ile
T h is is th e d e fa u lt v a lu e . T h e im a g e is tile d (r e p e a te d ly d is p la y e d ) a c r o s s th e fo r m .
• Cen ter
T h e im a g e is c e n te r e d in th e fo r m w ith o u t b e in g r e s iz e d .
• Stretch
T h e im a g e is r e s iz e d b o th h o r iz o n ta lly a n d v e r tic a lly to fit in th e fo r m . If th e im a g e
is r e s iz e d m o r e in o n e d ir e c tio n th a n th e o th e r , it a p p e a r s s tr e tc h e d .
• Zo o m
T h e im a g e is u n ifo r m ly r e s iz e d to fit in th e fo r m w ith o u t lo s in g its o r ig in a l a s p e c t
r a tio . T h is c a u s e s th e im a g e to b e r e s iz e d w ith o u t a p p e a r in g s tr e tc h e d .
F ig u r e 3 -3 7 s h o w s e x a m p le s o f e a c h o f th e s e s e ttin g s .
181
182
C h a p te r 3
P r o c e s s in g D a t a
F ig u r e 3 -3 7
D iffe r e n t s e t t in g s fo r t h e B a c k g r o u n d Im a g e L a y o u t p r o p e r t y
BackgroundImageLayout set to None
BackgroundImageLayout set to Tile
BackgroundImageLayout set to Stretch
BackgroundImageLayout set to Center
BackgroundImageLayout set to Zoom
O r g a n iz in g C o n t r o ls w it h G r o u p B o x e s a n d P a n e ls
A G r o u p B o x c o n tr o l is a r e c ta n g u la r c o n tr o l th a t a p p e a r s w ith a th in b o r d e r a n d a n
o p tio n a l title in its u p p e r -le ft c o r n e r . It is a c o n ta in e r th a t c a n h o ld o th e r c o n tr o ls . Y o u
c a n u s e G r o u p B o x e s to c r e a te a s e n s e o f v is u a l o r g a n iz a tio n o n a fo r m .
T h e G r o u p B o x c o n t r o l i s f o u n d i n t h e Toolbox, i n t h e Containers s e c t i o n . W h e n y o u c r e a te a G r o u p B o x c o n tr o l, y o u c a n s e t its T itle p r o p e r ty to th e te x t th a t y o u w a n t d is p la y e d
in th e G r o u p B o x ’s u p p e r -le ft c o r n e r . If y o u d o n ’t w a n t a title d is p la y e d o n th e G r o u p B o x ,
y o u c a n c le a r th e c o n te n ts o f its T e x t p r o p e r ty .
F ig u r e 3 -3 8 s h o w s a fo r m w ith a G r o u p B o x c o n tr o l. T h e c o n tr o l’s T e x t p r o p e r ty is s e t to
Personal D ata, a n d s e v e r a l o t h e r c o n t r o l s a r e i n s i d e t h e G r o u p B o x . T h e i m a g e o n t h e l e f t
F ig u r e 3 -3 8
A G r o u p B o x c o n t a in in g o t h e r c o n t r o ls
3 .1 1
M o r e G U I D e t a ils
s h o w s h o w t h e f o r m a p p e a r s i n t h e D esigner, a n d t h e i m a g e o n t h e r i g h t s h o w s h o w t h e
fo r m a p p e a r s a t r u n tim e .
C r e a t in g a G r o u p B o x a n d A d d in g C o n t r o ls t o It
S u p p o s e y o u ’v e ju s t c r e a te d a G r o u p B o x c o n tr o l. T o a d d a n o th e r c o n tr o l to th e G r o u p B o x ,
s e l e c t t h e G r o u p B o x c o n t r o l a n d t h e n d o u b l e - c l i c k t h e d e s i r e d t o o l i n t h e Toolbox t o p l a c e
a n o th e r c o n tr o l in s id e th e g r o u p b o x .
M o v in g a n E x is t in g C o n t r o l t o a G r o u p B o x
If a n e x is tin g c o n tr o l is n o t in s id e a G r o u p B o x b u t y o u w a n t to m o v e it to th e G r o u p B o x ,
fo llo w th e s e s te p s :
1 . S e le c t th e c o n tr o l y o u w is h to a d d to th e G r o u p B o x .
2 . C u t th e c o n tr o l to th e c lip b o a r d .
3 . S e le c t th e G r o u p B o x .
4 . P a s te th e c o n tr o l.
M o v in g a n d R e s iz in g a G r o u p B o x
I f a G r o u p B o x i s s e l e c t e d i n t h e D esigner, a f o u r - h e a d e d a r r o w (
) w ill a p p e a r in th e
G r o u p B o x ’s u p p e r -le ft c o r n e r . C lic k a n d d r a g th e fo u r -h e a d e d a r r o w to m o v e th e G r o u p B o x .
A n y c o n tr o ls in s id e th e G r o u p B o x m o v e w ith it.
D e le t in g a G r o u p B o x
T o d e l e t e a G r o u p B o x , s i m p l y s e l e c t i t i n t h e D esigner a n d t h e n p r e s s t h e
c o n tr o ls in s id e th e G r o u p B o x a r e d e le te d a s w e ll.
k ey. An y
G r o u p B o x T a b O r d e r
T h e v a lu e o f a c o n tr o l’s T a b In d e x p r o p e r ty is h a n d le d d iffe r e n tly w h e n th e c o n tr o l is
p la c e d in s id e a G r o u p B o x c o n tr o l. G r o u p B o x c o n tr o ls h a v e th e ir o w n T a b In d e x p r o p e r ty , a n d th e T a b In d e x v a lu e o f th e c o n tr o ls in s id e th e g r o u p b o x a r e r e la tiv e to th e
G r o u p B o x c o n tr o l’s T a b In d e x p r o p e r ty . F o r e x a m p le , F ig u r e 3 -3 9 s h o w s a G r o u p B o x
c o n tr o l d is p la y e d in ta b o r d e r s e le c tio n m o d e . A s y o u c a n s e e , th e G r o u p B o x c o n tr o l’s
T a b In d e x is s e t to 0 . T h e T a b In d e x o f th e c o n tr o ls in s id e th e g r o u p b o x is d is p la y e d a s
0 .0 , 0 .1 , 0 .2 , a n d s o fo r th .
F ig u r e 3 -3 9
G r o u p B o x T a b In d e x v a lu e s
N O T E : T h e T a b In d e x p r o p e r tie s o f th e c o n tr o ls in s id e th e g r o u p b o x w ill n o t
a p p e a r t h i s w a y i n t h e Properties w i n d o w . T h e y w i l l a p p e a r a s 0 , 1 , 2 , a n d s o f o r t h .
183
184
C h a p te r 3
P r o c e s s in g D a t a
A P a n e l c o n tr o l is a r e c ta n g u la r c o n ta in e r fo r o th e r c o n tr o ls , lik e a G r o u p B o x . T h e r e a r e
s e v e r a l p r im a r y d iffe r e n c e s b e tw e e n a P a n e l a n d G r o u p B o x :
• A P a n e l c a n n o t d is p la y a title a n d d o e s n o t h a v e a T e x t p r o p e r ty .
• A P a n e l’s b o r d e r c a n b e s p e c ifie d b y its B o r d e r S ty le p r o p e r ty . T h e a v a ila b le s e ttin g s
a r e N o n e , F ix e d S in g le , a n d F ix e d 3 D . T h e p r o p e r ty is s e t to N o n e b y d e fa u lt, w h ic h
m e a n s th a t n o b o r d e r w ill a p p e a r . If th e B o r d e r S ty le p r o p e r ty is s e t to F ix e d S in g le ,
th e c o n tr o l w ill b e o u tlin e d w ith a th in b o r d e r . If th e B o r d e r S ty le p r o p e r ty is s e t to
F ix e d 3 D , th e c o n tr o l w ill h a v e a r e c e s s e d 3 D a p p e a r a n c e .
F ig u r e 3 -4 0 s h o w s a n e x a m p le o f a fo r m w ith a P a n e l. T h e P a n e l’s B o r d e r S ty le p r o p e r ty is
s e t to F ix e d 3 D . T h e im a g e o n th e le ft s h o w s th e fo r m a s it a p p e a r s in th e D e s ig n e r , a n d
th e im a g e o n th e r ig h t s h o w s h o w th e fo r m a p p e a r s a t r u n tim e .
F ig u r e 3 -4 0
3 .1 2
A P a n e l c o n t a in in g o t h e r c o n t r o ls
U s in g t h e D e b u g g e r t o L o c a t e L o g ic E r r o r s
C O N C E P T :
T h e V is u a l S tu d io d e b u g g e r a llo w s y o u to p a u s e a p r o g r a m a n d th e n
e x e c u te s ta te m e n ts o n e a t a tim e . A fte r e a c h s ta te m e n t e x e c u te s , y o u m a y
e x a m in e v a r ia b le c o n te n ts a n d p r o p e r ty v a lu e s .
A lo g ic e r r o r is a m is ta k e th a t d o e s n o t p r e v e n t a n a p p lic a tio n fr o m r u n n in g , b u t c a u s e s
th e a p p lic a tio n to p r o d u c e in c o r r e c t r e s u lts . M a th e m a tic a l m is ta k e s , a s s ig n in g a v a lu e to
th e w r o n g v a r ia b le , o r a s s ig n in g th e w r o n g v a lu e to a v a r ia b le a r e e x a m p le s o f lo g ic
e r r o r s . L o g ic e r r o r s c a n b e d iffic u lt to fin d . F in d in g a n d fix in g a lo g ic e r r o r u s u a lly r e q u ir e s
a b it o f d e te c tiv e w o r k o n th e p a r t o f th e p r o g r a m m e r . F o r tu n a te ly , V is u a l S tu d io p r o v id e s y o u w ith d e b u g g in g to o ls th a t m a k e lo c a tin g lo g ic e r r o r s e a s ie r .
V is u a l S tu d io a llo w s y o u to s e t b r e a k p o in ts in y o u r p r o g r a m c o d e . A b r e a k p o in t is a lin e
y o u s e le c t in y o u r s o u r c e c o d e . W h e n th e a p p lic a tio n is r u n n in g a n d it r e a c h e s a b r e a k p o in t, th e a p p lic a tio n p a u s e s a n d e n te r s b r e a k m o d e . W h ile th e a p p lic a tio n is p a u s e d , y o u
m a y e x a m in e v a r ia b le c o n te n ts a n d th e v a lu e s s to r e d in c e r ta in c o n tr o l p r o p e r tie s .
V is u a l S tu d io a llo w s y o u to s in g le -s te p th r o u g h a n a p p lic a tio n ’s c o d e o n c e its e x e c u tio n
h a s b e e n p a u s e d b y a b r e a k p o in t. T h is m e a n s th a t th e a p p lic a tio n ’s s ta te m e n ts e x e c u te
o n e a t a tim e , u n d e r y o u r c o n tr o l. A fte r e a c h s ta te m e n t e x e c u te s , y o u c a n e x a m in e v a r ia b le
a n d p r o p e r ty v a lu e s . T h is p r o c e s s a llo w s y o u to id e n tify th e lin e o r lin e s o f c o d e c a u s in g
th e e r r o r . In T u to r ia l 3 -6 , y o u s in g le -s te p th r o u g h a n a p p lic a tio n ’s c o d e .
3 .1 2
U s in g t h e D e b u g g e r t o L o c a t e L o g ic E r r o r s
T u t o r ia l 3 -6 :
S in g le - s t e p p in g t h r o u g h a n A p p lic a t io n ’ s C o d e a t R u n t im e
VideoNot e
T u to r ia l 3 -6 :
S in g le s te p p in g
th ro u gh an
A p p lic a tio n ’s
Co d e at
R u n tim e
I n t h i s t u t o r i a l , y o u w i l l o p e n t h e Average Race Times a p p l i c a t i o n , a n d t e s t i t f o r l o g i c
e r r o r s . T h e a p p lic a tio n is s im p le : It le ts th e u s e r e n te r th e fin is h in g tim e s fo r th r e e r u n n e r s ,
a n d th e n c lic k a b u tto n to c a lc u la te th e ir a v e r a g e tim e . T o d e te r m in e w h e th e r th e a p p lic a tio n c o r r e c tly c a lc u la te s a n a v e r a g e , y o u w ill p e r fo r m a s im p le te s t. Y o u w ill e n te r th e
v a lu e 2 5 fo r e a c h r u n n e r , a n d th e n c lic k th e b u tto n to c a lc u la te th e a v e r a g e . T h e r e s u lt
s h o u ld a ls o b e 2 5 . If th e a p p lic a tio n p r o d u c e s a n y o th e r v a lu e , th e n y o u k n o w th a t a lo g ic
e r r o r e x is ts s o m e w h e r e in th e a p p lic a tio n ’s c o d e .
S t e p 1 :
S t a r t V i s u a l S t u d i o . O p e n t h e p r o j e c t n a m e d Average Race Times i n t h e
Chap03 f o l d e r o f t h e S t u d e n t S a m p l e P r o g r a m s .
S t e p 2 :
R u n th e a p p lic a tio n . T h e a p p lic a tio n ’s fo r m a p p e a r s , a s s h o w n in F ig u r e 3 -4 1 .
F ig u r e 3 -4 1
T h e Avera ge Ra ce Times a p p l i c a t i o n r u n n i n g
S t e p 3 :
T h is a p p lic a tio n a llo w s y o u to e n te r th e fin is h in g tim e s o f th r e e r u n n e r s in a
r a c e , a n d th e n s e e th e ir a v e r a g e tim e . E n te r 2 5 a s th e tim e fo r a ll th r e e r u n n e r s .
S t e p 4 :
C l i c k t h e Calculate Average b u t t o n . T h e a p p l i c a t i o n d i s p l a y s t h e i n c o r r e c t
v a lu e 5 8 .3 a s th e a v e r a g e tim e . (T h e c o r r e c t v a lu e s h o u ld b e 2 5 .)
S t e p 5 :
C l i c k t h e Exit b u t t o n t o s t o p t h e a p p l i c a t i o n .
S t e p 6 :
O p e n t h e c o d e e d i t o r ( c l i c k View o n t h e m e n u b a r , a n d t h e n s e l e c t Code) a n d
l o c a t e t h e f o l l o w i n g l i n e o f c o d e , w h i c h a p p e a r s i n t h e calculateButton_Click
e v e n t h a n d le r :
runner1 = double.Parse(runner1TextBox.Text);
T h is lin e o f c o d e is w h e r e w e w a n t to p a u s e th e e x e c u tio n o f th e a p p lic a tio n .
W e m u s t m a k e th is lin e a b r e a k p o in t.
S t e p 7 :
C lic k th e m o u s e in th e le ft m a r g in o f th e c o d e e d ito r , n e x t to th e lin e o f c o d e , a s
s h o w n in F ig u r e 3 -4 2 . N o tic e th a t a r e d d o t a p p e a r s n e x t to th e lin e in th e le ft
m a r g in , a n d th e lin e o f c o d e b e c o m e s h ig h lig h te d . T h e d o t in d ic a te s th a t a
b r e a k p o in t h a s b e e n s e t o n th is lin e . A n o th e r w a y to s e t a b r e a k p o in t is to m o v e
th e te x t c u r s o r to th e lin e y o u w is h to s e t a s a b r e a k p o in t, a n d th e n p r e s s
.
S t e p 8 :
N o w th a t y o u h a v e s e t th e b r e a k p o in t, r u n th e a p p lic a tio n . W h e n th e fo r m
a p p e a r s , e n te r 2 5 a s th e tim e fo r e a c h r u n n e r .
185
186
C h a p te r 3
P r o c e s s in g D a t a
F ig u r e 3 -4 2
S e t t in g a b r e a k p o in t
Click the mouse
pointer here.
S t e p 9 :
C l i c k t h e Calculate Average b u t t o n . W h e n p r o g r a m e x e c u t i o n r e a c h e s t h e
b r e a k p o in t, it g o e s in to b r e a k m o d e a n d th e c o d e e d ito r r e a p p e a r s . T h e b r e a k p o in t lin e is s h o w n w ith y e llo w h ig h lig h tin g a n d a s m a ll y e llo w a r r o w a p p e a r s
in th e le ft m a r g in , a s s h o w n in F ig u r e 3 -4 3 . T h e y e llo w h ig h lig h tin g a n d s m a ll
a r r o w in d ic a te th e a p p lic a tio n ’s c u r r e n t e x e c u tio n p o in t. T h e e x e c u tio n p o in t
is th e n e x t lin e o f c o d e th a t w ill e x e c u te . (T h e lin e h a s n o t y e t e x e c u te d .)
F ig u r e 3 -4 3
B r e a k p o in t r e a c h e d
N O T E : If th e h ig h lig h tin g a n d a r r o w a p p e a r in a c o lo r o th e r th a n y e llo w , th e
c o lo r o p tio n s o n y o u r s y s te m m a y h a v e b e e n c h a n g e d .
S t e p 1 0 : T o e x a m in e th e c o n te n ts o f a v a r ia b le o r c o n tr o l p r o p e r ty , h o v e r th e c u r s o r
o v e r th e v a r ia b le o r th e p r o p e r ty ’s n a m e in th e c o d e e d ito r . A s m a ll b o x w ill
a p p e a r s h o w in g th e v a r ia b le o r p r o p e r ty ’s c o n te n ts . F o r e x a m p le , F ig u r e 3 -4 4
3 .1 2
F ig u r e 3 -4 4
U s in g t h e D e b u g g e r t o L o c a t e L o g ic E r r o r s
runner1TextBox.Text p r o p e r t y c o n t e n t s r e v e a l e d
s h o w s th e r e s u lt o f h o v e r in g th e m o u s e p o in te r o v e r th e e x p r e s s io n
runner1TextBox.Text i n t h e h i g h l i g h t e d l i n e . T h e b o x i n d i c a t e s t h a t t h e
p r o p e r ty is c u r r e n tly s e t to “ 2 5 .”
S t e p 1 1 : N o w , h o v e r t h e m o u s e p o i n t e r o v e r t h e v a r i a b l e n a m e runner1 . A b o x
a p p e a r s in d ic a tin g th a t th e v a r ia b le is s e t to 0 . B e c a u s e th e h ig h lig h te d s ta te m e n t h a s n o t y e t e x e c u te d , n o v a lu e h a s b e e n a s s ig n e d to th is v a r ia b le .
S t e p 1 2 : Y o u m a y a l s o e x a m i n e t h e c o n t e n t s o f v a r i a b l e s w i t h t h e Autos, L ocals, a n d
Watch w i n d o w s . ( T h e I mmediate w i n d o w i s b e y o n d t h e s c o p e o f t h i s c h a p t e r . )
A d e s c r ip tio n o f e a c h w in d o w fo llo w s :
• T h e Autos w i n d o w d i s p l a y s a l i s t o f t h e v a r i a b l e s a p p e a r i n g i n t h e c u r r e n t
statemen t, th e th ree statemen ts b efo re, an d th e th ree statemen ts after th e
c u r r e n t s ta te m e n t. T h e c u r r e n t v a lu e a n d th e d a ta ty p e o f e a c h v a r ia b le a r e
a ls o d is p la y e d .
• T h e Immediate w i n d o w a l l o w s y o u t o t y p e d e b u g g i n g c o m m a n d s u s i n g
th e k e y b o a r d . T h is w in d o w is g e n e r a lly u s e d b y a d v a n c e d p r o g r a m m e r s .
• T h e Locals w i n d o w d i s p l a y s a l i s t o f a l l t h e v a r i a b l e s i n t h e c u r r e n t p r o c e d u r e .
T h e c u r r e n t v a lu e a n d th e d a ta ty p e o f e a c h v a r ia b le a r e a ls o d is p la y e d .
• T h e Watch w i n d o w a l l o w s y o u t o a d d t h e n a m e s o f v a r i a b l e s y o u w a n t t o
w a tc h . T h is w in d o w d is p la y s o n ly th e v a r ia b le s y o u h a v e a d d e d . V is u a l
S t u d i o l e t s y o u o p e n m u l t i p l e Watch w i n d o w s .
Y o u c a n o p e n a n y o f t h e s e w i n d o w s b y c l i c k i n g D ebug o n t h e m e n u b a r , t h e n
s e l e c t i n g Windows, a n d t h e n s e l e c t i n g t h e w i n d o w t h a t y o u w a n t t o o p e n .
U s e t h i s t e c h n i q u e t o o p e n t h e L ocals w i n d o w n o w .
T h e L ocals w i n d o w s h o u l d a p p e a r , s i m i l a r t o F i g u r e 3 - 4 5 .
F ig u r e 3 -4 5
Loca ls w i n d o w d i s p l a y e d
S t e p 1 3 : N o w y o u
a r e r e a d y to s in g le -s te p th r o u g h e a c h s ta te m e n t in th e e v e n t h a n d l e r . T o d o t h i s , u s e t h e Step Into c o m m a n d . ( T h e Step O ver c o m m a n d ,
w h i c h i s s i m i l a r t o Step I nto, i s c o v e r e d i n C h a p t e r 6 . ) Y o u a c t i v a t e t h e Step
I nto c o m m a n d b y o n e o f t h e f o l l o w i n g m e t h o d s :
• P ress th e
k ey.
• C l i c k D ebug o n
D ebug m e n u .
th e m e n u
b a r , a n d
th e n
s e l e c t Step I nto f r o m t h e
187
188
C h a p te r 3
P r o c e s s in g D a t a
W h e n y o u a c t i v a t e t h e Step I nto c o m m a n d , t h e h i g h l i g h t e d s t a t e m e n t i s
ex ecu ted . P ress th e
k e y n o w . L o o k a t t h e Watch w i n d o w a n d n o t i c e t h a t
t h e runner1 v a r i a b l e i s n o w s e t t o 2 5 . A l s o n o t i c e t h a t t h e n e x t l i n e o f c o d e
is n o w h ig h lig h te d .
S t e p 1 4 : P r e s s th e
k e y t w o m o r e t i m e s . T h e v a r i a b l e s runner1, runner2, a n d
runner3 s h o u l d d i s p l a y v a l u e s o f 2 5 i n t h e L ocals w i n d o w .
S t e p 1 5 : T h e fo llo w in g s ta te m e n t, w h ic h
is s u p p o s e d to c a lc u la te th e a v e r a g e o f th e
th r e e s c o r e s , is n o w h ig h lig h te d :
average = runner1 + runner2 + runner3 / 3.0;
A fte r th is s ta te m e n t e x e c u te s , th e a v e r a g e o f th e th r e e n u m b e r s s h o u ld d is p l a y n e x t t o average. P r e s s
to ex ecu te th e statemen t.
S t e p 1 6 : N o t i c e t h a t t h e L ocals w i n d o w n o w r e p o r t s t h a t average h o l d s t h e v a l u e
5 8 .3 3 3 3 3 3 3 3 3 3 3 3 3 3 6 . T h is is n o t th e c o r r e c t v a lu e , s o th e r e m u s t b e a p r o b le m w ith th e m a th s ta te m e n t th a t ju s t e x e c u te d . C a n y o u fin d it? T h e m a th
s ta te m e n t d o e s n o t c a lc u la te th e c o r r e c t v a lu e b e c a u s e th e d iv is io n o p e r a tio n
ta k e s p la c e b e fo r e a n y o f th e a d d itio n o p e r a tio n s . Y o u m u s t c o r r e c t th e s ta te m e n t b y in s e r tin g a s e t o f p a r e n th e s e s .
F r o m t h e m e n u , s e l e c t D ebug, a n d t h e n c l i c k Stop D ebugging t o h a l t t h e
a p p l i c a t i o n . I n t h e Code w i n d o w , i n s e r t a s e t o f p a r e n t h e s e s i n t o t h e m a t h
s ta te m e n t s o it a p p e a r s a s fo llo w s :
average = (runner1 + runner2 + runner3) / 3.0;
S t e p 1 7 : N e x t, y o u
w ill c le a r th e b r e a k p o in t s o th e a p p lic a tio n w ill n o t p a u s e a g a in
w h e n it r e a c h e s th a t lin e o f c o d e . T o c le a r th e b r e a k p o in t, u s e o n e o f th e
fo llo w in g m e th o d s :
• C lic k th e m o u s e o n th e b r e a k p o in t d o t in th e le ft m a r g in o f th e c o d e e d ito r .
• P ress
+
+
.
• S e l e c t D ebug f r o m t h e m e n u b a r , a n d t h e n s e l e c t D elete All Breakpoints
f r o m t h e D ebug m e n u .
S t e p 1 8 : R u n th e a p p lic a tio n a g a in . E n te r 2 5 a s e a c h r u n n e r ’s tim e , a n d th e n c lic k th e
Calculate Average b u t t o n . T h i s t i m e t h e c o r r e c t a v e r a g e , 2 5 . 0 , i s d i s p l a y e d .
S t e p 1 9 : C l i c k t h e Exit b u t t o n t o s t o p t h e a p p l i c a t i o n .
D e b u g g in g C o m m a n d s in t h e T o o lb a r
V is u a l S tu d io p r o v id e s a to o lb a r fo r d e b u g g in g c o m m a n d s , s h o w n in F ig u r e 3 -4 6 .
F ig u r e 3 -4 6
D e b u g to o lb a r c o m m a n d s
Step Into
Break All
Start or continue
Debugging
Stop Debugging
Step Over
Step Out
3 .1 2
U s in g t h e D e b u g g e r t o L o c a t e L o g ic E r r o r s
C h e c k p o in t
3 .5 0
W h a t h a p p e n s if y o u p r e s s th e E n te r k e y w h ile a B u tto n c o n tr o l h a s th e fo c u s ?
3 .5 1
H o w d o y o u d is p la y a fo r m in ta b o r d e r s e le c tio n m o d e ? H o w d o y o u e x it ta b
o r d e r s e le c tio n m o d e ?
3 .5 2
W r ite a p r o g r a m m in g s ta te m e n t th a t g iv e s th e fo c u s to a T e x tB o x c o n tr o l n a m e d
numberTextBox.
3 .5 3
H o w d o y o u a s s ig n a n a c c e s s k e y to a B u tto n c o n tr o l?
3 .5 4
H o w d o y o u d is p la y a n a m p e r s a n d (& ) c h a r a c te r o n a B u tto n c o n tr o l?
3 .5 5
W r ite th e c o d e th a t w ill c h a n g e th e B a c k C o lo r p r o p e r ty o f a L a b e l c o n tr o l n a m e d
resultLabel t o t h e c o l o r w h i t e a n d t h e F o r e C o l o r p r o p e r t y t o t h e c o l o r r e d .
3 .5 6
L is t th e d iffe r e n t v a lu e s o f a fo r m ’s B a c k g r o u n d Im a g e L a y o u t p r o p e r ty .
3 .5 7
W h e n a G r o u p B o x c o n tr o l is d e le te d , w h a t h a p p e n s to th e c o n tr o ls th a t a r e in s id e ?
3 .5 8
H o w a r e th e T a b In d e x p r o p e r tie s o f th e c o n tr o ls in s id e th e g r o u p b o x o r g a n iz e d ?
3 .5 9
H o w is a P a n e l c o n tr o l d iffe r e n t fr o m a G r o u p B o x c o n tr o l?
189
190
C h a p te r 3
P r o c e s s in g D a t a
K e y T e r m s
accep t b u tto n
access k ey
a c c e s s m o d ifie r
argu men t
A u to s w in d o w
B a c k C o lo r p r o p e r ty
b reak mo d e
b r e a k p o in t
can cel b u tto n
cast o p erato r
c a tc h b lo c k
catch c l a u s e
c o m b in e d a s s ig n m e n t o p e r a to r s
c o n c a te n a tio n
c o n s ta n t fie ld
d ata typ e
decimal l i t e r a l
decimal.Parse m e t h o d
double l i t e r a l
double.Parse m e t h o d
e x c e p tio n
e x c e p tio n h a n d le r
e x c e p tio n o b je c t
e x e c u tio n p o in t
fie ld
fo cu s
Focus m e t h o d
F o r e C o lo r
fo r m a ttin g s tr in g
Gro u p Bo x Co n tro l
Im m e d ia te w in d o w
in itia liz e
int.Parse m e t h o d
in te g e r lite r a l
life tim e
lo c a l v a r ia b le
L o c a ls w in d o w
lo g ic e r r o r
m a th e x p r e s s io n
math o p erato rs
m n e m o n ic
n amed co n stan t
n u m e r ic lite r a l
o p eran d s
o r d e r o f o p e r a tio n s
P an el co n tro l
p arse
Parse m e t h o d s
p r im itiv e d a ta ty p e s
sco p e
s in g le -s te p
tab o rd er
ta b o r d e r s e le c tio n m o d e
Tab In d ex p ro p erty
Tex tBo x co n tro l
ToString m e t h o d
tr u n c a tio n
tr y b lo c k
try-catch s t a t e m e n t
v a r ia b le
v a r ia b le d e c la r a tio n
v a r ia b le n a m e
W a tc h w in d o w
R e v ie w Q u e s t io n s
M u lt ip le C h o ic e
1 .
W h e n th e u s e r ty p e s in to a T e x tB o x c o n tr o l, th e te x t is s to r e d in th e c o n tr o l’s
__________ p ro p erty.
a.
b .
c.
d .
2 .
A _ _ _ _ _ _ _ _ _ _ is a s to r a g e lo c a tio n in m e m o r y th a t is r e p r e s e n te d b y a n a m e .
a.
b .
c.
d .
3 .
In p u t
Tex t
S tr in g
Data
m n e m o n ic
d ata typ e
n amesp ace
v a r ia b le
In C # , y o u m u s t _ _ _ _ _ _ _ _ _ _ a v a r ia b le b e fo r e y o u c a n u s e it to s to r e d a ta .
a.
b .
c ite
a s s o c ia te
R e v ie w Q u e s t io n s
c.
d .
4 .
A v a r ia b le ’s _ _ _ _ _ _ _ _ _ _ in d ic a te s th e ty p e o f d a ta th a t th e v a r ia b le w ill h o ld .
a.
b .
c.
d .
5 .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
ran ge
sco p e
fo cu s
fie ld
A v a r ia b le ’s _ _ _ _ _ _ _ _ _ _ is th e tim e p e r io d d u r in g w h ic h th e v a r ia b le e x is ts in m e m o r y w h ile th e p r o g r a m is e x e c u tin g .
a.
b .
c.
d .
1 1 .
m e th o d v a r ia b le
p r im itiv e v a r ia b le
te m p o r a r y v a r ia b le
lo c a l v a r ia b le
P r o g r a m m e r s u s e th e te r m _ _ _ _ _ _ _ _ _ _ to d e s c r ib e th e p a r t o f a p r o g r a m in w h ic h a
v a r ia b le m a y b e a c c e s s e d .
a.
1 0 .
a d d itio n
m e r g in g
c o n c a te n a tio n
ty in g
A _ _ _ _ _ _ _ _ _ _ b e lo n g s to th e m e th o d in w h ic h it is d e c la r e d , a n d o n ly s ta te m e n ts
in s id e th a t m e th o d c a n a c c e s s th e v a r ia b le .
a.
9 .
b in a r y n u m b e r
v a r ia b le n a m e
u n iq u e g lo b a l id e n tifie r
h e x a d e c im a l v a lu e
A c o m m o n o p e r a tio n p e r fo r m e d o n s tr in g s is _ _ _ _ _ _ _ _ _ _ , o r a p p e n d in g o n e s tr in g
to th e e n d o f a n o th e r s tr in g .
a.
8 .
p r im itiv e d a ta ty p e s
fu n d a m e n ta l v a r ia b le s
lo g ic a l d ig its
lite r a l d a ta ty p e s
A _ _ _ _ _ _ _ _ _ _ id e n tifie s a v a r ia b le in th e p r o g r a m c o d e .
a.
7 .
n ame
d ata typ e
sco p e
v a lu e
F u n d a m e n ta l ty p e s o f d a ta , s u c h a s s tr in g s , in te g e r s , a n d r e a l n u m b e r s , a r e k n o w n
as __________.
a.
6 .
d e c la r e
in s ta n c e
life tim e
r u n tim e
tim e to liv e
h a lf life
O n e w a y to m a k e s u r e th a t a v a r ia b le h a s b e e n a s s ig n e d a v a lu e is to _ _ _ _ _ _ _ _ _ _ th e
v a r ia b le w ith a v a lu e w h e n y o u d e c la r e it.
a.
b .
c.
d .
co n caten ate
in itia liz e
d e lim it
r e s tr ic t
191
192
C h a p te r 3
P r o c e s s in g D a t a
1 2 .
Y o u c a n u s e a _ _ _ _ _ _ _ _ _ _ to e x p lic itly c o n v e r t a v a lu e fr o m o n e n u m e r ic d a ta ty p e
to a n o th e r , e v e n if th e c o n v e r s io n m ig h t r e s u lt in a lo s s o f d a ta .
a.
b .
c.
d .
1 3 .
T h e p r o c e s s o f d r o p p in g a n u m b e r ’s fr a c tio n a l p a r t is c a lle d _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
1 4 .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
v a r ia b le
argu men t
s tr in g
lite r a l
A (n ) _ _ _ _ _ _ _ _ _ _ is a n u n e x p e c te d e r r o r th a t o c c u r s w h ile a p r o g r a m is r u n n in g ,
c a u s in g th e p r o g r a m to h a lt if th e e r r o r is n o t p r o p e r ly d e a lt w ith .
a.
b .
c.
d .
2 0 .
c o m p ile
co mp u te
d eb u g
p arse
A (n ) _ _ _ _ _ _ _ _ _ _ is a p ie c e o f d a ta th a t is p a s s e d in to a m e th o d .
a.
1 9 .
c o m b in e d a s s ig n m e n t o p e r a to r s
ad van ced math o p erato rs
v a r ia b le m o d ifie r s
a s s ig n m e n t s e q u e n c e r s
In c o m p u te r s c ie n c e , th e te r m _ _ _ _ _ _ _ _ _ _ ty p ic a lly m e a n s to a n a ly z e a s tr in g o f
ch aracters fo r so me p u rp o se.
a.
1 8 .
n u m e r ic lite r a l
m a th e x p r e s s io n
m a c h in e in s tr u c tio n
p r o g r a m m in g s ta te m e n t
C # o ffe r s a s p e c ia l s e t o f o p e r a to r s k n o w n a s _ _ _ _ _ _ _ _ _ _ th a t a r e d e s ig n e d s p e c ific a lly
fo r c h a n g in g th e v a lu e o f a v a r ia b le w ith o u t h a v in g to ty p e th e v a r ia b le n a m e tw ic e .
a.
1 7 .
math o p erato rs
n u m e r ic lite r a ls
lo c a l v a r ia b le s
p a r s e d lite r a ls
A _ _ _ _ _ _ _ _ _ _ p e r fo r m s a c a lc u la tio n a n d g iv e s a v a lu e .
a.
1 6 .
s h iftin g
tw o s c o m p le m e n t
n u m e r ic r o u n d in g
tr u n c a tio n
A p r o g r a m m e r ’s to o ls fo r p e r fo r m in g c a lc u la tio n s a r e _ _ _ _ _ _ _ _ _ _ .
a.
1 5 .
tran sp o se statemen t
cast o p erato r
c o n v e r s io n o p e r a to r
lite r a l c o n v e r s io n
b r e a k p o in t
b u g
syn tax erro r
e x c e p tio n
T h e _ _ _ _ _ _ _ _ _ _ in d ic a te s th a t y o u w a n t th e n u m b e r to a p p e a r fo r m a tte d in a s p e c i f i c w a y w h e n i t i s r e t u r n e d a s a s t r i n g f r o m t h e ToString m e t h o d .
a.
b .
fo r m a ttin g s tr in g
insert m e t h o d
R e v ie w Q u e s t io n s
c.
d .
2 1 .
Y o u h a v e s t a r t e d a n a p p l i c a t i o n b y c l i c k i n g t h e s t a r t D ebugging b u t t o n ( ) o r b y
p r e s s in g
o n th e k e y b o a r d . If a n e x c e p tio n is th r o w n , th e a p p lic a tio n s to p s r u n n in g a n d V is u a l S tu d io g o e s in to a s p e c ia l m o d e k n o w n a s _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
2 2 .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
b .
c.
d .
s ta tic fie ld
c la s s n a m e
k e y fie ld
c o n s ta n t fie ld
T h e .N E T F r a m e w o r k p r o v id e s a c la s s n a m e d _ _ _ _ _ _ _ _ _ _ , w h ic h c o n ta in s n u m e r o u s m e th o d s th a t a r e u s e fu l fo r p e r fo r m in g a d v a n c e d m a th e m a tic a l o p e r a tio n s .
a.
b .
c.
d .
2 8 .
n amesp ace
a c c e s s m o d ifie r
s c o p e d e lim ite r
c la s s d ir e c tiv e
A _ _ _ _ _ _ _ _ _ _ is a fie ld th a t c a n n o t b e c h a n g e d b y a n y s ta te m e n t in th e c la s s .
a.
2 7 .
term
c la s s v a r ia b le
fie ld
m n e m o n ic
A (n ) _ _ _ _ _ _ _ _ _ _ s p e c ifie s h o w a c la s s m e m b e r c a n b e a c c e s s e d b y c o d e o u ts id e th e
c la s s .
a.
2 6 .
n a m e d lite r a l
n amed co n stan t
v a r ia b le s ig n a tu r e
k ey term
A _ _ _ _ _ _ _ _ _ _ is a v a r ia b le th a t is d e c la r e d in s id e a c la s s b u t n o t in s id e a n y m e th o d .
a.
2 5 .
e x it s tr a te g y
fa il s a fe
e v e n t h a n d le r
e x c e p tio n h a n d le r
A _ _ _ _ _ _ _ _ _ _ is a n a m e th a t r e p r e s e n ts a v a lu e th a t c a n n o t b e c h a n g e d d u r in g th e
p r o g r a m ’s e x e c u tio n .
a.
2 4 .
e x c e p tio n m o d e
b reak mo d e
d eb u g mo d e
crash mo d e
C o d e th a t r e s p o n d s to e x c e p tio n s w h e n th e y a r e th r o w n a n d p r e v e n ts th e p r o g r a m
fr o m a b r u p tly c r a s h in g is c a lle d a (n ) _ _ _ _ _ _ _ _ _ _ .
a.
2 3 .
d ata typ e
v a r ia b le n a m e
Math
Calc
Trig
Linq
W h e n a c o n tr o l h a s th e _ _ _ _ _ _ _ _ _ _ , it r e c e iv e s th e u s e r ’s k e y b o a r d in p u t.
a.
b .
c.
d .
tex t
tab o rd er
fo cu s
in p u t a llo c a to r
193
194
C h a p te r 3
P r o c e s s in g D a t a
2 9 .
T h e o r d e r in w h ic h c o n tr o ls r e c e iv e th e fo c u s is c a lle d th e _ _ _ _ _ _ _ _ _ _ .
a.
b .
c.
d .
3 0 .
o r d e r o f o p e r a tio n s
p r o g r a m flo w
e x e c u tio n s e q u e n c e
tab o rd er
T h e _ _ _ _ _ _ _ _ _ _ c o n ta in s a n u m e r ic v a lu e , w h ic h in d ic a te s th e c o n tr o l’s p o s itio n in
th e tab o rd er.
a.
b .
c.
d .
In d ex Of p ro p erty
Tab In d ex p ro p erty
C o n tr o lO r d e r p r o p e r ty
Tab Ord er p ro p erty
T r u e o r F a ls e
1 .
Y o u c a n c le a r th e c o n te n ts o f a T e x tB o x c o n tr o l in th e s a m e w a y th a t y o u c le a r th e
c o n te n ts o f a L a b e l c o n tr o l.
2 .
In C # , y o u m u s t d e c la r e a v a r ia b le in a p r o g r a m b e fo r e y o u c a n u s e it to s to r e d a ta .
3 .
Y o u c a n d e c la r e m u ltip le v a r ia b le s o f d iffe r e n t d a ta ty p e s w ith o n e d e c la r a tio n .
4 .
W h e n y o u a p p e n d t h e l e t t e r D o r d t o a n u m e r i c l i t e r a l , i t i s t r e a t e d a s a decimal a n d
i s r e f e r r e d t o a s a decimal l i t e r a l .
5 .
T h e o r d e r o f o p e r a tio n s d ic ta te s th a t th e d iv is io n o p e r a to r w o r k s b e fo r e th e a d d itio n o p e r a to r d o e s .
6 .
A l l v a r i a b l e s h a v e a ToString m e t h o d t h a t y o u c a n c a l l t o c o n v e r t t h e v a r i a b l e ’ s
v a lu e to a s tr in g .
7 .
W h e n y o u p a s s t h e f o r m a t t i n g s t r i n g "C" o r "c" t o t h e ToString m e t h o d , t h e n u m b e r is r e tu r n e d fo r m a tte d a s c u r r e n c y .
8 .
W h e n y o u d e c la r e a n a m e d c o n s ta n t, a n in itia liz a tio n v a lu e is r e q u ir e d .
9 .
A n e r r o r w ill o c c u r if th e c o m p ile r fin d s a s ta te m e n t th a t tr ie s to c h a n g e th e v a lu e o f
a c o n s ta n t fie ld .
1 0 .
F o r m s a n d m o s t c o n tr o ls h a v e a P r e fe r e n c e s p r o p e r ty th a t a llo w s y o u to c h a n g e th e
o b je c t’s b a c k g r o u n d c o lo r .
S h o r t A n s w e r
1 .
I n t h e Toolbox, i n w h i c h g r o u p i s t h e T e x t B o x t o o l l o c a t e d ?
2 .
W h a t tw o th in g s d o e s a v a r ia b le d e c la r a tio n s p e c ify a b o u t a v a r ia b le ?
3 .
G iv e a n e x a m p le o f a p r o g r a m m in g s ta te m e n t th a t u s e s s tr in g c o n c a te n a tio n .
4 .
W h a t is th e te r m u s e d fo r a n u m b e r th a t is w r itte n in to a p r o g r a m ’s c o d e ?
5 .
W r ite a p r o g r a m m in g s ta te m e n t th a t a s s ig n s a n in te g e r lite r a l to a v a r ia b le .
6 .
W h a t a r e th e v a lu e s o n th e r ig h t a n d le ft o f a n o p e r a to r c a lle d ?
7 .
N a m e th e fa m ily o f m e th o d s in th e .N E T F r a m e w o r k th a t c a n b e u s e d to c o n v e r t a
s tr in g to a n y o f th e n u m e r ic d a ta ty p e s .
8 .
W h a t o b je c t is c r e a te d in m e m o r y w h e n a n e x c e p tio n is th r o w n a n d h a s v a r io u s
p r o p e r tie s th a t c o n ta in d a ta a b o u t th e e x c e p tio n ?
9 .
W h a t i s t h e p u r p o s e o f a try-catch s t a t e m e n t ?
P r o g r a m m in g P r o b le m s
1 0 .
W h ic h c la s s in th e .N E T F r a m e w o r k p r o v id e s p r e d e fin e d n a m e d c o n s ta n ts th a t a r e
a s s i g n e d t h e m a t h e m a t i c a l v a l u e s f o r pi a n d e?
1 1 .
In c o d e , w h a t fu n c tio n d o y o u c a ll to m o v e th e fo c u s to a c o n tr o l?
1 2 .
W h a t p r o p e r ty a llo w s y o u to c h a n g e th e c o lo r o f a c o n tr o l’s te x t?
P r o g r a m m in g P r o b le m s
1 .
Name F o rmatter
C r e a te a n a p p lic a tio n th a t le ts th e u s e r e n te r th e fo llo w in g p ie c e s o f d a ta :
•
•
•
•
T h e u s e r ’s fir s t n a m e
T h e u s e r ’s m id d le n a m e
T h e u s e r ’s la s t n a m e
T h e u s e r ’s p r e fe r r e d title (M r ., M r s ., M s ., D r ., e tc .)
A s s u m e th e u s e r h a s e n te r e d th e fo llo w in g d a ta :
•
•
•
•
F i r s t n a m e : Kelly
M i d d l e n a m e : Jane
L a s t n a m e : Smith
T i t l e : M s.
T h e a p p lic a tio n s h o u ld h a v e b u tto n s th a t d is p la y th e u s e r ’s n a m e fo r m a tte d in th e
fo llo w in g w a y s :
M s. Kelly Jane Smith
Kelly Jane Smith
Kelly Smith
Smith, Kelly Jane, M s.
Smith, Kelly Jane
Smith, Kelly
2 .
C r e a te a n a p p lic a tio n th a t le ts th e u s e r e n te r th e fo o d c h a r g e fo r a m e a l a t a
r e s ta u r a n t. W h e n a b u tto n is c lic k e d , th e a p p lic a tio n s h o u ld c a lc u la te a n d
d is p la y th e a m o u n t o f a 1 5 p e r c e n t tip , 7 p e r c e n t s a le s ta x , a n d th e to ta l o f a ll
th r e e a m o u n ts .
VideoNot e
S o lv in g th e
T ip , T a x ,
an d To tal
P r o b le m
T ip , T a x , a n d T o ta l
3 .
D is ta n c e T r a v e le d
A s s u m in g th e r e a r e n o a c c id e n ts o r d e la y s , th e d is ta n c e th a t a c a r tr a v e ls d o w n a n
in te r s ta te h ig h w a y c a n b e c a lc u la te d w ith th e fo llo w in g fo r m u la :
D is ta n c e = S p e e d × T im e
C r e a te a n a p p lic a tio n th a t a llo w s th e u s e r to e n te r a c a r ’s s p e e d in m ile s p e r h o u r .
T h e a p p lic a tio n s h o u ld h a v e b u tto n s th a t d is p la y th e fo llo w in g :
•
•
•
4 .
T h e d is ta n c e th e c a r w ill tr a v e l in 5 h o u r s
T h e d is ta n c e th e c a r w ill tr a v e l in 8 h o u r s
T h e d is ta n c e th e c a r w ill tr a v e l in 1 2 h o u r s
S a le s T a x a n d T o ta l
C r e a te a n a p p lic a tio n th a t a llo w s th e u s e r to e n te r th e a m o u n t o f a p u r c h a s e . T h e
p r o g r a m s h o u ld th e n c a lc u la te th e s ta te a n d c o u n ty s a le s ta x . A s s u m e th e s ta te s a le s
ta x is 4 p e r c e n t a n d th e c o u n ty s a le s ta x is 2 p e r c e n t. T h e p r o g r a m s h o u ld d is p la y
th e a m o u n t o f th e p u r c h a s e , th e s ta te s a le s ta x , th e c o u n ty s a le s ta x , th e to ta l s a le s
ta x , a n d th e to ta l o f th e s a le (w h ic h is th e s u m o f th e a m o u n t o f p u r c h a s e p lu s th e
to ta l s a le s ta x ).
195
196
C h a p te r 3
P r o c e s s in g D a t a
5 .
C e ls iu s a n d F a h r e n h e it T e m p e r a tu r e C o n v e r te r
A s s u m in g th a t Cis a C e ls iu s te m p e r a tu r e , th e fo llo w in g fo r m u la c o n v e r ts th e te m p e r a tu r e to F a h r e n h e it:
9
F=
5
C+ 3 2
A s s u m in g th a t Fis a F a h r e n h e it te m p e r a tu r e , th e fo llo w in g fo r m u la c o n v e r ts th e
te m p e r a tu r e to C e ls iu s :
C=
9
( F − 32)
5
Create an application that allows the user to enter a temperature. The application
should have Button controls described as follows:
•
•
6 .
A button that reads Convert to Fahrenheit. If the user clicks this button, the
application should treat the temperature that is entered as a Celsius temperature
and convert it to Fahrenheit.
A button that reads Convert to Celsius. If the user clicks this button, the application should treat the temperature that is entered as a Fahrenheit temperature,
and convert it to Celsius.
Bo d y Mass In d ex
Create an application that lets the user enter his or her weight (in pounds) and
height (in inches). The application should display the user’s body mass index (BM I).
The BM I is often used to determine whether a person is overweight or underweight
for his or her height. A person’s BM I is calculated with the following formula:
BM I = weight × 703 ÷ height 2
7 .
S e n te n c e B u ild e r
The form in Figure 3-47 contains buttons showing various words, phrases, and
punctuation. Create an application with a form similar to this one. When the application runs, the user clicks the buttons to build a sentence, which is shown in a
Label control. You can use the same buttons as shown in the figure or make up your
own. The Reset button should clear the sentence so the user can start over.
F ig u r e 3 -4 7
T h e Sentence Builder f o r m
8 .
Ho w Mu ch In su ran ce?
M any financial experts advise that property owners should insure their homes or
buildings for at least 80 percent of the amount it would cost to replace the
structure. Create an application that lets the user enter the replacement cost of a
P r o g r a m m in g P r o b le m s
b u ild in g a n d th e n d is p la y s th e m in im u m a m o u n t o f in s u r a n c e h e o r s h e s h o u ld
b u y fo r th e p ro p erty.
9 .
C o o k ie C a lo r ie s
A b a g o f c o o k ie s h o ld s 4 0 c o o k ie s . T h e c a lo r ie in fo r m a tio n o n th e b a g c la im s th a t
th e r e a r e 1 0 s e r v in g s in th e b a g a n d th a t a s e r v in g e q u a ls 3 0 0 c a lo r ie s . C r e a te a n
a p p lic a tio n th a t le ts th e u s e r e n te r th e n u m b e r o f c o o k ie s h e o r s h e a c tu a lly a te a n d
th e n r e p o r ts th e n u m b e r o f to ta l c a lo r ie s c o n s u m e d .
1 0 .
C a lo r ie C o u n te r
C r e a te a n a p p lic a tio n w ith a fo r m th a t r e s e m b le s F ig u r e 3 -4 8 . T h e P ic tu r e B o x c o n tr o ls d is p la y th e im a g e s o f fo u r fr u its (a b a n a n a , a n a p p le , a n o r a n g e , a n d a p e a r )
a n d e a c h f r u i t ’ s c a l o r i e s . Y o u c a n f i n d t h e s e i m a g e s i n t h e Chap03 f o l d e r o f t h e
S tu d e n t S a m p le P r o g r a m s .
W h e n th e a p p lic a tio n s ta r ts , th e to ta l c a lo r ie s d is p la y e d s h o u ld b e z e r o . E a c h tim e
th e u s e r c lic k s o n e o f th e P ic tu r e B o x e s , th e c a lo r ie s fo r th a t fr u it s h o u ld b e a d d e d to
th e to ta l c a lo r ie s , a n d th e to ta l c a lo r ie s s h o u ld b e d is p la y e d . W h e n th e u s e r c lic k s
t h e Reset b u t t o n , t h e t o t a l c a l o r i e s s h o u l d b e r e s e t t o z e r o .
F ig u r e 3 -4 8
Ca lorie Counter f o r m
1 1 .
A u to m o b ile C o s ts
C r e a te a n a p p lic a tio n th a t le ts th e u s e r e n te r th e m o n th ly c o s ts fo r th e fo llo w in g
e x p e n s e s in c u r r e d fr o m o p e r a tin g h is o r h e r a u to m o b ile : lo a n p a y m e n t, in s u r a n c e ,
g a s , o il, tir e s , a n d m a in te n a n c e . T h e p r o g r a m s h o u ld th e n d is p la y th e to ta l m o n th ly
co st o f th ese ex p en ses an d th e to tal an n u al co st o f th ese ex p en ses.
1 2 .
P a in t J o b E s tim a to r
A p a in tin g c o m p a n y h a s d e te r m in e d th a t fo r e v e r y 1 1 5 s q u a r e fe e t o f w a ll s p a c e ,
1 g a llo n o f p a in t a n d 8 h o u r s o f la b o r w ill b e r e q u ir e d . T h e c o m p a n y c h a r g e s $ 2 0 .0 0
p e r h o u r fo r la b o r . C r e a te a n a p p lic a tio n th a t a llo w s th e u s e r to e n te r th e s q u a r e fe e t
o f w a ll s p a c e to b e p a in te d a n d th e p r ic e o f th e p a in t p e r g a llo n . T h e p r o g r a m
s h o u ld d is p la y th e fo llo w in g d a ta :
•
•
•
•
•
T h e n u m b e r o f g a llo n s o f p a in t r e q u ir e d
T h e h o u r s o f la b o r r e q u ir e d
T h e c o s t o f th e p a in t
T h e la b o r c h a r g e s
T h e to ta l c o s t o f th e p a in t jo b
197
198
C h a p te r 3
P r o c e s s in g D a t a
1 3 .
P ro p erty Tax
If y o u o w n r e a l e s ta te in a p a r tic u la r c o u n ty , th e p r o p e r ty ta x th a t y o u o w e e a c h
y e a r is c a lc u la te d a s 6 4 c e n ts p e r $ 1 0 0 o f th e p r o p e r ty ’s v a lu e . F o r e x a m p le , if th e
p r o p e r ty ’s v a lu e is $ 1 0 ,0 0 0 , th e n th e p r o p e r ty ta x is c a lc u la te d a s fo llo w s :
Tax = $ 1 0 , 0 0 0 ÷ 1 0 0 × 0 . 6 4
C r e a te a n a p p lic a tio n th a t a llo w s th e u s e r to e n te r a p r o p e r ty ’s v a lu e a n d d is p la y s
th e s a le s ta x o n th a t p r o p e r ty .
1 4 .
S ta d iu m S e a tin g
T h e r e a r e th r e e s e a tin g c a te g o r ie s a t a n a th le tic s ta d iu m . F o r a b a s e b a ll g a m e ,
C la s s A s e a ts c o s t $ 1 5 e a c h , C la s s B s e a ts c o s t $ 1 2 e a c h , a n d C la s s C s e a ts c o s t $ 9
e a c h . C r e a te a n a p p lic a tio n th a t a llo w s th e u s e r to e n te r th e n u m b e r o f tic k e ts s o ld
fo r e a c h c la s s . T h e a p p lic a tio n s h o u ld b e a b le to d is p la y th e a m o u n t o f in c o m e
g e n e r a te d fr o m e a c h c la s s o f tic k e t s a le s a n d th e to ta l r e v e n u e g e n e r a te d . T h e
a p p lic a tio n ’s fo r m s h o u ld r e s e m b le th e o n e s h o w n in F ig u r e 3 -4 9 .
U s e th e fo llo w in g s e ts o f te s t d a ta to
in g p r o p e r ly :
F ig u r e 3 -4 9
d e te r m in e if th e a p p lic a tio n
Sta dium Sea ting f o r m
T ic k e t S a le s
C la s s A : 3 2 0
C la s s B : 5 7 0
C la s s C : 8 9 0
Reven u e
C la s s A : $ 4 ,8 0 0 .0 0
C la s s B : $ 6 ,8 4 0 .0 0
C la s s C : $ 8 ,0 1 0 .0 0
Total Revenue: $ 1 9 , 6 5 0 . 0 0
C la s s A : 5 0 0
C la s s B : 7 5 0
C la s s C : 1 ,2 0 0
C la s s A : $ 7 ,5 0 0 .0 0
C la s s B : $ 9 ,0 0 0 .0 0
C la s s C : $ 1 0 ,8 0 0 .0 0
Total Revenue: $ 2 7 , 3 0 0 . 0 0
C la s s A : 1 0 0
C la s s B : 3 0 0
C la s s C : 5 0 0
C la s s A : $ 1 ,5 0 0 .0 0
C la s s B : $ 3 ,6 0 0 .0 0
C la s s C : $ 4 ,5 0 0 .0 0
Total Revenue: $ 9 , 6 0 0 . 0 0
is c a lc u la t-
C H A P T E R
4
M a k in g D e c is io n s
T O P I C S
4 .1
4 .1
D e c i s i o n S t r u c t u r e s a n d t h e if
S ta te m e n t
4 .2
T h e if-else S t a t e m e n t
4 .3
4 .7
P r e v e n t in g D a t a C o n v e r s io n
E x c e p t i o n s w i t h t h e TryParse
M e th o d s
N e s t e d D e c is io n S t r u c t u r e s
4 .8
In p u t V a lid a t io n
4 .4
L o g ic a l O p e r a t o r s
4 .9
R a d io B u t t o n s a n d C h e c k B o x e s
4 .5
bool V a r i a b l e s a n d F l a g s
4 .1 0
T h e switch S t a t e m e n t
4 .6
C o m p a r in g S t r in g s
4 .1 1
In t r o d u c t io n t o L is t B o x e s
D e c i s i o n S t r u c t u r e s a n d t h e if S t a t e m e n t
C O N C E P T :
A d e c is io n s tr u c tu r e a llo w s a p r o g r a m to p e r fo r m a c tio n s o n ly u n d e r
c e r t a i n c o n d i t i o n s . I n c o d e , y o u c a n u s e t h e if s t a t e m e n t t o w r i t e a s i m p l e
d e c is io n s tr u c tu r e .
A c o n tr o l s tr u c tu r e is a lo g ic a l d e s ig n th a t c o n tr o ls th e o r d e r in w h ic h a s e t o f s ta te m e n ts
e x e c u te . S o fa r in th is b o o k , w e h a v e u s e d o n ly th e s im p le s t ty p e o f c o n tr o l s tr u c tu r e : th e
s e q u e n c e s tr u c tu r e . A s e q u e n c e s tr u c tu r e is a s e t o f s ta te m e n ts th a t e x e c u te in th e o r d e r
th a t th e y a p p e a r . F o r e x a m p le , th e fo llo w in g c o d e s a m p le is a s e q u e n c e s tr u c tu r e b e c a u s e
th e statemen ts ex ecu te fro m to p to b o tto m.
int ageInYears, ageInDays;
ageInYears = int.Parse(ageTextBox.Text);
ageInDays = ageInYears * 365;
daysLabel = ageInDays.ToString();
A lth o u g h th e s e q u e n c e s tr u c tu r e is h e a v ily u s e d in p r o g r a m m in g , it c a n n o t h a n d le e v e r y ty p e
o f ta s k . S o m e p r o b le m s s im p ly c a n n o t b e s o lv e d b y p e r fo r m in g a s e t o f o r d e r e d s te p s , o n e
a fte r th e o th e r . F o r e x a m p le , c o n s id e r a p a y -c a lc u la tin g p r o g r a m th a t d e te r m in e s w h e th e r a n
e m p lo y e e h a s w o r k e d o v e r tim e . If th e e m p lo y e e h a s w o r k e d m o r e th a n 4 0 h o u r s , h e o r s h e
g e ts p a id e x tr a fo r a ll h o u r s o v e r 4 0 . O th e r w is e , th e o v e r tim e c a lc u la tio n s h o u ld b e s k ip p e d .
P r o g r a m s lik e th is r e q u ir e a d iffe r e n t ty p e o f c o n tr o l s tr u c tu r e : o n e th a t c a n e x e c u te a s e t o f
s ta te m e n ts o n ly u n d e r c e r ta in c ir c u m s ta n c e s . T h is c a n b e a c c o m p lis h e d w ith a d e c is io n
s tr u c tu r e . (D e c is io n s tr u c tu r e s a r e a ls o k n o w n a s s e le c tio n s tr u c tu r e s .)
199
200
C h a p te r 4
M a k in g D e c is io n s
In a d e c is io n s tr u c tu r e ’s s im p le s t fo r m , a s p e c ific a c tio n is p e r fo r m e d o n ly if a c e r ta in c o n d itio n e x is ts . If th e c o n d itio n d o e s n o t e x is t, th e a c tio n is n o t p e r fo r m e d . T h e flo w c h a r t
s h o w n in F ig u r e 4 -1 s h o w s h o w th e lo g ic o f a n e v e r y d a y d e c is io n c a n b e d ia g r a m m e d a s a
d e c is io n s tr u c tu r e . T h e d ia m o n d s y m b o l r e p r e s e n ts a tr u e -fa ls e c o n d itio n . If th e c o n d itio n
is tr u e , w e fo llo w o n e p a th , w h ic h le a d s to a n a c tio n b e in g p e r fo r m e d . If th e c o n d itio n is
fa ls e , w e fo llo w a n o th e r p a th , w h ic h s k ip s th e a c tio n .
F ig u r e 4 -1
A s im p le d e c is io n s t r u c t u r e
Cold
outside
False
True
Wear a coat.
In th e flo w c h a r t, th e d ia m o n d s y m b o l in d ic a te s s o m e c o n d itio n th a t m u s t b e te s te d . In th is
c a s e , w e a r e d e t e r m i n i n g w h e t h e r t h e c o n d i t i o n Cold outside i s t r u e o r f a l s e . I f t h i s c o n d i t i o n i s t r u e , t h e a c t i o n Wear a coat i s p e r f o r m e d . I f t h e c o n d i t i o n i s f a l s e , t h e a c t i o n i s
s k ip p e d . T h e a c tio n is c o n d itio n a lly e x e c u te d b e c a u s e it is p e r fo r m e d o n ly w h e n a c e r ta in
c o n d itio n is tr u e .
P r o g r a m m e r s c a ll th e ty p e o f d e c is io n s tr u c tu r e s h o w n in F ig u r e 4 -1 a s in g le -a lte r n a tiv e
d e c is io n s tr u c tu r e b e c a u s e it p r o v id e s o n ly o n e a lte r n a tiv e p a th o f e x e c u tio n . If th e c o n d itio n in th e d ia m o n d s y m b o l is tr u e , w e ta k e th e a lte r n a tiv e p a th . O th e r w is e , w e e x it th e
s tr u c tu r e . F ig u r e 4 -2 s h o w s a m o r e e la b o r a te e x a m p le , w h e r e th r e e a c tio n s a r e ta k e n o n ly
w h e n it is c o ld o u ts id e .
F ig u r e 4 -2
A d e c is io n s t r u c t u r e t h a t p e r fo r m s t h r e e a c t io n s if it is c o ld o u t s id e
Cold
outside
False
True
Wear a coat.
Wear a hat.
Wear gloves.
4 .1
D e c i s i o n S t r u c t u r e s a n d t h e if S t a t e m e n t
I n C # , y o u u s e t h e if s t a t e m e n t t o w r i t e a s i n g l e - a l t e r n a t i v e d e c i s i o n s t r u c t u r e . H e r e i s t h e
g e n e r a l f o r m a t o f t h e if s t a t e m e n t :
if (expression)
{
statement;
statement;
etc.
}
T h e s t a t e m e n t b e g i n s w i t h t h e w o r d if, f o l l o w e d b y a n expression e n c l o s e d i n a s e t o f
p a r e n th e s e s . B e g in n in g o n th e n e x t lin e is a s e t o f s ta te m e n ts e n c lo s e d in c u r ly b r a c e s .
T h e expression t h a t a p p e a r s i n s i d e t h e p a r e n t h e s e s i s a B o o l e a n e x p r e s s i o n . A
B o o l e a n e x p r e s s i o n i s o n e t h a t c a n b e e v a l u a t e d a s e i t h e r t r u e o r f a l s e . W h e n t h e if
s ta te m e n t e x e c u te s , th e B o o le a n e x p r e s s io n is te s te d . If it is tr u e , th e s ta te m e n ts th a t
a p p e a r in s id e th e c u r ly b r a c e s a r e e x e c u te d . If th e B o o le a n e x p r e s s io n is fa ls e , h o w e v e r ,
th e s ta te m e n ts in s id e th e c u r ly b r a c e s a r e s k ip p e d . W e s a y th a t th e s ta te m e n ts in s id e
t h e c u r l y b r a c e s a r e conditionally executed b e c a u s e t h e y a r e e x e c u t e d o n l y i f t h e
B o o le a n e x p r e s s io n is tr u e .
I f y o u a r e w r i t i n g a n if s t a t e m e n t t h a t h a s o n l y o n e c o n d i t i o n a l l y e x e c u t e d s t a t e m e n t ,
y o u d o n o t h a v e to e n c lo s e th e c o n d itio n a lly e x e c u te d s ta te m e n t in s id e c u r ly b r a c e s . S u c h
a n if s t a t e m e n t c a n b e w r i t t e n i n t h e f o l l o w i n g g e n e r a l f o r m a t :
if (expression)
statement;
W h e n a n if s t a t e m e n t w r i t t e n i n t h i s f o r m a t e x e c u t e s , t h e B o o l e a n e x p r e s s i o n i s t e s t e d . I f
it is tr u e , th e o n e s ta te m e n t th a t a p p e a r s o n th e n e x t lin e is e x e c u te d . If th e B o o le a n
e x p r e s s io n is fa ls e , h o w e v e r , th a t o n e s ta te m e n t is s k ip p e d .
A lth o u g h th e c u r ly b r a c e s a r e n o t r e q u ir e d w h e n th e r e is o n ly o n e c o n d itio n a lly e x e c u te d
s ta te m e n t, it is s till a g o o d id e a to u s e th e m , a s s h o w n in th e fo llo w in g g e n e r a l fo r m a t:
if (expression)
{
statement;
}
T h i s i s a g o o d s t y l e f o r w r i t i n g if s t a t e m e n t s b e c a u s e i t m i n i m i z e s e r r o r s . R e m e m b e r , i f
y o u h a v e m o r e t h a n o n e c o n d i t i o n a l l y e x e c u t e d s t a t e m e n t , t h o s e s t a t e m e n t s must b e
e n c lo s e d in c u r ly b r a c e s . If y o u g e t in to th e h a b it o f a lw a y s e n c lo s in g th e c o n d itio n a lly
e x e c u te d s ta te m e n ts in a s e t o f c u r ly b r a c e s , it’s le s s lik e ly th a t y o u w ill fo r g e t th e m .
B o o le a n E x p r e s s io n s a n d R e la t io n a l O p e r a t o r s
B o o le a n e x p r e s s io n s a r e n a m e d in h o n o r o f th e E n g lis h m a th e m a tic ia n G e o r g e B o o le . In
th e 1 8 0 0 s , B o o le in v e n te d a s y s te m o f m a th e m a tic s in w h ic h th e a b s tr a c t c o n c e p ts o f tr u e
a n d fa ls e c a n b e u s e d in c o m p u ta tio n s .
T y p i c a l l y , t h e B o o l e a n e x p r e s s i o n t h a t i s t e s t e d b y a n if s t a t e m e n t i s f o r m e d w i t h a r e l a tio n a l o p e r a to r . A r e la tio n a l o p e r a to r d e te r m in e s w h e th e r a s p e c ific r e la tio n s h ip e x is ts
b e t w e e n t w o v a l u e s . F o r e x a m p l e , t h e g r e a t e r t h a n o p e r a t o r ( >) d e t e r m i n e s w h e t h e r o n e
v a l u e i s g r e a t e r t h a n a n o t h e r . T h e e q u a l t o o p e r a t o r ( ==) d e t e r m i n e s w h e t h e r t w o v a l u e s
a r e e q u a l. T a b le 4 -1 lis ts th e r e la tio n a l o p e r a to r s th a t a r e a v a ila b le in C # .
T h e f o l l o w i n g i s a n e x a m p l e o f a n e x p r e s s i o n t h a t u s e s t h e g r e a t e r t h a n ( >) o p e r a t o r t o
c o m p a r e t w o v a r i a b l e s , length a n d width:
length > width
201
202
C h a p te r 4
M a k in g D e c is io n s
T a b le 4 -1
Op erato r
R e la t io n a l o p e r a t o r s
M e a n in g
>
Greater th an
<
Less th an
>=
Greater th an o r eq u al to
<=
Less th an o r eq u al to
==
Eq u al to
!=
No t eq u al to
T h i s e x p r e s s i o n d e t e r m i n e s w h e t h e r t h e v a l u e o f t h e length v a r i a b l e i s g r e a t e r t h a n
t h e v a l u e o f t h e width v a r i a b l e . I f length i s g r e a t e r t h a n width , t h e v a l u e o f t h e
e x p r e s s io n is tr u e . O th e r w is e , th e v a lu e o f th e e x p r e s s io n is fa ls e . T h e fo llo w in g
e x p r e s s i o n u s e s t h e l e s s t h a n o p e r a t o r ( < ) t o d e t e r m i n e w h e t h e r length i s l e s s
t h a n width:
length < width
T a b le 4 -2 s h o w s e x a m p le s o f s e v e r a l B o o le a n e x p r e s s io n s th a t c o m p a r e th e v a r ia b le s x
a n d y.
T a b le 4 -2
B o o le a n e x p r e s s io n s u s in g r e la t io n a l o p e r a t o r s
E x p r e s s io n
M e a n in g
x > y
I s x g r e a t e r t h a n y?
x < y
I s x l e s s t h a n y?
x >= y
I s x g r e a t e r t h a n o r e q u a l t o y?
x <= y
I s x l e s s t h a n o r e q u a l t o y?
x == y
I s x e q u a l t o y?
x != y
I s x n o t e q u a l t o y?
T h e >= a n d
<= O p e r a t o r s
T w o o f t h e o p e r a t o r s , >= a n d <=, t e s t f o r m o r e t h a n o n e r e l a t i o n s h i p . T h e >= o p e r a t o r
d e t e r m i n e s w h e t h e r t h e o p e r a n d o n i t s l e f t i s g r e a t e r t h a n or e q u a l t o t h e o p e r a n d o n i t s
r i g h t . T h e <= o p e r a t o r d e t e r m i n e s w h e t h e r t h e o p e r a n d o n i t s l e f t i s l e s s t h a n or e q u a l t o
th e o p e r a n d o n its r ig h t.
F o r e x a m p le , a s s u m e th e v a r ia b le ais a s s ig n e d 4 . A ll th e fo llo w in g e x p r e s s io n s a r e tr u e :
a >= 4
a >= 2
8 >= a
a <= 4
a <= 9
4 <= a
T h e == O p e r a t o r
T h e == o p e r a t o r d e t e r m i n e s w h e t h e r t h e o p e r a n d o n i t s l e f t i s e q u a l t o t h e o p e r a n d o n i t s
r ig h t. If th e v a lu e s o f b o th o p e r a n d s a r e th e s a m e , th e e x p r e s s io n is tr u e . A s s u m in g th a t a
i s 4 , t h e e x p r e s s i o n a == 4 i s t r u e a n d t h e e x p r e s s i o n a == 2 i s f a l s e .
4 .1
D e c i s i o n S t r u c t u r e s a n d t h e if S t a t e m e n t
N O T E : T h e e q u a lity o p e r a to r is tw o =s y m b o ls to g e th e r . D o n ’t c o n fu s e th is o p e r a to r
w ith th e a s s ig n m e n t o p e r a to r , w h ic h is o n e =s y m b o l.
T h e != O p e r a t o r
T h e != o p e r a t o r i s t h e n o t e q u a l t o o p e r a t o r . I t d e t e r m i n e s w h e t h e r t h e o p e r a n d o n i t s l e f t
i s n o t e q u a l t o t h e o p e r a n d o n i t s r i g h t , w h i c h i s t h e o p p o s i t e o f t h e == o p e r a t o r . A s
b e f o r e , a s s u m i n g a i s 4 , b i s 6 , a n d c i s 4 , b o t h a != b a n d b != c a r e t r u e b e c a u s e a i s
n o t e q u a l t o b a n d b i s n o t e q u a l t o c; h o w e v e r , a != c i s f a l s e b e c a u s e a i s e q u a l t o c.
P u t t in g It A ll T o g e t h e r
L e t ’ s l o o k a t t h e f o l l o w i n g e x a m p l e o f t h e if s t a t e m e n t :
if (sales > 50000)
{
bonus = 500;
}
T h i s s t a t e m e n t u s e s t h e > o p e r a t o r t o d e t e r m i n e w h e t h e r sales i s g r e a t e r t h a n 5 0 , 0 0 0 . I f
t h e e x p r e s s i o n sales > 50000 i s t r u e , t h e v a r i a b l e bonus i s a s s i g n e d 5 0 0 . I f t h e e x p r e s s io n is fa ls e , h o w e v e r , th e a s s ig n m e n t s ta te m e n t is s k ip p e d . F ig u r e 4 -3 s h o w s a flo w c h a r t
fo r th is s e c tio n o f c o d e .
F ig u r e 4 -3
E x a m p le d e c is io n s t r u c t u r e
sales > 50000
True
bonus = 500
False
T h e fo llo w in g c o d e s a m p le c o n d itio n a lly e x e c u te s th r e e s ta te m e n ts . F ig u r e 4 -4 s h o w s a
flo w c h a r t fo r th is s e c tio n o f c o d e .
if (sales > 50000)
{
bonus = 500;
commissionRate = 0.12;
MessageBox.Show("You met your sales quota!");
}
W h e n y o u w r i t e a n if s t a t e m e n t , V i s u a l S t u d i o a u t o m a t i c a l l y i n d e n t s t h e c o n d i t i o n a l l y
e x e c u te d s ta te m e n ts , a s s h o w n in th e p r e v io u s e x a m p le s . T h e in d e n ta tio n is n o t r e q u ir e d ,
b u t it m a k e s th e c o d e e a s ie r to r e a d a n d d e b u g . B y in d e n tin g th e c o n d itio n a lly e x e c u te d
s ta te m e n ts , y o u v is u a lly s e t th e m a p a r t fr o m th e s u r r o u n d in g c o d e . T h is a llo w s y o u to te ll
a t a g l a n c e w h a t p a r t o f t h e p r o g r a m i s c o n t r o l l e d b y t h e if s t a t e m e n t . M o s t p r o g r a m m e r s u s e t h i s s t y l e o f i n d e n t a t i o n w h e n w r i t i n g if s t a t e m e n t s .
203
204
C h a p te r 4
M a k in g D e c is io n s
F ig u r e 4 -4
E x a m p le d e c is io n s t r u c t u r e
sales > 50000
True
bonus = 500
False
commissionRate = 0.12
Display message: “You
met your sales quota!”
T u t o r ia l 4 -1 :
C o m p l e t i n g t h e Test Score Avera ge A p p l i c a t i o n
VideoNot e
T u to r ia l 4 -1 :
C o m p le tin g
t h e Test
Score
Average
a p p lic a tio n
In th is tu to r ia l, y o u w ill c o m p le te a n a p p lic a tio n th a t a llo w s th e u s e r to e n te r th r e e te s t
s c o r e s a n d c a lc u la te s th e a v e r a g e o f th e te s t s c o r e s . If th e a v e r a g e is g r e a te r th a n 9 5 , th e
a p p lic a tio n a ls o d is p la y s a m e s s a g e c o n g r a tu la tin g th e u s e r .
T o s a v e tim e , th e p r o je c t h a s a lr e a d y b e e n s ta r te d fo r y o u , a n d th e a p p lic a tio n ’s fo r m h a s
a lr e a d y b e e n c r e a te d . T o c o m p le te th e p r o je c t, fo llo w th e s te p s in th is tu to r ia l.
S t e p 1 :
S t a r t V i s u a l S t u d i o . O p e n t h e p r o j e c t n a m e d Test Score Average i n t h e Chap04
fo ld e r o f th is b o o k ’s S tu d e n t S a m p le P r o g r a m s , a v a ila b le fo r d o w n lo a d a t w w w .
p e a r s o n h ig h e r e d .c o m /g a d d is .
S t e p 2 :
O p e n t h e F o r m 1 f o r m i n t h e D esigner. T h e f o r m i s s h o w n , a l o n g w i t h t h e n a m e s
o f th e im p o r ta n t c o n tr o ls , in F ig u r e 4 -5 .
F ig u r e 4 -5
T h e Test Score Avera ge f o r m
test1TextBox
test2TextBox
test3TextBox
averageLabel
clearButton
exitButton
calculateButton
4 .1
D e c i s i o n S t r u c t u r e s a n d t h e if S t a t e m e n t
S t e p 3 :
N o w , y o u w ill c r e a te th e C lic k e v e n t h a n d le r s fo r th e B u tto n c o n tr o ls . A t th e e n d
o f th is tu to r ia l, P r o g r a m 4 -1 s h o w s th e c o m p le te d c o d e fo r th e fo r m . Y o u w ill b e
in s tr u c te d to r e fe r to P r o g r a m 4 -1 a s y o u w r ite th e e v e n t h a n d le r s .
I n t h e D esigner, d o u b l e - c l i c k t h e calculateButton c o n t r o l . T h i s w i l l o p e n t h e
c o d e e d i t o r , a n d y o u s e e a n e m p t y e v e n t h a n d l e r n a m e d calculateButton_Click.
C o m p l e t e t h e calculateButton_Click e v e n t h a n d l e r b y t y p i n g t h e c o d e s h o w n i n
lin e s 2 2 – 4 9 in P r o g r a m 4 -1 .
L e t’s ta k e a c lo s e r lo o k a t th e c o d e :
L i n e 2 2 : T h i s i s t h e b e g i n n i n g o f a try-catch s t a t e m e n t . T h e t r y b l o c k a p p e a r s
in lin e s 2 4 – 4 3 , a n d th e c a tc h b lo c k a p p e a r s in lin e s 4 7 – 4 8 . T h e p u r p o s e o f th is
try-catch s t a t e m e n t i s t o g r a c e f u l l y r e s p o n d i f t h e u s e r e n t e r s i n v a l i d i n p u t f o r
a n y o f th e te s t s c o r e s . If a n y o f th e s ta te m e n ts in lin e s 2 8 , 2 9 , a n d 3 0 th r o w a n
e x c e p tio n , th e p r o g r a m d o e s n o t c r a s h . In s te a d , it ju m p s to th e c a tc h b lo c k , a n d
lin e 4 8 d is p la y s a n e r r o r m e s s a g e .
L i n e 2 4 : T h i s s t a t e m e n t d e c l a r e s a c o n s t a n t double n a m e d HIGH_SCORE, s e t t o
th e v a lu e 9 5 .0 . W e u s e th is c o n s ta n t to d e te r m in e w h e th e r th e a v e r a g e is h ig h .
If th e a v e r a g e is g r e a te r th a n th is c o n s ta n t, th e p r o g r a m d is p la y s a m e s s a g e
c o n g r a tu la tin g th e u s e r .
L i n e 2 5 : T h i s s t a t e m e n t d e c l a r e s t h e f o l l o w i n g double v a r i a b l e s : test1, test2,
test3, a n d average. T h e v a r i a b l e s h o l d t h e t h r e e t e s t s c o r e s a n d t h e a v e r a g e
test sco re.
L i n e 2 8 : T h i s s t a t e m e n t c o n v e r t s t h e test1TextBox c o n t r o l ’ s T e x t p r o p e r t y t o
a double a n d a s s i g n s t h e r e s u l t t o t h e test1 v a r i a b l e .
L i n e 2 9 : T h i s s t a t e m e n t c o n v e r t s t h e test2TextBox c o n t r o l ’ s T e x t p r o p e r t y t o
a double a n d a s s i g n s t h e r e s u l t t o t h e test2 v a r i a b l e .
L i n e 3 0 : T h i s s t a t e m e n t c o n v e r t s t h e test3TextBox c o n t r o l ’ s T e x t p r o p e r t y t o
a double a n d a s s i g n s t h e r e s u l t t o t h e test3 v a r i a b l e .
L i n e 3 3 : T h i s s t a t e m e n t c a l c u l a t e s t h e a v e r a g e o f t h e test1, test2, a n d test3
v a r i a b l e s a n d a s s i g n s t h e r e s u l t t o t h e average v a r i a b l e .
L i n e 3 6 : T h i s s t a t e m e n t c o n v e r t s t h e average v a r i a b l e t o a s t r i n g ( r o u n d e d t o 1 d e c i m a l p l a c e ) a n d a s s i g n s t h e r e s u l t t o t h e averageLabel c o n t r o l ’ s T e x t p r o p e r t y .
L i n e 4 0 : T h i s if s t a t e m e n t d e t e r m i n e s w h e t h e r average i s g r e a t e r t h a n HIGH_
SCORE. I f i t i s , t h e s t a t e m e n t i n l i n e 4 2 i s e x e c u t e d , d i s p l a y i n g a m e s s a g e b o x
w i t h a c o n g r a t u l a t o r y m e s s a g e . I f average i s n o t g r e a t e r t h a n HIGH_SCORE, t h e
s ta te m e n t in lin e 4 2 is s k ip p e d .
S t e p 4 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e clearButton
c o n tr o l. In th e c o d e e d ito r y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
clearButton_Click. C o m p l e t e t h e clearButton_Click e v e n t h a n d l e r b y
ty p in g th e c o d e s h o w n in lin e s 5 4 – 6 1 in P r o g r a m 4 -1 .
L i n e s 5 5 – 5 7 : E a c h o f t h e s e s t a t e m e n t s a s s i g n s a n e m p t y s t r i n g ( "") t o t h e T e x t
p r o p e r ty o f o n e o f th e T e x tB o x c o n tr o ls . W h e n th e s e s ta te m e n ts h a v e fin is h e d
e x e c u tin g , th e T e x tB o x c o n tr o ls a p p e a r e m p ty .
L i n e 5 8 : T h i s s t a t e m e n t a s s i g n s a n e m p t y s t r i n g ( "") t o t h e averageLabel c o n t r o l ’ s
T e x t p r o p e r ty . A fte r th e s ta te m e n t h a s e x e c u te d , th e la b e l a p p e a r s e m p ty .
L i n e 6 1 : T h i s s t a t e m e n t s e t s t h e f o c u s t o t h e test1TextBox c o n t r o l . T h i s m a k e s
it m o r e c o n v e n ie n t fo r th e u s e r to s ta r t e n te r in g a n e w s e t o f te s t s c o r e s .
S t e p 5 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e exitButton
c o n tr o l. In th e c o d e e d ito r y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
exitButton_Click . C o m p l e t e t h e exitButton_Click e v e n t h a n d l e r b y
ty p in g th e c o d e s h o w n in lin e s 6 6 – 6 7 in P r o g r a m 4 -1 .
205
206
C h a p te r 4
M a k in g D e c is io n s
S t e p 6 :
S a v e th e p r o je c t. T h e n , p r e s s
o n t h e k e y b o a r d o r c l i c k t h e Start D ebugging
b u tto n ( ) o n th e to o lb a r to c o m p ile a n d r u n th e a p p lic a tio n .
F i r s t , e n t e r t h e f o l l o w i n g t e s t s c o r e s i n t h e T e x t B o x e s : 80, 90, a n d 75. C l i c k t h e
Calculate Average b u t t o n a n d t h e a v e r a g e s h o u l d a p p e a r a s s h o w n i n F i g u r e 4 - 6 .
F ig u r e 4 -6
A v e r a g e d is p la y e d
N e x t , c l i c k t h e Clear b u t t o n t o c l e a r t h e T e x t B o x e s a n d t h e a v e r a g e . N o w , e n t e r
t h e f o l l o w i n g t e s t s c o r e s i n t h e T e x t B o x e s : 100, 97, a n d 99. C l i c k t h e Calculate
Average b u t t o n . T h i s t i m e , i n a d d i t i o n t o d i s p l a y i n g t h e a v e r a g e , t h e a p p l i c a t i o n
d is p la y s th e m e s s a g e b o x s h o w n in F ig u r e 4 -7 .
F ig u r e 4 -7
A v e r a g e a n d m e s s a g e d is p la y e d
C o n tin u e to te s t th e a p p lic a tio n a s y o u w is h . W h e n y o u a r e fin is h e d , c lic k th e
Exit b u t t o n , a n d t h e f o r m s h o u l d c l o s e .
P r o g r a m 4 -1
C o m p l e t e d F o r m 1 c o d e f o r t h e Test Score Avera ge a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
4 .1
D e c i s i o n S t r u c t u r e s a n d t h e if S t a t e m e n t
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Test_Score_Average
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void calculateButton_Click(object sender, EventArgs e)
21
{
22
try
23
{
24
const double HIGH_SCORE = 95.0;
// High Score value
25
double test1, test2, test3, average; // Variables
26
27
// Get the test scores from the TextBoxes.
28
test1 = double.Parse(test1TextBox.Text);
29
test2 = double.Parse(test2TextBox.Text);
30
test3 = double.Parse(test3TextBox.Text);
31
32
// Calculate the average test score.
33
average = (test1 + test2 + test3) / 3.0;
34
35
// Display the average, rounded to 2 decimal places.
36
averageLabel.Text = average.ToString("n1");
37
38
// If the average is a high score, congratulate
39
// the user with a message box.
40
if (average > HIGH_SCORE)
41
{
42
MessageBox.Show("Congratulations! Great job!");
43
}
44
}
45
catch (Exception ex)
46
{
47
// Display the default error message.
48
MessageBox.Show(ex.Message);
49
}
50
}
51
52
private void clearButton_Click(object sender, EventArgs e)
53
{
54
// Clear the TextBoxes and the averageLabel control.
55
test1TextBox.Text = "";
56
test2TextBox.Text = "";
57
test3TextBox.Text = "";
58
averageLabel.Text = "";
59
60
// Reset the focus to test1.
61
test1TextBox.Focus();
62
}
63
64
private void exitButton_Click(object sender, EventArgs e)
207
208
C h a p te r 4
M a k in g D e c is io n s
65
66
67
68
69
70 }
{
// Close the form.
this.Close();
}
}
C h e c k p o in t
4 .2
4 .1
W h a t is a c o n tr o l s tr u c tu r e ?
4 .2
W h a t is a d e c is io n s tr u c tu r e ?
4 .3
W h a t is a s in g le -a lte r n a tiv e d e c is io n s tr u c tu r e ?
4 .4
W h a t is a B o o le a n e x p r e s s io n ?
4 .5
W h a t ty p e s o f r e la tio n s h ip s b e tw e e n
r e la tio n a l o p e r a to r s ?
4 .6
W r i t e a n if s t a t e m e n t t h a t d e t e r m i n e s w h e t h e r t h e v a r i a b l e y i s e q u a l t o 2 0 . I f i t i s ,
a s s i g n 0 t o t h e v a r i a b l e x.
4 .7
W r i t e a n if s t a t e m e n t t h a t d e t e r m i n e s w h e t h e r t h e v a r i a b l e sales i s g r e a t e r t h a n
o r e q u a l t o 1 0 , 0 0 0 . I f i t i s , a s s i g n 0 . 2 t o t h e v a r i a b l e commissionRate.
n u m e r ic v a lu e s c a n
y o u
te s t w ith
T h e if-else S t a t e m e n t
C O N C E P T :
A n if-else s t a t e m e n t w i l l e x e c u t e o n e b l o c k o f s t a t e m e n t s i f i t s B o o l e a n
e x p r e s s io n is tr u e o r a n o th e r b lo c k if its B o o le a n e x p r e s s io n is fa ls e .
T h e p r e v i o u s s e c t i o n i n t r o d u c e d t h e s i n g l e - a l t e r n a t i v e d e c i s i o n s t r u c t u r e ( t h e if s t a t e m e n t ) ,
w h ic h h a s o n e a lte r n a tiv e p a th o f e x e c u tio n . N o w , w e w ill lo o k a t th e d u a l-a lte r n a tiv e
d e c is io n s tr u c tu r e , w h ic h h a s tw o p o s s ib le p a th s o f e x e c u tio n — o n e p a th is ta k e n if th e
B o o le a n e x p r e s s io n is tr u e , a n d th e o th e r p a th is ta k e n if th e B o o le a n e x p r e s s io n is fa ls e .
F ig u r e 4 -8 s h o w s a n e x a m p le flo w c h a r t fo r a d u a l-a lte r n a tiv e d e c is io n s tr u c tu r e .
F ig u r e 4 -8
A d u a l- a lt e r n a t iv e d e c is io n s t r u c t u r e
False
Display "Nice weather
we're having."
temperature
< 40
True
Display "A little cold,
isn't it?"
4 .2
T h e if-else S t a t e m e n t
T h e d e c i s i o n s t r u c t u r e i n t h e f l o w c h a r t t e s t s t h e e x p r e s s i o n temperature < 40. I f t h i s
e x p r e s s io n is tr u e , th e m e s s a g e “ A little c o ld , is n ’t it? ” is d is p la y e d . If th e e x p r e s s io n is
fa ls e , th e m e s s a g e “ N ic e w e a th e r w e ’r e h a v in g .” is d is p la y e d .
I n c o d e , w e w r i t e a d u a l - a l t e r n a t i v e d e c i s i o n s t r u c t u r e a s a n if-else s t a t e m e n t . H e r e i s
t h e g e n e r a l f o r m a t o f t h e if-else s t a t e m e n t :
if (expression)
{
statement;
statement;
etc.
}
else
{
statement;
statement;
etc.
}
If the Boolean expression is true,
this set of statements is executed.
If the Boolean expression is false,
this set of statements is executed.
A n if-else s t a t e m e n t h a s t w o p a r t s : a n if c l a u s e a n d a n else c l a u s e . J u s t l i k e a
r e g u l a r if s t a t e m e n t , t h e if-else s t a t e m e n t t e s t s a B o o l e a n e x p r e s s i o n . I f t h e
B o o l e a n e x p r e s s i o n i s t r u e , t h e s e t o f s t a t e m e n t s f o l l o w i n g t h e if c l a u s e i s e x e c u t e d .
I f t h e B o o l e a n e x p r e s s i o n i s f a l s e , t h e s e t o f s t a t e m e n t s f o l l o w i n g t h e else c l a u s e
is e x e c u te d .
T h e if-else s t a t e m e n t h a s t w o s e t s o f c o n d i t i o n a l l y e x e c u t e d s t a t e m e n t s . O n e s e t i s
e x e c u te d o n ly u n d e r th e c o n d itio n th a t th e B o o le a n e x p r e s s io n is tr u e , a n d th e o th e r s e t is
e x e c u te d o n ly u n d e r th e c o n d itio n th a t th e B o o le a n e x p r e s s io n is fa ls e . U n d e r n o c ir c u m s ta n c e s a r e b o th s e ts o f c o n d itio n a lly e x e c u te d s ta te m e n ts e x e c u te d .
If e ith e r s e t o f c o n d itio n a lly e x e c u te d s ta te m e n ts c o n ta in s o n ly o n e s ta te m e n t, th e c u r ly
b r a c e s a r e n o t r e q u ir e d . F o r e x a m p le , th e fo llo w in g g e n e r a l fo r m a t s h o w s o n ly o n e s ta te m e n t f o l l o w i n g t h e if c l a u s e a n d o n l y o n e s t a t e m e n t f o l l o w i n g t h e else c l a u s e :
if (expression)
statement;
else
statement;
A lth o u g h th e c u r ly b r a c e s a r e n o t r e q u ir e d w h e n th e r e is o n ly o n e c o n d itio n a lly
e x e c u te d s ta te m e n t, it is s till a g o o d id e a to u s e th e m , a s s h o w n in th e fo llo w in g
g e n e r a l fo r m a t:
if (expression)
{
statement;
}
else
{
statement;
}
W h e n w e d i s c u s s e d t h e r e g u l a r if s t a t e m e n t , w e m e n t i o n e d t h a t t h i s i s a g o o d s t y l e o f
p r o g r a m m in g b e c a u s e it c u ts d o w n o n e r r o r s . If th e r e is m o r e th a n o n e c o n d itio n a lly
e x e c u t e d s t a t e m e n t f o l l o w i n g e i t h e r t h e if c l a u s e o r t h e else c l a u s e , t h o s e s t a t e m e n t s
must b e e n c l o s e d i n c u r l y b r a c e s . I f y o u g e t i n t o t h e h a b i t o f a l w a y s e n c l o s i n g t h e
c o n d itio n a lly e x e c u te d s ta te m e n ts in a s e t o f c u r ly b r a c e s , it’s le s s lik e ly th a t y o u w ill
fo rget th em.
I n T u t o r i a l 4 - 2 , y o u w i l l c o m p l e t e a n a p p l i c a t i o n t h a t u s e s a n if-else s t a t e m e n t .
209
210
C h a p te r 4
M a k in g D e c is io n s
T u t o r ia l 4 -2 :
C o m p l e t i n g t h e Pa yroll with Overtime A p p l i c a t i o n
VideoNot e
T u to r ia l 4 -2 :
Completing
the Payroll
with
O vertime
application
A t a p a r tic u la r b u s in e s s , if a n e m p lo y e e w o r k s m o r e th a n 4 0 h o u r s in a w e e k , it is s a id
t h a t t h e e m p l o y e e h a s w o r k e d overtime. F o r e x a m p l e , a n e m p l o y e e t h a t h a s w o r k e d 4 5
h o u r s in a w e e k h a s w o r k e d 5 o v e r tim e h o u r s . E m p lo y e e s th a t w o r k o v e r tim e g e t p a id
th e ir r e g u la r h o u r ly p a y r a te fo r th e fir s t 4 0 h o u r s p lu s 1 .5 tim e s th e ir r e g u la r h o u r ly p a y
r a te fo r a ll h o u r s o v e r 4 0 . In th is tu to r ia l, y o u w ill c o m p le te a p a y r o ll a p p lic a tio n th a t
c a lc u la te s a n e m p lo y e e ’s g r o s s p a y , in c lu d in g o v e r tim e p a y .
T h e a p p lic a tio n a llo w s th e u s e r to e n te r th e n u m b e r o f h o u r s w o r k e d a n d th e h o u r ly p a y
r a te in to T e x tB o x e s . W h e n th e u s e r c lic k s a b u tto n , th e g r o s s p a y is c a lc u la te d in th e
fo llo w in g m a n n e r :
If th e h o u r s w o r k e d is g r e a te r th a n 4 0 :
b a s e p a y = h o u r ly p a y r a te × 4 0
overtime hours = hours worked − 40
overtime pay = overtime hours × hourly pay rate × 1.5
gross pay = base pay + overtime pay
Else:
gross pay = hours worked × hourly pay rate
To save time, the project has already been started for you, and the application’s form has
already been created. To complete the project, follow the steps in this tutorial.
S t e p 1 :
Start Visual Studio. Open the project named Payroll with O vertime in the
Chap04 folder of this book’s Student Sample Programs.
S t e p 2 :
Open the Form1 form in the D esigner. The form is shown, along with the names
of the important controls, in Figure 4-9.
F ig u r e 4 -9
T h e Pa yroll with Overtime f o r m
hoursWorkedTextBox
hourlyPayRateTextBox
grossPayLabel
calculateButton
S t e p 3 :
clearButton
exitButton
N ow, you will create the Click event handlers for the Button controls. At the end
of this tutorial, Program 4-2 shows the completed code for the form. You will be
instructed to refer to Program 4-2 as you write the event handlers.
In the D esigner, double-click the calculateButton control. This opens the
code editor, and you see an empty event handler named calculateButton_
Click. Complete the calculateButton_Click event handler by typing the
code shown in lines 22– 69 in Program 4-2.
4 .2
T h e if-else S t a t e m e n t
Let’s take a closer look at the code:
L i n e 2 2 : This is the beginning of a try-catch statement. The try block appears
in lines 24–63, and the catch block appears in lines 67–68. The purpose of this
try-catch statement is to gracefully respond if the user enters invalid input. If
an exception is thrown by any statement inside the try block, the program jumps
to the catch block, and line 68 displays an error message.
L i n e s 2 5 – 2 6 : These statements declare the following named constants:
• BASE_HOURS, a constant decimal set to the value 40. This is the number of
hours an employee can work in a week without getting overtime pay.
• OT_MULTIPLIER, a constant decimal set to the value 1.5. This is the pay rate
multiplier for overtime hours.
L i n e s 2 9 – 3 4 : These statements declare the following variables:
•
•
•
•
•
•
hoursWorked, a decimal variable to hold the number of hours worked
hourlyPayRate, a decimal variable to hold the hourly pay rate
basePay, a decimal variable to hold the pay for 40 or less hours
overtimeHours, a decimal variable to hold the number of overtime hours worked
overtimePay, a decimal variable to hold the amount of overtime pay
grossPay, a decimal variable to hold the gross pay
L i n e 3 7 : This statement converts the hoursWorkedTextBox control’s Text
property to a decimal and assigns the result to the hoursWorked variable.
L i n e 3 8 : This statement converts the hourlyPayRateTextBox control’s Text
property to a decimal and assigns the result to the hourlyPayRate variable.
L i n e 4 1 : This if statement determines whether hoursWorked is greater than
BASE_HOURS (40). If so, the statements in lines 43–54 are executed. Otherwise,
the statements in lines 58–59 are executed.
L i n e s 4 3 – 5 4 : These statements, which are executed only if the hours worked
are greater than 40, make all the necessary calculations to determine gross pay
with overtime:
• Line 44 calculates the base pay, which is the amount of pay for the first 40
hours.
• Line 47 calculates the number of overtime hours, which is the number of
hours over 40.
• Lines 50 and 51 calculate the amount of overtime pay, which is the pay for
the hours over 40.
• Line 54 calculates the gross pay, which is the amount of base pay plus the
amount of overtime pay. The result is assigned to the grossPay variable.
L i n e 5 9 : This statement, which is executed only if the hours worked are 40 or
less, calculates the gross pay and assigns the result to the grossPay variable.
L i n e 6 3 : This statement converts the value of the grossPay variable to a string,
formatted as currency, and assigns the result to the grossPayLabel control’s
Text property.
S t e p 4 :
Switch your view back to the D esigner and double-click the clearButton
control.
In the code editor you see an empty event handler named clearButton_Click.
Complete the clearButton_Click event handler by typing the code shown
in lines 74–80 in Program 4-2. These statements clear the TextBoxes and
the grossPayLabel control and sets the focus to the hoursWorkedTextBox
control.
211
212
C h a p te r 4
M a k in g D e c is io n s
S t e p 5 :
Switch your view back to the D esigner and double-click the exitButton control.
In the code editor you see an empty event handler named exitButton_Click.
Complete the exitButton_Click event handler by typing the code shown in
lines 85–86 in Program 4-2.
S t e p 6 :
Save the project and run the application. First, enter 40 for the number of hours
worked and 20 for the hourly pay rate. Click the Calculate Gross Pay button,
and the application should display $800.00 as the gross pay. N o overtime hours
were worked, so the gross pay is simply calculated as hours worked × hourly
pay rate.
Click the Clear button. Enter 50 for the number of hours worked and 20 for the
hourly pay rate. Click the Calculate Gross Pay button, and the application should
display $1,100.00 as the gross pay. This time, more than 40 hours were worked,
so the application calculated the gross pay to include overtime pay.
Continue to test the application as you wish. When you are finished, click the
Exit button, and the form should close.
P r o g r a m 4 -2
C o m p l e t e d F o r m 1 c o d e f o r t h e Pa yroll with Overtime a pplica tion
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Payroll_with_Overtime
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void calculateButton_Click(object sender, EventArgs e)
21
{
22
try
23
{
24
// Named constants
25
const decimal BASE_HOURS = 40m;
26
const decimal OT_MULTIPLIER = 1.5m;
27
28
// Local variables
29
decimal hoursWorked;
// Number of hours worked
30
decimal hourlyPayRate; // Hourly pay rate
31
decimal basePay;
// Pay not including overtime
32
decimal overtimeHours; // overtime hours worked
33
decimal overtimePay;
// overtime pay
34
decimal grossPay;
// total gross pay
35
36
// Get the hours worked and hourly pay rate.
37
hoursWorked = decimal.Parse(hoursWorkedTextBox.Text);
38
hourlyPayRate = decimal.Parse(hourlyPayRateTextBox.Text);
4 .2
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89 }
T h e if-else S t a t e m e n t
// Determine the gross pay.
if (hoursWorked > BASE_HOURS)
{
// Calculate the base pay (without overtime).
basePay = hourlyPayRate * BASE_HOURS;
// Calculate the number of overtime hours.
overtimeHours = hoursWorked - BASE_HOURS;
// Calculate the overtime pay.
overtimePay = overtimeHours * hourlyPayRate *
OT_MULTIPLIER;
// Calculate the gross pay.
grossPay = basePay + overtimePay;
}
else
{
// Calculate the gross pay.
grossPay = hoursWorked * hourlyPayRate;
}
// Display the gross pay.
grossPayLabel.Text = grossPay.ToString("c");
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
}
}
private void clearButton_Click(object sender, EventArgs e)
{
// Clear the TextBoxes and gross pay label.
hoursWorkedTextBox.Text = "";
hourlyPayRateTextBox.Text = "";
grossPayLabel.Text = "";
// Reset the focus.
hoursWorkedTextBox.Focus();
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
C h e c k p o in t
4.8 Describe how a dual alternative decision structure works.
4.9 In an if-else statement, under what circumstances do the statements that appear
after the else clause execute?
213
214
C h a p te r 4
M a k in g D e c is io n s
4.10 Write an if-else statement that works like this: If the sales variable is greaterthan or equal-to 50,000, the commissionRate variable should be assigned the value
0.2. Otherwise, the commissionRate variable should be assigned the value 0.1.
4 .3
N e s t e d D e c is io n S t r u c t u r e s
C O N C E P T :
T o te s t m o r e th a n o n e c o n d itio n , a d e c is io n s tr u c tu r e c a n b e n e s te d in s id e
a n o th e r d e c is io n s tr u c tu r e .
In Section 4.1, we mentioned that a control structure determines the order in which a set
of statements execute. Programs are usually designed as combinations of different control
structures. For example, Figure 4-10 shows a flowchart that combines a decision structure
with two sequence structures.
F ig u r e 4 -1 0
C o m b in in g s e q u e n c e s t r u c t u r e s w it h a d e c is io n s t r u c t u r e
Start
Go to the window.
Sequence structure
Read thermometer.
Cold
outside
True
Decision structure
Wear a coat.
False
Open the door.
Sequence structure
Go outside.
End
4 .3
N e s t e d D e c is io n S t r u c t u r e s
The flowchart in Figure 4-10 starts with a sequence structure. Assuming you have an
outdoor thermometer in your window, the first step is Go to the window, and the
next step is Read thermometer. A decision structure appears next, testing the condition Cold outside. If this is true, the action Wear a coat is performed. Another
sequence structure appears next. The step O pen the door is performed, followed by
Go outside.
Quite often, structures must be nested inside other structures. For example, look at the
partial flowchart in Figure 4-11. It shows a decision structure with a sequence structure
nested inside. The decision structure tests the condition Cold outside. If that condition is
true, the steps in the sequence structure are executed.
F ig u r e 4 -1 1
A s e q u e n c e s t r u c t u r e n e s t e d in s id e a d e c is io n s t r u c t u r e
Cold
outside
True
Wear a coat.
Decision
structure
False
Wear a hat.
Sequence
structure
Wear gloves.
You can also have n e s t e d d e c i s i o n s t r u c t u r e s , which are decision structures that
appear inside other decision structures. This is commonly done in programs that
need to test more than one condition. For example, consider a program that determines whether a bank customer qualifies for a loan. To qualify, two conditions
must exist: (1) The customer must earn at least $40,000 per year, and (2) the customer must have been employed at his or her current job for at least 2 years. Figure 4-12
shows a flowchart for an algorithm that could be used in such a program. Assume
that the salary variable contains the customer’s annual salary, and the yearsOnJob
variable contains the number of years that the customer has worked on his or her
current job.
If we follow the flow of execution, we see that the Boolean expression salary >=
40000 is tested. If this expression is false, there is no need to perform further tests;
we know that the customer does not qualify for the loan. If the expression is true,
however, we need to test the second condition. This is done with a nested decision
structure that tests the Boolean expression yearsOnJob >= 2. If this expression is
true, then the customer qualifies for the loan. If this expression is false, then the
customer does not qualify. In Tutorial 4-3, you create an application that performs
this algorithm.
215
216
C h a p te r 4
M a k in g D e c is io n s
F ig u r e 4 -1 2
A n e s t e d d e c is io n s t r u c t u r e
False
True
salary >= 40000
Display "Minimum salary
requirement not met."
False
yearsOnJob >= 2
Display "Minimum years
at current job not met."
True
Display "You qualify for
the loan."
End
T u t o r ia l 4 -3 :
C o m p l e t i n g t h e Loa n Qua lifier A p p l i c a t i o n
VideoNot e
T u to r ia l 4 -3 :
Completing
the L oan
Q ualifier
application
In this tutorial, you complete an application that determines whether a person qualifies
for a loan. To qualify for the loan, the person must earn a salary of at least $40,000 and
must have been employed at his or her current job for at least 2 years.
To save time, the project has already been started for you, and the application’s form has
already been created. To complete the project, follow the steps in this tutorial.
S t e p 1 :
Start Visual Studio. Open the project named L oan Q ualifier in the Chap04
folder of this book’s Student Sample Programs.
S t e p 2 :
Open the Form1 form in the D esigner. The form is shown, along with the names
of the important controls, in Figure 4-13.
S t e p 3 :
N ow, you will create the Click event handlers for the Button controls. At the
end of this tutorial, Program 4-3 shows the completed code for the form. You
will be instructed to refer to Program 4-3 as you write the event handlers.
4 .3
F ig u r e 4 -1 3
N e s t e d D e c is io n S t r u c t u r e s
T h e Loa n Qua lifier f o r m
salaryTextBox
yearsTextBox
decisionLabel
checkButton
clearButton
exitButton
In the D esigner, double-click the checkButton control. This opens the code
editor, and you see an empty event handler named checkButton_Click .
Complete the checkButton_Click event handler by typing the code shown in
lines 22–62 in Program 4-3. Let’s take a closer look at the code:
L i n e 2 2 : This is the beginning of a try-catch statement. The try block appears
in lines 24–56, and the catch block appears in lines 60–61. The purpose of this
try-catch statement is to gracefully respond if the user enters invalid input. If
an exception is thrown by any statement inside the try block, the program jumps
to the catch block, and line 61 displays an error message.
L i n e s 2 5 – 2 6 : These statements declare the following named constants:
• MINIMUM_SALARY, a constant decimal set to the value 40,000, which is the
minimum salary a person must earn to qualify for the loan
• MINIMUM_YEARS_ON_JOB, a constant int set to the value 2, which is the
minimum number of years a person must have been at his or her current job
to qualify for the loan
L i n e s 2 9 – 3 0 : These statements declare the following variables:
• salary, a decimal variable to hold the salary
• yearsOnJob, an int variable to hold the number of years at the current job
L i n e s 3 3 – 3 4 : These statements get the salary and years at the current job from the
TextBox controls and assign those values to the salary and yearsOnJob variables.
L i n e 3 7 : This if statement determines whether salary is greater than or
equal to MINIMUM_SALARY. If so, the program continues at line 39. Otherwise,
the program jumps to the else clause in line 51, and in lines 54–55 the string
“ M inimum salary requirement not met.” is assigned to the decisionLabel
control’s Text property.
L i n e 3 9 : This if statement determines whether yearsOnJob is greater than or
equal to MINIMUM_YEARS_ON_JOB. If so, the program continues at line 42, where
the string “ You qualify for the loan.” is assigned to the decisionLabel control’s
Text property. Otherwise, the program jumps to the else clause in line 44, and in
lines 47–48 the string “ M inimum years at current job not met.” is assigned to the
decisionLabel control’s Text property.
S t e p 4 :
Switch your view back to the D esigner and double-click the clearButton control.
In the code editor you see an empty event handler named clearButton_Click.
Complete the clearButton_Click event handler by typing the code shown in
lines 67–73 in Program 4-3.
217
218
C h a p te r 4
M a k in g D e c is io n s
S t e p 5 :
Switch your view back to the D esigner and double-click the exitButton control. In the code editor you see an empty event handler named exitButton_Click.
Complete the exitButton_Click event handler by typing the code shown in lines
78–79 in Program 4-3.
S t e p 6 :
Save the project and run the application. First, enter 45000 for the salary
and 1 for the years at current job. Click the Check Q ualifications button,
and the application should display the message “ M inimum years at current
job not met.”
Click the Clear button. Enter 35000 for the salary and 5 for the years at current
job. Click the Check Q ualifications button, and the application should display
the message “ M inimum salary requirement not met.”
Click the Clear button. Enter 45000 for the salary and 5 for the years at current
job. Click the Check Q ualifications button, and the application should display
the message “ You qualify for the loan.”
Continue to test the application as you wish. When you are finished, click the
Exit button, and the form should close.
P r o g r a m 4 -3
C o m p l e t e d F o r m 1 c o d e f o r t h e Loa n Qua lifier a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Loan_Qualifier
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void checkButton_Click(object sender, EventArgs e)
21
{
22
try
23
{
24
// Names constants
25
const decimal MINIMUM_SALARY = 40000m;
26
const int MINIMUM_YEARS_ON_JOB = 2;
27
28
// Local variables
29
decimal salary;
30
int yearsOnJob;
31
// Get the salary and years on the job.
32
33
salary = decimal.Parse(salaryTextBox.Text);
34
yearsOnJob = int.Parse(yearsTextBox.Text);
35
4 .3
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82 }
N e s t e d D e c is io n S t r u c t u r e s
// Determine whether the user qualifies.
if (salary >= MINIMUM_SALARY)
{
if (yearsOnJob >= MINIMUM_YEARS_ON_JOB)
{
// The user qualifies.
decisionLabel.Text = "You qualify for the loan.";
}
else
{
// The user does not qualify.
decisionLabel.Text = "Minimum years at current " +
"job not met.";
}
}
else
{
// The user does not qualify.
decisionLabel.Text = "Minimum salary requirement " +
"not met.";
}
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
}
}
private void clearButton_Click(object sender, EventArgs e)
{
// Clear the TextBoxes and the decisionLabel.
salaryTextBox.Text = "";
yearsTextBox.Text = "";
decisionLabel.Text = "";
// Reset the focus.
salaryTextBox.Focus();
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
In d e n t a t io n a n d A lig n m e n t in N e s t e d
D e c is io n S t r u c t u r e s
For debugging purposes, it’s important to use proper alignment and indentation in a
nested if statement. This makes it easier to see which actions are performed by each part
of the structure. For example, the following code is functionally equivalent to lines 37–56
in Program 4-3. Although this code is logically correct, it would be very difficult to debug
because it is not properly indented.
219
220
C h a p te r 4
M a k in g D e c is io n s
if (salary >= MINIMUM_SALARY)
{
if (yearsOnJob >= MINIMUM_YEARS_ON_JOB)
{
// The user qualifies.
decisionLabel.Text = "You qualify for the loan.";
}
else
{
// The user does not qualify.
decisionLabel.Text = "Minimum years at current " +
"job not met.";
}
}
else
{
// The user does not qualify.
decisionLabel.Text = "Minimum salary requirement " +
"not met.";
}
Fortunately, Visual Studio automatically indents and aligns the statements in a decision
structure. Proper indentation and alignment make it easier to see which if and else
clauses belong together, as shown in Figure 4-14.
F ig u r e 4 -1 4
This if
and else
go together.
A l i g n m e n t o f if a n d else c l a u s e s
if (salary >= MINIMUM_SALARY)
{
if (yearsOnJob >= MINIMUM_YEARS_ON_JOB)
{
This if
// The user qualifies.
and else
decisionLabel.Text = "You qualify for the loan.";
go together.
}
else
{
// The user does not qualify.
decisionLabel.Text = "Minimum years at current " +
"job not met.";
}
}
else
{
// The user does not qualify.
decisionLabel.Text = "Minimum salary requirement " +
"not met.";
}
T e s t in g a S e r ie s o f C o n d it io n s
In Tutorial 4-3, you saw how a program can use nested decision structures to test more
than one Boolean expression. It is not uncommon for a program to have a series of
Boolean expressions to test and then perform an action, depending on which expression is
true. One way to accomplish this it to have a decision structure with numerous other decision structures nested inside it. For example, look at the Grader application in the Chap04
folder of this book’s Student Sample Programs.
Figure 4-15 shows the application’s form, with the names of several controls. When
you run the application, you enter a numeric test score into the testScoreTexBox
control and click the determineGradeButton control; a grade is then displayed in the
gradeLabel control.
4 .3
F ig u r e 4 -1 5
N e s t e d D e c is io n S t r u c t u r e s
T h e Gra der a p p l i c a t i o n ’ s f o r m
testScoreTextBox
gradeLabel
determineGradeButton
exitButton
The following 10-point grading scale is used to determine the grade:
Test Sco re
90 and above
80–89
70–79
60–69
Below 60
Grad e
A
B
C
D
F
The logic of determining the grade can be expressed like this:
If the test score is less than 60, then the grade is “ F.”
Otherwise, if the test score is less than 70, then the grade is “ D.”
Otherwise, if the test score is less than 80, then the grade is “ C.”
Otherwise, if the test score is less than 90, then the grade is “ B.”
Otherwise, the grade is “ A.”
This logic requires several nested decision structures, as shown in the flowchart in Figure 4-16.
F ig u r e 4 -1 6
N e s t e d d e c is io n s t r u c t u r e t o d e t e r m in e a g r a d e
False
False
False
False
Display "Your
grade is A."
score
< 90
score
< 80
True
Display "Your
grade is B."
score
< 70
True
Display "Your
grade is C."
score
< 60
True
Display "Your
grade is D."
True
Display "Your
grade is F."
221
222
C h a p te r 4
M a k in g D e c is io n s
Open the code editor and look at the determineGradeButton_Click event handler, shown in the following code sample. The nested decision structure appears in
lines 12–41.
1 private void determineGradeButton_Click(object sender, EventArgs e)
2 {
3
try
4
{
5
// Variable to hold the test score.
6
double testScore;
7
8
// Get the test score.
9
testScore = double.Parse(testScoreTextBox.Text);
10
11
// Determine the grade.
12
if (testScore < 60)
13
{
14
gradeLabel.Text = "F";
15
}
16
else
17
{
18
if (testScore < 70)
19
{
20
gradeLabel.Text = "D";
21
}
22
else
23
{
24
if (testScore < 80)
25
{
26
gradeLabel.Text = "C";
27
}
28
else
29
{
30
if (testScore < 90)
31
{
32
gradeLabel.Text = "B";
33
}
34
else
35
{
36
gradeLabel.Text = "A";
37
}
38
}
39
}
40
}
41
}
42
catch (Exception ex)
43
{
44
// Display an error message.
45
MessageBox.Show(ex.Message);
46
}
47 }
T h e if-else-if S t a t e m e n t
Even though the Grader application previously shown is a simple example, the logic
of the nested decision structure is fairly complex. C# provides a special version of
the decision structure known as the i f - e l s e - i f s t a t e m e n t , which makes this type of
logic simpler to write. You write the if-else-if statement using the following
general format:
4 .3
N e s t e d D e c is io n S t r u c t u r e s
if (BooleanExpression_1)
{
statement;
If BooleanExpression_1 is true, this
statement;
set of statements is executed.
etc.
}
else if (BooleanExpression_2)
{
statement;
If BooleanExpression_2 is true, this
statement;
set of statements is executed.
etc.
}
Insert as many else if clauses as necessary…
else
{
statement;
statement;
etc.
}
This set of statements is executed if
none of the Boolean expressions
are true.
When the statement executes, BooleanExpression_1 is tested. If BooleanExpression_1 is
true, the set of statements that immediately follows is executed, and the rest of the structure is skipped. If BooleanExpression_1 is false, however, the program jumps to the very
next else if clause and tests BooleanExpression_2. If it is true, the set of statements that
immediately follows is executed, and the rest of the structure is then skipped. This process
continues until a Boolean expression is found to be true, or no more else if clauses are
left. If none of the Boolean expressions are true, the set of statements following the final
else clause is executed.
For example, look at the Grader2 application in the Chap04 folder of this book’s Student
Sample Programs. This application works just like the Grader application that was previously
discussed. The user enters a numeric test score, and the application displays a grade. Its form
is identical to the form shown in Figure 4-15. The Grader2 application, however, uses an
if-else-if statement to determine the grade instead of nested if-else statements. The
Grader2 application’s determineGradeButton_Click event handler is shown here:
1 private void determineGradeButton_Click(object sender, EventArgs e)
2 {
3
try
4
{
5
// Variable to hold the test score.
6
double testScore;
7
// Get the test score.
8
9
testScore = double.Parse(testScoreTextBox.Text);
10
11
// Determine the grade.
12
if (testScore < 60)
13
{
14
gradeLabel.Text = "F";
15
}
16
else if (testScore < 70)
17
{
18
gradeLabel.Text = "D";
19
}
20
else if (testScore < 80)
21
{
22
gradeLabel.Text = "C";
23
}
24
else if (testScore < 90)
25
{
26
gradeLabel.Text = "B";
223
224
C h a p te r 4
M a k in g D e c is io n s
27
28
29
30
31
32
33
34
35
36
37
38 }
}
else
{
gradeLabel.Text = "A";
}
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
}
N otice the alignment and indentation that is used with the if-else-if statement: The
if, else if, and else clauses are all aligned, and the conditionally executed statements
are indented.
You never have to use the if-else-if statement because its logic can be coded with
nested if-else statements; however, a long series of nested if-else statements has two
particular disadvantages when you are debugging code:
• The code can grow complex and become difficult to understand.
• Because indenting is important in nested statements, a long series of nested if-else
statements can become too long to be displayed on the computer screen without
horizontal scrolling. Also, long statements tend to wrap around when printed on
paper, making the code even more difficult to read.
The logic of an if-else-if statement is usually easier to follow than a long series of
nested if-else statements. And, because all the clauses are aligned in an if-else-if
statement, the lengths of the lines in the statement tend to be shorter.
C h e c k p o in t
4.11 Convert the following set of nested if-else statements to an if-else
if statement:
if (number == 1)
{
MessageBox.Show("One");
}
else
{
if (number == 2)
{
MessageBox.Show("Two");
}
else
{
if (number == 3)
{
MessageBox.Show("Three");
}
else
{
MessageBox.Show("Unknown");
}
}
}
4 .4
4 .4
L o g ic a l O p e r a t o r s
L o g ic a l O p e r a t o r s
C O N C E P T :
T h e l o g i c a l A N D o p e r a t o r ( &&) a n d t h e l o g i c a l O R o p e r a t o r ( ||) a l l o w y o u
to c o n n e c t m u ltip le B o o le a n e x p r e s s io n s to c r e a te a c o m p o u n d e x p r e s s io n .
T h e l o g i c a l N O T o p e r a t o r ( !) r e v e r s e s t h e t r u t h o f a B o o l e a n e x p r e s s i o n .
The C# language provides a set of operators known as l o g i c a l o p e r a t o r s , which you can
use to create complex Boolean expressions. Table 4-3 describes these operators.
T a b le 4 -3
L o g ic a l o p e r a t o r s
Op erato r
M e a n in g
&&
This is the logical AN D operator. It connects two Boolean expressions
into one compound expression. Both subexpressions must be true for
the compound expression to be true.
||
This is the logical OR operator. It connects two Boolean expressions
into one compound expression. One or both subexpressions must be
true for the compound expression to be true. It is necessary for only
one of the subexpressions to be true, and it does not matter which.
!
This is the logical N OT operator. It is a unary operator, meaning it
works with only one operand. The operand must be a Boolean
expression. The not operator reverses the truth of its operand. If it is
applied to an expression that is true, the operator returns false. If it is
applied to an expression that is false, the operator returns true.
Table 4-4 shows examples of several compound Boolean expressions that use logical
operators.
T a b le 4 -4
C o m p o u n d B o o le a n e x p r e s s io n s u s in g lo g ic a l o p e r a t o r s
E x p r e s s io n
M e a n in g
x > y && a < b
Is x greater than y AN D is a less than b?
x == y || x == z
Is x equal to y O R is x equal to z?
! (x > y)
Is the expression x > y N O T true?
T h e && O p e r a t o r
The && o p e r a t o r is the l o g i c a l A N D o p e r a t o r . It takes two Boolean expressions as operands and creates a compound Boolean expression that is true only when both subexpressions are true. The following is an example of an if statement that uses the && operator:
if (temperature < 20 && minutes > 12)
{
MessageBox.Show("The temperature is in the danger zone.");
}
In this statement, the two Boolean expressions temperature < 20 and minutes > 12
are combined into a compound expression. The MessageBox.Show statement is executed
only if temperature is less than 20 and minutes is greater than 12. If either of the
Boolean subexpressions is false, the compound expression is false and the message is
not displayed.
225
226
C h a p te r 4
M a k in g D e c is io n s
Table 4-5 shows a truth table for the && operator. The truth table lists expressions showing all the possible combinations of true and false connected with the && operator. The
resulting values of the expressions are also shown.
T a b le 4 -5
T r u t h t a b l e f o r t h e AND o p e r a t o r
E x p r e s s io n
V a lu e o f th e E x p r e s s io n
true && false
false
false && true
false
false && false
false
true && true
true
As the table shows, both sides of the && operator must be true for the operator to return
a true value.
T h e || O p e r a t o r
The || o p e r a t o r is the l o g i c a l O R o p e r a t o r . It takes two Boolean expressions as operands
and creates a compound Boolean expression that is true when either of the subexpressions
is true. The following is an example of an if statement that uses the || operator:
if (temperature < 20 || temperature > 100)
{
MessageBox.Show("The temperature is in the danger zone.");
}
The MessageBox.Show statement executes only if temperature is less than 20 or
temperature is greater than 100. If either subexpression is true, the compound expression is true. Table 4-6 shows a truth table for the || operator.
T a b le 4 -6
T r u t h t a b l e f o r t h e || o p e r a t o r
E x p r e s s io n
V a lu e o f th e E x p r e s s io n
true || false
true
false || true
true
false || false
false
true || true
true
All it takes for an || expression to be true is for one side of the || operator to be true. It
doesn’t matter if the other side is false or true.
S h o r t -C ir c u it E v a lu a t io n
Both the && and || operators perform s h o r t - c i r c u i t e v a l u a t i o n . H ere is how it works with
the && operator: if the expression on the left side of the && operator is false, the expression
on the right side is not checked. Because the compound expression is false if only one of
the subexpressions is false, it would waste CPU time to check the remaining expression.
So, when the && operator finds that the expression on its left is false, it short-circuits and
does not evaluate the expression on its right.
H ere’s how short-circuit evaluation works with the || operator: if the expression on the
left side of the || operator is true, the expression on the right side is not checked. Because
it is necessary for only one of the expressions to be true, it would waste CPU time to check
the remaining expression.
4 .4
L o g ic a l O p e r a t o r s
T h e !O p e r a t o r
The ! o p e r a t o r is the l o g i c a l N O T o p e r a t o r . It is a unary operator that takes a Boolean
expression as its operand and reverses its logical value. In other words, if the expression is
true, the ! operator returns false, and if the expression is false, the ! operator returns true.
The following is an if statement using the N OT operator:
if ( !(temperature > 100) )
{
MessageBox.Show("This is below the maximum temperature.");
}
First, the expression (temperature > 100) is tested and a value of either true or false is
the result. Then the ! operator is applied to that value. If the expression (temperature >
100) is true, the ! operator returns false. If the expression (temperature > 100) is false,
the ! operator returns true. The previous code is equivalent to asking “ Is the temperature
not greater than 100?”
Notice that in this example, we have put parentheses around the expression temperature >
100. This is necessary because the ! operator has higher precedence than the relational
operators. If we do not put the parentheses around the expression temperature > 100,
the ! operator will be applied just to the temperature variable.
Table 4-7 shows a truth table for the ! operator.
T a b le 4 -7
T r u th ta b le fo r th e ! o p e r a to r
E x p r e s s io n
V a lu e o f th e E x p r e s s io n
! true
false
! false
true
P r e c e d e n c e o f t h e L o g ic a l O p e r a t o r s
We mentioned earlier that the ! operator has higher precedence than the relational operators. The && and || logical operators have lower precedence than the relational operators.
For example, look at the following expression:
creditScore > 700 || accountBalance > 9000
When this expression is evaluated, the > operators work first, and then the || operator
works. The expression is the same as the following:
(creditScore > 700) || (accountBalance > 9000)
M any programmers choose to enclose the expressions that are to the left and the right of a
logical operator in parentheses, asshown here. Even though theparenthesesarenot required
in many situations, using them makes the compound expression easier to understand.
C h e c k in g N u m e r ic R a n g e s w it h L o g ic a l O p e r a t o r s
Sometimes you need to write code that determines whether a numeric value is within a
specific range of values or outside a specific range of values. When determining whether a
number is inside a range, it is best to use the && operator. For example, the following if
statement checks the value in x to determine whether it is in the range of 20 through 40:
if (x > 20 && x < 40)
{
MessageBox.Show("The value is in the acceptable range.");
}
227
228
C h a p te r 4
M a k in g D e c is io n s
The compound Boolean expression being tested by this statement is true only when x is
greater than 20 and less than 40. The value in x must be between the values of 20 and 40
for this compound expression to be true.
When determining whether a number is outside a range, it is best to use the || operator.
The following statement determines whether x is outside the range of 20 through 40:
if (x < 20 || x > 40)
{
MessageBox.Show("The value is outside the acceptable range.");
}
It is important not to get the logic of the logical operators confused when testing for a
range of numbers. For example, the compound Boolean expression in the following code
would never test true:
// This is an error!
if (x < 20 && x > 40)
{
MessageBox.Show("The value is outside the acceptable range.");
}
Obviously, x cannot be less than 20 and at the same time be greater than 40.
Let’s look at an example application that checks the range of a value entered by the user.
Open the Range Checker application in the Chap04 folder of this book’s Student Sample
Programs. Figure 4-17 shows the application’s form, along with the names of some of the
controls. When you run the application, you enter an integer into the inputTexBox control and click the checkButton control. If you enter a number in the range of 1 through
10, a message box appears letting you know that the number is acceptable. Otherwise, a
message box appears letting you know that the number is not acceptable.
F ig u r e 4 -1 7
T h e Ra nge Checker a p p l i c a t i o n ’ s f o r m
inputTextBox
checkButton
exitButton
The following code sample shows the checkButton_Click event handler. Line 7 declares
an int variable named number, initialized with the value that has been entered into the
inputTextBox control. The if statement that begins in line 10 determines whether
number is greater than or equal to 1 AN D number is less than or equal to 10. If the
Boolean expression is true, the statement in line 12 executes. Otherwise, the statement in
line 16 executes.
1 private void checkButton_Click(object sender, EventArgs e)
2 {
3
try
4
{
4 .4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 }
L o g ic a l O p e r a t o r s
// Declare a variable and initialize it with
// the user's input.
int number = int.Parse(inputTextBox.Text);
// Check the number's range.
if (number >= 1 && number <= 10)
{
MessageBox.Show("That number is acceptable.");
}
else
{
MessageBox.Show("That number is NOT acceptable.");
}
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
}
C h e c k p o in t
4.12 What is a compound Boolean expression?
4.13 The following truth table shows various combinations of the values true and
false connected by a logical operator. Complete the table by circling T or F to
indicate whether the result of such a combination is true or false.
L o g ic a l E x p r e s s io n
R e s u lt (c ir c le T o r F )
true && false
T
F
true && true
T
F
false && true
T
F
false && false
T
F
true || false
T
F
true || true
T
F
false || true
T
F
false || false
T
F
! true
T
F
! false
T
F
4.14 Assume the variables a = 2, b = 4, and c = 6. Circle T or F for each of the following
conditions to indicate if it is true or false.
a == 4 || b > 2
T
F
6 <= c && a > 3
T
F
1 != b && c != 3
T
F
a >= −1 || a <= b
T
F
!(a > 2)
T
F
4.15 Explain how short-circuit evaluation works with the && and || operators.
4.16 Write an if statement that displays the message “ The number is valid” in a message box if the variable speed is within the range 0 through 200.
4.17 Write an if statement that displays the message “ The number is not valid” in a
message box if the variable speed is outside the range 0 through 200.
2 2 9
230
C h a p te r 4
4 .5
M a k in g D e c is io n s
bool V a r i a b l e s a n d F l a g s
C O N C E P T :
Y o u c a n s t o r e t h e v a l u e s true a n d false i n bool v a r i a b l e s , w h i c h a r e
c o m m o n ly u s e d a s fla g s .
The C# language provides the bool d a t a t y p e that you can use to create variables that
hold true or false values. H ere is an example of the declaration of a bool variable:
bool grandMaster;
This declares a bool variable named grandMaster. In the program we can assign the
values true or false to the variable, as shown here:
if (points > 5000)
{
grandMaster = true;
}
else
{
grandMaster = false;
}
Variables of the bool data type are commonly used as flags. A f l a g is a variable that
signals when some condition exists in the program. When the flag variable is set to
false, it indicates that the condition does not yet exist. When the flag variable is set
to true, it means the condition does exist. For example, the previous code might be
used in a game to determine whether the user is a “ grand master.” If he or she has
earned more than 5,000 points, we set the grandMaster variable to true. Otherwise,
we set the variable to false . Later in the program we can test the grandMaster
variable, like this:
if (grandMaster)
{
powerLevel += 500;
}
This code performs the following: if grandMaster is true, add 500 to powerLevel. H ere
is another example:
if (!grandMaster)
{
powerLevel = 100;
}
This code performs the following: if grandMaster is not true, set powerLevel to 100.
C h e c k p o in t
4.18 What special values can you store in a bool variable?
4.19 What is a flag variable?
4 .6
C o m p a r in g S t r in g s
C O N C E P T :
Y o u c a n u s e c e r ta in r e la tio n a l o p e r a to r s a n d m e th o d s to c o m p a r e s tr in g s .
4 .6
C o m p a r in g S t r in g s
You can use the == operator to compare two strings. For example, look at the following
code sample:
string name1 = "Mary";
string name2 = "Mark";
if (name1 == name2)
{
MessageBox.Show("The names are the same.");
}
else
{
MessageBox.Show("The names are NOT the same.");
}
The == operator compares name1 and name2 to determine whether they are equal. Because
the strings “ M ary” and “ M ark” are not equal, the else clause displays the message “ The
names are N OT the same.”
You can compare string variables with string literals as well. Assume month is a string
variable. The following code sample uses the != operator to determine whether month is
not equal to "October".
if (month != "October")
{
statement;
}
Look at the Secret Word application in the Chap04 folder of this book’s Student Sample
Programs. Figure 4-18 shows the application’s form, with the names of some of the controls. The form prompts you to enter the secret word into the inputTexBox control.
When you click the checkButton control, the application compares the string that you
entered to " Ariel."
F ig u r e 4 -1 8
T h e Secret Word a p p l i c a t i o n ’ s f o r m
inputTextBox
checkButton
exitButton
The following code sample shows the checkButton_Click event handler. Line 5 declares
a string variable named secretWord, initialized with the value that has been entered
into the inputTextBox control. The if statement that begins in line 8 compares the
secretWord variable to the string literal "Ariel". If the two are equal, the statement in
line 10 executes. Otherwise, the statement in line 14 executes.
1 private void checkButton_Click(object sender, EventArgs e)
2 {
3
// Declare a string variable and initialize it with
4
// the user's input.
5
string secretWord = inputTextBox.Text;
6
231
232
C h a p te r 4
M a k in g D e c is io n s
7
8
9
10
11
12
13
14
15
16
// Did the user enter the correct secret word?
if (secretWord == "Ariel")
{
MessageBox.Show("That is the correct secret word.");
}
else
{
MessageBox.Show("Sorry, that is NOT the secret word.");
}
}
O t h e r S t r in g C o m p a r is o n s
In addition to determining whether strings are equal or not equal, you can use the String.
Compare method to determine whether one string is greater than or less than another
string. This is a useful capability because sometimes you need to sort strings in some
order. Before we look at how the method works, we should review how characters are
stored in memory.
Recall from Chapter 1 that computers do not actually store characters, such as A, B, C,
and so forth, in memory. Instead, they store numeric codes that represent the characters.
We mentioned in Chapter 1 that C# uses Unicode to represent characters. H ere are some
facts about the Unicode system:
• The uppercase characters A through Z are represented by the numbers 65
through 90.
• T he l ow er case char act er s a t hr ough z ar e r epr esent ed by t he number s 97
through 122.
• When the digits 0 through 9 are stored in memory as characters, they are represented by the numeric codes 48 through 57. (For example, the string “ abc123” is
stored in memory as the codes 97, 98, 99, 49, 50, and 51.)
• A blank space is represented by the number 32.
In addition to establishing a set of numeric codes to represent characters in memory, Unicode also establishes an order for characters. The character A comes before the character
B, which comes before the character C, and so forth.
When a program compares characters, it actually compares the codes for the characters.
The character A would be considered less than the character B because the character A’s
numeric code is less than the character B’s numeric code.
Let’s look at how strings containing more than one character are compared. Suppose we
have the strings “ M ary” and “ M ark” stored in memory, as follows:
string name1 = "Mary";
string name2 = "Mark";
Figure 4-19 shows how the strings “ M ary” and “ M ark” are stored in memory using
character codes.
F ig u r e 4 -1 9
C h a r a c t e r c o d e s fo r t h e s t r in g s “ M a r y ” a n d “ M a r k ”
M
a
r
y
77 97 114 121
M
a
r
k
77 97 114 107
When you compare these strings in a program, they are compared character by character,
beginning with the first, or leftmost, characters. This is shown in Figure 4-20.
4 .6
F ig u r e 4 -2 0
C o m p a r in g S t r in g s
C o m p a r in g e a c h c h a r a c t e r in a s t r in g
M
a
r
y
77 97 114 121
77 97 114 107
M
a
r
k
H ere is how the comparison takes place:
1. The M in “ M ary” is compared with the M in “ M ark.” These are the same, so the
next characters are compared.
2. The a in “ M ary” is compared with the a in “ M ark.” Because these are the same, the
next characters are compared.
3. The r in “ M ary” is compared with the r in “ M ark.” These are the same, so the next
characters are compared.
4. The y in “ M ary” is compared with the k in “ M ark.” Because these are not the same,
the two strings are not equal. The character y has a higher character code (121) than
k (107), so it is determined that the string “ M ary” is greater than the string “ M ark.”
If one of the strings in a comparison is shorter than the other, only the corresponding characters are compared. If the corresponding characters are identical, then the shorter string is
considered less than the longer string. For example, suppose the strings “ H igh” and “ H i”
are compared. The string “ H i” is considered less than “ H igh” because it is shorter.
In C# you cannot use relational operators to determine whether one string is greater than
or less than another string. Instead, you use the String.Compare method. You use the
following general format to call the method:
String.Compare(string1, string2)
In the general format, string1 and string2 are the strings that are being compared. The
method returns an integer value indicating the result of the comparison. The integer value
will be one of the following:
• Greater than zero if string1 is greater than string2.
• Z ero if string1 is equal to string2.
• Less than zero if string1 is less than string2.
H ere is a code sample that uses the method to display two names in alphabetical order:
1 string str1 = "Joe";
2 string str2 = "Kerry";
3
4 if (String.Compare(str1, str2) < 0)
5 {
6
MessageBox.Show(str1 + " " + str2);
7 }
8 else
9 {
10
MessageBox.Show(str2 + " " + str1);
11 }
The if statement in line 4 calls the String.Compare method, passing str1 and str2 as
arguments. If we execute this code, the method will return a value that is less than 0
because the string “ Joe” is less than the string “ Kerry” . As a result, the statement in line 6
will display Joe Kerry.
The String.Compare method performs a case sensitive comparison, which means that
uppercase characters are not considered the same as their lowercase counterparts.
233
234
C h a p te r 4
M a k in g D e c is io n s
For example, the strings “ Joe” and “ joe” are not equal because the case of the first
character is different in each. You can pass the Boolean value true as an optional third
argument to the String.Compare method if you want it to perform a case insensitive
comparison. H ere is an example:
1 string str1 = "JOE";
2 string str2 = "joe";
3
4 if (String.Compare(str1, str2, true) == 0)
5 {
6
MessageBox.Show(str1 + " and " + str2 + " are equal.");
7 }
8 else
9 {
10
MessageBox.Show(str1 + " and " + str2 + " are NOT equal.");
11 }
N otice that the if statement in line 4 passes true as the third argument to the String.
Compare method. This specifies that we want a case insensitive comparison. As a result,
the method will return 0 and the statement in line 6 will display JO E and joe are equal.
C h e c k p o in t
4.20 If the following code were part of a complete program, what would it display?
if (String.Compare("z", "a") < 0)
{
MessageBox.Show("z is less than a.");
}
else
{
MessageBox.Show("z is not less than a.");
}
4.21 If the following code were part of a complete program, what would it display?
string s1 = "New York";
string s2 = "Boston";
if (String.Compare(s1, s2) > 0)
{
MessageBox.Show(s2);
MessageBox.Show(s1);
}
else
{
MessageBox.Show(s1);
MessageBox.Show(s2);
}
4 .7
P r e v e n t in g D a t a C o n v e r s io n E x c e p t io n s
w i t h t h e TryParse M e t h o d s
C O N C E P T :
E x c e p t i o n s s h o u l d b e p r e v e n t e d w h e n p o s s i b l e . Y o u c a n u s e t h e TryParse
m e th o d s to p r e v e n t e x c e p tio n s a s a r e s u lt o f th e u s e r e n te r in g in v a lid d a ta .
In Chapter 3, you learned that the Parse methods throw an exception when you try to
use them to convert nonnumeric data to a numeric data type. If you use one of the Parse
4 .7
P r e v e n t i n g D a t a C o n v e r s i o n E x c e p t i o n s w i t h t h e TryParse M e t h o d s
methods to convert a TextBox control’s Text property to a number, there is always the
possibility of an exception being thrown. After all, the user is free to enter anything he or
she wants into a TextBox control. To handle the exceptions that are caused by the Parse
methods, we have been using the try-catch statement.
Although many exceptions happen for reasons that the programmer cannot anticipate
(such as a system malfunction), some exceptions are predictable. For example, you know
that using a Parse method to convert nonnumeric input to a numeric data type will
throw an exception. In situations like that, where an exception is predictable, you should
write your code to prevent the exception. It is a better programming practice to prevent
an exception instead of allowing it to happen and then letting a try-catch statement
react to it. You should use try-catch statements primarily for those exceptions that are
beyond your control.
N O T E :
Until now, we’ve simply been allowing exceptions to happen and letting a
try-catch statement respond to them. After reading the previous paragraph, you
might be wondering why we haven’t been preventing exceptions all along. The reason
is that you need to know how to write if statements to perform the techniques that
we discuss in this section. N ow that you know how to write if statements, you can
add more sophistication to your code.
N ow that you know how to write if statements, you can use a family of methods in the
.N ET Framework known as the TryParse methods. With the TryParse m e t h o d s , you can
determine whether a string (such as a control’s Text property) contains a value that can be
converted to a specific data type before it is converted to that data type. The TryParse
methods do not throw an exception, so you can use them without a try-catch statement.
There are several TryParse methods in the .N ET Framework. For now, we are using the
int, double, and decimal numeric data types, so we will discuss three of them:
• We use the int.TryParse m e t h o d to convert a string to an int.
• We use the double.TryParse m e t h o d to convert a string to a double.
• We use the decimal.TryParse m e t h o d to convert a string to a decimal.
When you call one of the TryParse methods, you pass two arguments: (1) the string that
you want to convert, and (2) the name of the variable in which you want to store the converted value. First, let’s look at the int.TryParse method. H ere is the general format of
how the int.TryParse method is called:
int.TryParse(string, out targetVariable)
In the general format, string is the string that you want to convert, and targetVariable
is the name of an int variable. The method tries to convert the string argument to an
int. If the conversion is successful, the converted value is stored in the targetVariable,
and the method returns the Boolean value true to indicate that the conversion was
successful. If the conversion is not successful, the method does not throw an exception.
Instead, it stores 0 in the targetVariable and returns the Boolean value false to
indicate that the string could not be converted.
Look carefully at the general format and notice that the word out appears before the
targetVariable. The out k e y w o r d is required, and it specifies that the targetVariable
is an output variable. An o u t p u t v a r i a b l e is a variable that is passed as an argument to a
method, and when the method is finished, a value is stored in the variable.
Because the TryParse methods return either true or false, they are commonly called as
the Boolean expression in an if statement. The following code shows an example using
235
236
C h a p te r 4
M a k in g D e c is io n s
the int.TryParse method. In the example, assume that inputTextBox is the name of a
TextBox control.
1 int number;
2
3 if (int.TryParse(inputTextBox.Text, out number))
4 {
5
MessageBox.Show("Success!");
6 }
7 else
8 {
9
MessageBox.Show("Enter a valid integer.");
10 }
The purpose of this code sample is to convert the value of the inputTextBox control’s
Text property to an int and assign that value to the number variable. In line 3, the if
statement calls the int.TryParse method, passing inputTextBox.Text as argument 1
and number as argument 2. H ere’s what happens:
• If inputTextBox.Text is successfully converted to an int, the resulting value is
assigned to the number variable, and the method returns true. That causes the
statement in line 5 to execute.
• If inputTextBox.Text cannot be converted to an int, the value 0 is assigned to the
number variable, and the method returns false. That causes the statement in line 9
(after the else clause) to execute.
The other TryParse methods work in a similar manner. H ere is the general format of
how the double.TryParse method is called:
double.TryParse(string, out targetVariable)
In the general format, string is the string that you want to convert, and targetVariable
is the name of a double variable. If the string can be converted to a double, its value is
stored in the targetVariable, and the method returns the Boolean value true to indicate
that the conversion was successful. If the conversion was not successful, the method stores
0 in the targetVariable and returns the Boolean value false to indicate that the string
could not be converted.
The following code shows an example using the double.TryParse method. In the example, assume that inputTextBox is the name of a TextBox control.
1 double number;
2
3 if (double.TryParse(inputTextBox.Text, out number))
4 {
5
MessageBox.Show("Success!");
6 }
7 else
8 {
9
MessageBox.Show("Enter a valid double.");
10 }
H ere is the general format of how the decimal.TryParse method is called:
decimal.TryParse(string, out targetVariable)
In the general format, string is the string that you want to convert, and targetVariable
is the name of a decimal variable. If the string can be converted to a decimal, its value is
stored in the targetVariable, and the method returns the Boolean value true to indicate
that the conversion was successful. If the conversion was not successful, the method stores 0
in the targetVariable and returns the Boolean value false to indicate that the string
could not be converted.
4 .7
P r e v e n t i n g D a t a C o n v e r s i o n E x c e p t i o n s w i t h t h e TryParse M e t h o d s
The following code shows an example using the decimal.TryParse method. In the
example, assume that inputTextBox is the name of a TextBox control.
1 decimal number;
2
3 if (decimal.TryParse(inputTextBox.Text, out number))
4 {
5
MessageBox.Show("Success!");
6 }
7 else
8 {
9
MessageBox.Show("Enter a valid decimal.");
10 }
V a lid a t in g t h e D a t a in M u lt ip le T e x t B o x e s
If a form has multiple TextBoxes, then the user has multiple opportunities to enter an
invalid piece of data. A well-designed program should validate the contents of each
TextBox individually. When a piece of invalid data is found, the program should display
an error message that tells the user specifically which TextBox contains the bad input.
This technique requires a set of nested if statements. For example, suppose a form has
two TextBoxes. The following pseudocode shows the logic for validating each TextBox.
(In the pseudocode, a set of dotted lines connects each If statement with its corresponding
Else clause and its ending.)
If the data in the first TextBox is good, then
If the data in the second TextBox is good, then
Process the data in both TextBoxes
Else
Display an error message about the second TextBox
End if
Else
Display an error message about the first TextBox
End if
Let’s see how that logic looks in actual C# code. In the Chap04 folder of this book’s
Student Sample Programs, you will find a project named Add Two N umbers. The
application’s form is shown in Figure 4-21. When you run the application, enter an integer
into each of the TextBox controls and then click the Add button. A message box will
appear showing the sum of the two numbers. If you enter anything other than an integer
into either TextBox, an error message will appear telling you which TextBox contains the
invalid data.
F ig u r e 4 -2 1
T h e Add Two Numbers f o r m
firstTextBox
secondTextBox
addButton
237
238
C h a p te r 4
M a k in g D e c is io n s
H ere is the code for the addButton_Click event handler:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private void addButton_Click(object sender, EventArgs e)
{
// Local variables
int first, second, sum;
if (int.TryParse(firstTextBox.Text, out first))
{
if (int.TryParse(secondTextBox.Text, out second))
{
// Add the two numbers and display the sum.
sum = first + second;
MessageBox.Show(sum.ToString());
}
else
{
// Display an error message about the second TextBox.
MessageBox.Show("The second TextBox contains invalid data.");
}
}
else
{
// Display an error message about the first TextBox.
MessageBox.Show("The first TextBox contains invalid data.");
}
}
Let’s take a closer look:
• Line 4 declares three int variables: first, second, and sum.
• The if statement in line 6 tries to convert firstTextBox.Text to an int. If the
conversion is successful, the result is stored in the first variable, and the program
continues executing at line 8. If the conversion is not successful, the program jumps
to the else clause in line 20, and line 23 displays an error message regarding the
first TextBox control.
• The if statement in line 8 tries to convert secondTextBox.Text to an int. If the
conversion is successful, the result is stored in the second variable, and the program
continues executing at line 10. If the conversion is not successful, the program jumps
to the else clause in line 14, and line 17 displays an error message regarding the
second TextBox control.
• The statements in lines 11 and 12 execute only if both TextBox controls contain
valid integer values. These statements add the first and second variables and display their sum.
If you need to validate three TextBox controls, you will write a set of three nested if
statements. H ere’s the pseudocode:
If the data in the first TextBox is good, then
If the data in the second TextBox is good, then
If the data in the third TextBox is good, then
Process the data in all three TextBoxes
Else
Display an error message about the third TextBox
End if
Else
Display an error message about the second TextBox
End if
Else
Display an error message about the first TextBox
End if
4 .9
R a d io B u t t o n s a n d C h e c k B o x e s
CheckedChanged. Complete the yellowRadioButton_CheckedChanged event
handler by typing the code shown in lines 22–25 in Program 4-5.
The event handler is easy to understand. The if statement in line 22 determines
whether the yellowRadioButton control is checked. If so, line 24 sets the
form’s background to yellow.
S t e p 4 :
Switch your view back to the D esigner and double-click the redRadioButton
control. This opens the code editor, and you see an empty event handler named
redRadioButton_CheckedChanged . Complete the redRadioButton_
CheckedChanged event handler by typing the code shown in lines 30–33 in
Program 4-5.
S t e p 5 :
Switch your view back to the D esigner and double-click the whiteRadioButton
control. This opens the code editor, and you see an empty event handler named
whiteRadioButton_CheckedChanged. Complete the whiteRadioButton_
CheckedChanged event handler by typing the code shown in lines 38–41 in
Program 4-5.
S t e p 6 :
Switch your view back to the D esigner and double-click the normalRadioButton
control. This opens the code editor, and you see an empty event handler named
normalRadioButton_CheckedChanged. Complete the normalRadioButton_
CheckedChanged event handler by typing the code shown in lines 46–49 in
Program 4-5.
S t e p 7 :
Switch your view back to the D esigner and double-click the exitButton control.
In the code editor you see an empty event handler named exitButton_Click.
Complete the exitButton_Click event handler by typing the code shown in
lines 54–55 in Program 4-5.
S t e p 8 :
Save the project and run the application. N otice that the Back to N ormal radio
button is initially selected. That’s because you set its Checked property to True
in the Properties window. Click the other Radio buttons and notice that the
form’s background color changes immediately. When you are finished testing
the application, click the Exit button to close it.
P r o g r a m 4 -5
C o m p l e t e d F o r m 1 c o d e f o r t h e Color Theme a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Color_Theme
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void yellowRadioButton_CheckedChanged(object sender, EventArgs e)
21
{
249
250
C h a p te r 4
M a k in g D e c is io n s
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58 }
if (yellowRadioButton.Checked)
{
this.BackColor = Color.Yellow;
}
}
private void redRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (redRadioButton.Checked)
{
this.BackColor = Color.Red;
}
}
private void whiteRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (whiteRadioButton.Checked)
{
this.BackColor = Color.White;
}
}
private void normalRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (normalRadioButton.Checked)
{
this.BackColor = SystemColors.Control;
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
C h e c k p o in t
4.26 If several RadioButton controls have been created in the same GroupBox, how
many of them may be selected at one time?
4.27 If several CheckBox controls have been created in the same GroupBox, how many
of them may be selected at one time?
4.28 In code, how do you determine whether a RadioButton or a CheckBox control has
been selected?
4 .1 0
T h e switch S t a t e m e n t
C O N C E P T :
T h e switch s t a t e m e n t l e t s t h e v a l u e o f a v a r i a b l e o r a n
d e te r m in e w h ic h p a th o f e x e c u tio n th e p r o g r a m w ill ta k e .
e x p r e s s io n
The switch s t a t e m e n t is a m u l t i p l e - a l t e r n a t i v e d e c i s i o n s t r u c t u r e . It allows you to test
the value of a variable or an expression and then use that value to determine which
4 .1 0
T h e Switch S t a t e m e n t
statement or set of statements to execute. Figure 4-30 shows an example of how a
multiple-alternative decision structure looks in a flowchart.
F ig u r e 4 -3 0
A m u lt ip le - a lt e r n a t iv e d e c is io n s t r u c t u r e
month
1
2
Display "January"
Display "February"
3
Default
Display "March"
Display "Error:
Invalid month"
In the flowchart, the diamond symbol shows month, which is the name of a variable. If
the month variable contains the value 1, the program displays “ January.” If the month
variable contains the value 2, the program displays “ February.” If the month variable
contains the value 3, the program displays “ M arch.” If the month variable contains none
of these values, the action that is labeled Default is executed. In this case, the program
displays “ Error: Invalid month.”
H ere is the general format of a switch statement in C# code:
The testExpression is
a variable or expression.
switch (testExpression)
{
case value_1:
statement;
These statements are executed
statement;
if the testExpression is
etc.
equal to value_1.
break;
case value_2:
statement;
statement;
etc.
break;
These statements are executed
if the testExpression is
equal to value_2.
Insert as many case sections as necessary.
case value_N:
statement;
statement;
etc.
break;
default:
statement;
statement;
etc.
break;
}
These statements are executed
if the testExpression is
equal to value_N.
These statements are executed
if the testExpression is
not equal to any of the case
values.
251
252
C h a p te r 4
M a k in g D e c is io n s
The first lineof the statement starts with the word switch, followed by a testExpression,
which is enclosed in parentheses. The testExpression is a variable or an expression that
gives an integer, string, or bool value. (Several other data types that we have not discussed
yet are also permissible. The important thing to remember is that the testExpression
cannot be a floating-point or decimal value.)
Beginning at the next line is a block of code enclosed in curly braces. Inside this block of
code are one or more case sections. A case section begins with the word case, followed by
a value, followed by a colon. Each case section contains one or more statements, followed
by a break statement. Each case section must end with a break statement. At the end is an
optional default section. The default section must also end with a break statement.
When the switch statement executes, it compares the value of the testExpression with
the values that follow each of the case statements (from top to bottom). When it finds a
case value that matches the testExpression’s value, the program branches to the case
statement. The statements that follow the case statement are executed, until a break
statement is encountered. At that point the program jumps out of the switch statement.
If the testExpression does not match any of the case values, the program branches to
the default statement and executes the statements that immediately follow it.
For example, the following code performs the same operation as the flowchart in
Figure 4-30:
switch (month)
{
case 1:
MessageBox.Show("January");
break;
case 2:
MessageBox.Show("February");
break;
case 3:
MessageBox.Show("March");
break;
default:
MessageBox.Show("Error: Invalid month");
break;
}
In this example the testExpression is the month variable. If the value in the month
variable is 1, the program branches to the case 1: section and executes the MessageBox.
Show("January") statement that immediately follows it. If the value in the month
variable is 2, the program branches to the case 2: section and executes the MessageBox.
Show("February") statement that immediately follows it. If the value in the month
variable is 3, the program branches to the case 3: section and executes the MessageBox.
Show("March") statement that immediately follows it. If the value in the month variable
is not 1, 2, or 3, the program branches to the default: section and executes the
MessageBox.Show("Error: Invalid month") statement that immediately follows it.
The switch statement can be used as an alternative to an if-else-if statement that
tests the same variable or expression for several different values. For example, the
previously shown switch statement works like this if-else-if statement:
if (month == 1)
{
MessageBox.Show("January");
}
4 .1 1
In t r o d u c t io n t o L is t B o x e s
else if (month == 2)
{
MessageBox.Show("February");
}
else if (month == 3)
{
MessageBox.Show("March");
}
else
{
MessageBox.Show("Error: Invalid month");
}
To see an application that uses a switch statement, look at the Switch Example project in
the Chap04 folder of this book’s Student Sample Programs.
C h e c k p o in t
4.29 Convert the following if-else-if code to a switch statement:
if (choice == 1)
{
MessageBox.Show("You chose 1.");
}
else if (choice == 2)
{
MessageBox.Show("You chose 2.");
}
else if (choice == 3)
{
MessageBox.Show("You chose 3.");
}
else
{
MessageBox.Show("Make another choice.");
}
4 .1 1
In t r o d u c t io n t o L is t B o x e s
C O N C E P T :
L is t b o x e s d is p la y a lis t o f ite m s a n d a llo w th e u s e r to s e le c t a n ite m fr o m
th e lis t.
A list box displays a list of items and allows the user to select one or more items from the
list. In Visual C# you use the L i s t B o x c o n t r o l to create a list box on an application’s form.
Figure 4-31 shows a form, at run time, with two ListBox controls. At run time, the user
may select one of the items, causing the item to appear selected.
The topmost ListBox in Figure 4-31 does not have a scroll bar, but the bottom one does.
A scroll bar appears when a ListBox contains more items than can be displayed in the
space provided. In the figure, the top ListBox has four items (Poodle, Great Dane, German
Shepherd, and Terrier), and all items are displayed. The bottom ListBox shows four items
(Siamese, Persian, Bobtail, and Burmese), but because it has a scroll bar, we know there
are more items in the ListBox than those four.
253
254
C h a p te r 4
M a k in g D e c is io n s
F ig u r e 4 -3 1
L is t B o x e x a m p le s
You will find the ListBox control in the Common Controls section of the Toolbox. Once
you create a ListBox control, you add items to its I t e m s p r o p e r t y . The items that you add
to a ListBox’s Items property are displayed in the ListBox.
To store values in the Items property at design time, follow these steps:
1. Select the ListBox control in the D esigner window.
2. In the Properties window, the setting for the Items property is displayed as (Collection). When you select the Items property, an ellipses button ( ) appears.
3. Click the ellipses button. The String Collection Editor dialog box appears, as shown
in Figure 4-32.
4. Type the values that are to appear in the ListBox into the String Collection Editor dialog
box. Type each value on a separate line by pressing the Enter key after each entry.
5. When you have entered all the values, click the O K button.
F ig u r e 4 -3 2
T h e String Collection Editor d i a l o g b o x
N O T E : Once you acquire the necessary skills, you will be able to fill the Items
collection of list boxes from external data sources (such as databases).
4 .1 1
In t r o d u c t io n t o L is t B o x e s
T h e S e le c t e d It e m P r o p e r t y
When the user selects an item in a ListBox, the item is stored in the ListBox’s
S e l e c t e d I t e m p r o p e r t y . For example, suppose an application has a ListBox control named
fruitListBox and a string variable named selectedFruit . The fruitListBox
control contains the items Apples, Pears, and Bananas. If the user has selected Pears, the
following statement assigns the string "Pears" to the variable selectedFruit:
selectedFruit = fruitListBox.SelectedItem.ToString();
N otice that you have to call the SelectedItem property’s ToString method to retrieve the
value as a string.
D e t e r m in in g W h e t h e r a n It e m Is S e le c t e d
An exception will occur if you try to get the value of a ListBox’s SelectedItem property
when no item is selected in the ListBox. For that reason, you should always make sure
that an item is selected before reading the SelectedItem property. You do this with the
SelectedIndex property.
The items that are stored in a ListBox each have an index. The i n d e x is simply a number
that identifies the item’s position in the ListBox. The first item has the index 0, the next
has the index 1, and so forth. The last index value is n − 1, where n is the number of items
in the ListBox. When the user selects an item in a ListBox, the item’s index is stored in the
ListBox’s S e l e c t e d I n d e x p r o p e r t y . If no item is selected in the ListBox, the SelectedIndex
property is set to −1.
You can use the SelectedIndex property to make sure that an item is selected in a ListBox
before you try to get the value of the SelectedItem property. You simply make sure the
SelectedIndex property is not set to −1 before trying to read the SelectedItem property.
H ere is an example:
if (fruitListBox.SelectedIndex != −1)
{
selectedFruit = fruitListBox.SelectedItem.ToString();
}
In Tutorial 4-6, you will create an application that lets the user select an item from a
ListBox control.
T u t o r ia l 4 -6 :
C r e a t i n g t h e Time Zone A p p l i c a t i o n
VideoNot e
T u to r ia l 4 -6 :
Creating the
Time Z one
application
In this tutorial, you create an application that allows the user to select a city from a
ListBox control. When the user clicks a button, the application displays the name of the
city’s time zone. Figure 4-33 shows the application’s form, with the names of all the
controls.
S t e p 1 :
Start Visual Studio and begin a new Windows Forms Application project named
Time Z one.
S t e p 2 :
Set up the application’s form, as shown in Figure 4-33. N otice that the form’s
Text property is set to Time Z one. The names of the controls are shown in the
figure. As you place each of the controls on the form, refer to Table 4-9 for the
relevant property settings.
255
256
C h a p te r 4
M a k in g D e c is io n s
F ig u r e 4 -3 3
T h e Color Theme f o r m
promptLabel
cityListBox
timeZoneLabel
outputDescriptionLabel
okButton
T a b le 4 -9
exitButton
C o n t r o l p r o p e r t y s e t t in g s
Co n tro l Name
Co n tro l Typ e
P r o p e r ty S e ttin g s
promptLabel
Label
T e x t : Select a city and I will give
you the time zone.
cityListBox
ListBox
Items:
D enver
H onolulu
M inneapolis
N ew York
San Francisco
outputDescriptionLabel
Label
T e x t : Time Z one:
timeZoneLabel
Label
A u t o S i z e : False
B o r d e r S t y l e : FixedSingle
T e x t : (The contents of the Text
property have been erased.)
T e x t A l i g n : M iddleCenter
okButton
Button
T e x t : OK
exitButton
Button
T e x t : Exit
S t e p 3 :
Once you have set up the form with its controls, you can create the Click event
handlers for the Button controls. At the end of this tutorial, Program 4-6 shows
the completed code for the form. You will be instructed to refer to Program 4-6
as you write the event handlers.
In the D esigner, double-click the okButton control. This opens the code editor,
and you see an empty event handler named okButton_Click. Complete the
okButton_Click event handler by typing the code shown in lines 22–53 in
Program 4-6. Let’s take a closer look at the code:
L i n e 2 2 : This line declares a string variable named city. It is used to hold the
name of the city that the user selects from the ListBox.
L i n e 2 4 : This if statement determines whether the user has selected an item in
the cityListBox control. If an item is selected, the control’s SelectedIndex
property is set to the item’s index (a value of 0 or greater), and the program
4 .1 1
In t r o d u c t io n t o L is t B o x e s
continues to line 26. If no item is selected, however, the control’s SelectedIndex
property is set to −1, and the program jumps to the else clause in line 49.
L i n e 2 7 : This statement gets the selected item from the ListBox and assigns it to
the city variable.
L i n e 3 0 : This switch statement tests the city variable and branches to one of its
case statements, depending on the variable’s value:
• If the city variable equals "Honolulu", the program jumps to the case
statement in line 32.
• If the city variable equals "San Francisco", the program jumps to the
case statement in line 35.
• If the city variable equals "Denver" , the program jumps to the case
statement in line 38.
• If the city variable equals "Minneapolis", the program jumps to the case
statement in line 41.
• If the city variable equals "New York", the program jumps to the case
statement in line 44.
S t e p 4 :
Switch your view back to the D esigner and double-click the exitButton control. In the code editor you see an empty event handler named exitButton_
Click. Complete the exitButton_Click event handler by typing the code
shown in lines 58–59 in Program 4-6.
S t e p 5 :
Save the project and run the application. Select a city in the ListBox control and
click the O K button to see its time zone. Test each city, and when you are
finished, click the Exit button, and the form should close.
P r o g r a m 4 -6
C o m p l e t e d F o r m 1 c o d e f o r t h e Time Zone a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Time_Zone
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void okButton_Click(object sender, EventArgs e)
21
{
22
string city;
// To hold the name of a city
23
if (cityListBox.SelectedIndex != −1)
24
25
{
26
// Get the selected item.
27
city = cityListBox.SelectedItem.ToString();
257
258
C h a p te r 4
M a k in g D e c is io n s
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62 }
// Determine the time zone.
switch (city)
{
case "Honolulu":
timeZoneLabel.Text = "Hawaii-Aleutian";
break;
case "San Francisco":
timeZoneLabel.Text = "Pacific";
break;
case "Denver":
timeZoneLabel.Text = "Mountain";
break;
case "Minneapolis":
timeZoneLabel.Text = "Central";
break;
case "New York":
timeZoneLabel.Text = "Eastern";
break;
}
}
else
{
// No city was selected.
MessageBox.Show("Select a city.");
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
C h e c k p o in t
4.30 H ow do you add items to a ListBox control using the Properties window?
4.31 H ow do you get the item that is selected in a ListBox?
4.32 H ow can you determine whether an item has been selected in a ListBox?
R e v ie w Q u e s t io n s
K e y T e r m s
! operator
&& operator
|| operator
bool data type
Boolean expression
check box
CheckBox control
Checked property
CheckedChanged event
conditionally executed
control structure
decimal.TryParse method
decision structure
double.TryParse method
dual-alternative decision structure
flag
if-else statement
if-else-if statement
index
input validation
int.Tryparse method
Items property
ListBox control
logical AN D operator
logical N OT operator
logical operator
logical OR operator
multiple-alternative decision
structure
mutually exclusive selection
nested decision structure
out keyword
output variable
radio buttons
RadioButton control
relational operator
SelectedIndex property
SelectedItem property
selection structure
sequence structure
short-circuit evaluation
single-alternative decision structure
switch statement
TryParse method
R e v ie w Q u e s t io n s
M u lt ip le C h o ic e
1 .
A __________ structure executes a set of statements only under certain circumstances.
a.
b.
c.
d.
2 .
A __________ structure provides one alternative path of execution.
a.
b.
c.
d.
3 .
sequence
single-alternative decision
one-path alternative
single-execution decision
A(n) __________ expression has a value of either true or false.
a.
b.
c.
d.
4 .
sequence
circumstantial
decision
Boolean
binary
decision
unconditional
Boolean
The symbols >, <, and == are all __________ operators.
a.
b.
c.
d.
relational
logical
conditional
ternary
259
260
C h a p te r 4
M a k in g D e c is io n s
5 .
A __________ structure tests a condition and then takes one path if the condition is
true or another path if the condition is false.
a.
b.
c.
d.
6 .
You use a(n) __________ statement to write a single-alternative decision structure.
a.
b.
c.
d.
7 .
&&
||
!
either
The __________ operator takes a Boolean expression as its operand and reverses its
logical value.
a.
b.
c.
d.
1 3 .
&&
||
!
both
A compound Boolean expression created with the __________ operator is true if
either of its subexpressions is true.
a.
b.
c.
d.
1 2 .
relational
logical
conditional
ternary
A compound Boolean expression created with the __________ operator is true only
if both of its subexpressions are true.
a.
b.
c.
d.
1 1 .
nested
tiered
dislodged
hierarchical
&&, ||, and ! are __________ operators.
a.
b.
c.
d.
1 0 .
test-jump
if
if-else
if-call
A ____________ decision structure is written inside another decision structure.
a.
b.
c.
d.
9 .
test-jump
if
if-else
if-call
You use a(n) __________ statement to write a dual alternative decision structure.
a.
b.
c.
d.
8 .
multibranch statement
single-alternative decision
dual-alternative decision
sequence
&&
||
!
either
A __________ is a Boolean variable that signals when some condition exists in the
program.
a. flag
b. signal
R e v ie w Q u e s t io n s
c. sentinel
d. siren
1 4 .
The __________ family of methods can be used to convert a string to a specific data
type without throwing an exception.
a.
b.
c.
d.
1 5 .
If several __________ controls exist in a GroupBox, only one of them may be selected
at a time.
a.
b.
c.
d.
1 6 .
0
1
−1
any value you specify
You can use the __________ property to determine whether an item is selected in a
ListBox.
a.
b.
c.
d.
2 0 .
else
default
case
otherwise
A ListBox’s index numbering starts at __________.
a.
b.
c.
d.
1 9 .
menu
branch
select
switch
The __________ section of a switch statement is branched to if none of the case
values match the test expression.
a.
b.
c.
d.
1 8 .
CheckBox
RadioButton
ListBox
SelectionButton
You use the __________ statement to create a multiple-alternative decision structure.
a.
b.
c.
d.
1 7 .
TryConvert
Parse
TryParse
SafeConvert
Index
SelectedItem
SelectedIndex
Items.SelectedIndex
The __________ property holds the item that is selected in a ListBox control.
a.
b.
c.
d.
Index
SelectedItem
SelectedIndex
Items.SelectedIndex
T r u e o r F a ls e
1 .
You can write any program using only sequence structures.
2 .
A single-alternative decision structure tests a condition and then takes one path if
the condition is true or another path if the condition is false.
3 .
The if-else statement is a dual-alternative decision structure.
261
262
C h a p te r 4
M a k in g D e c is io n s
4 .
A decision structure can be nested inside another decision structure.
5 .
A compound Boolean expression created with the && operator is true only when
both subexpressions are true.
6 .
The TryParse methods throw an exception if the string argument cannot
be converted.
7 .
M ultiple CheckBox controls in the same GroupBox can be selected at the same time.
8 .
The test expression in a switch statement can be a double or a decimal value.
9 .
If an item is not selected in a ListBox, the control’s SelectedIndex property will be
set to 0.
1 0 .
To store items in a ListBox, you add them to the control’s Text property.
S h o r t A n s w e r
1 .
What is meant by the term conditionally executed?
2 .
You need to test a condition and then execute one set of statements if the condition
is true. If the condition is false, you need to execute a different set of statements.
What structure will you use?
3 .
Briefly describe how the && operator works.
4 .
Briefly describe how the || operator works.
5 .
When determining whether a number is inside a range, which logical operator is it
best to use?
6 .
What is a flag and how does it work?
7 .
What are the two arguments that you pass to a TryParse method?
8 .
H ow do you determine in code whether a RadioButton control or a CheckBox control is selected?
9 .
H ow do you add items to a ListBox using the Properties window?
1 0 .
H ow can you read the selected item from a ListBox while preventing an exception
from occurring if no item is selected?
A lg o r it h m W o r k b e n c h
1 .
Write an if statement that assigns 20 to the variable y and assigns 40 to the variable
z if the variable x is greater than 100.
2 .
Write an if statement that assigns 0 to the variable b and assigns 1 to the variable c
if the variable a is less than 10.
3 .
Write an if-else statement that assigns 0 to the variable b if the variable a is less
than 10. Otherwise, it should assign 99 to the variable b.
4 .
Write nested decision structures that perform the following: if amount1 is greater
than 10 and amount2 is less than 100, display the greater of amount1 and amount2.
5 .
Write an if-else statement that displays “ Speed is normal” if the value of the
speed variable is at least 24 but no more than 56. If the speed variable’s value is
outside this range, display “ Speed is abnormal.”
6 .
Write an if-else statement that determines whether the value of the points
variable is less than 9 or greater than 51. If this is true, display “ Invalid points.”
Otherwise, display “ Valid points.”
P r o g r a m m in g P r o b le m s
7 .
Assume pointsTextBox is the name of a TextBox control and points is the name
of an int variable. Write an if-else statement that uses one of the TryParse
methods to convert the pointsTextBox control’s Text property to an int and stores
the result in the points variable. If the conversion is not successful, display an error
message in a message box.
8 .
Rewrite the following if-else-if statement as a switch statement.
if (selection == 1)
{
MessageBox.Show("You selected 1.");
}
else if (selection == 2)
{
MessageBox.Show("You selected 2.");
}
else if (selection == 3)
{
MessageBox.Show("You selected 3.");
}
else if (selection == 4)
{
MessageBox.Show("You selected 4.");
}
else
{
MessageBox.Show("Not good with numbers, eh?");
}
9 .
Assume nameListBox is a ListBox control. Write code that reads the selected item
from the ListBox. Be sure to prevent an exception from occurring in case no item
has been selected.
P r o g r a m m in g P r o b le m s
1 .
Ro man Nu meral Co n verter
Create an application that allows the user to enter an integer between 1 and 10 into
a TextBox control. The program should display the Roman numeral version of that
number. If the number is outside the range of 1 through 10, the program should
display an error message.
The following table lists the Roman numerals for the numbers 1 through 10.
Nu mb er
1
2
3
4
5
6
7
8
9
10
Ro man Nu meral
I
II
III
IV
V
VI
VII
VIII
IX
X
263
264
C h a p te r 4
M a k in g D e c is io n s
2 .
M a s s a n d We ig h t
Scientists measure an object’s mass in kilograms and its weight in N ewtons. If you
know the amount of mass of an object, you can calculate its weight, in N ewtons,
with the following formula:
VideoNot e
Solving the
M ass and
Weight
Problem
Weight = M ass × 9.8
Create an application that lets the user enter an object’s mass and then calculates its
weight. If the object weighs more than 1000 N ewtons, display a message indicating
that it is too heavy. If the object weighs less than 10 N ewtons, display a message
indicating that it is too light.
3 .
M a g ic D a te s
The date June 10, 1960, is special because when it is written in the following format,
the month times the day equals the year:
6/10/60
Create an application that lets the user enter a month (in numeric form), a day, and
a two-digit year. The program should then determine whether the month times the
day equals the year. If so, it should display a message saying the date is magic. Otherwise, it should display a message saying the date is not magic.
4 .
C o lo r M ix e r
The colors red, blue, and yellow are known as the primary colors because they cannot be made by mixing other colors. When you mix two primary colors, you get a
secondary color, as shown here:
•
•
•
When you mix red and blue, you get purple.
When you mix red and yellow, you get orange.
When you mix blue and yellow, you get green.
Create an application that lets the user select two primary colors from two different
sets of Radio buttons. The form should also have a M ix button. When the user
clicks the M ix button, the form’s background should change to the color that you
get when you mix the two selected primary colors. Figure 4-34 shows an example of
how the form should appear.
F ig u r e 4 -3 4
T h e Color Mixer f o r m
N ote: If the user picks the same color from both sets of Radio buttons, set the form’s
background to that color.
5 .
D is ta n c e C o n v e r te r
In the English measurement system, 1 yard equals 3 feet and 1 foot equals 12 inches.
Use this information to create an application that lets the user convert distances to
and from inches, feet, and yards.
P r o g r a m m in g P r o b le m s
Figure 4-35 shows an example of how the application’s form might appear. In the
example, the user enters the distance to be converted into a TextBox. A ListBox
allows the user to select the units being converted from, and another ListBox allows
the user to select the units being converted to.
F ig u r e 4 -3 5
T h e Dista nce Converter f o r m
N ote: Be sure to handle the situation where the user picks the same units from both
list boxes. The converted value will be the same as the value entered.
6 .
B o o k C lu b P o in ts
Serendipity Booksellers has a book club that awards points to its customers based
on the number of books purchased each month. The points are awarded as follows:
•
•
•
•
•
If a customer purchases 0 books, he or she earns 0 points.
If a customer purchases 1 book, he or she earns 5 points.
If a customer purchases 2 books, he or she earns 15 points.
If a customer purchases 3 books, he or she earns 30 points.
If a customer purchases 4 or more books, he or she earns 60 points.
Create an application that lets the user enter the number of books that he or she has
purchased this month and displays the number of points awarded.
7 .
S o ftw a r e S a le s
A software company sells a package that retails for $99. Quantity discounts are
given according to the following table:
Q u a n tity
10–19
20–49
50–99
100 or more
D is c o u n t
20%
30%
40%
50%
Create an application that lets the user enter the number of packages purchased.
The program should then display the amount of the discount (if any) and the total
amount of the purchase after the discount.
8 .
Bo d y Mass In d ex P ro gram En h an cemen t
In Programming Problem 6 in Chapter 3, you were asked to create an application
that calculates a person’s body mass index (BM I). Recall from that exercise that the
BM I is often used to determine whether a person is overweight or underweight for
their height. A person’s BM I is calculated with the following formula:
BM I = Weight × 703 ÷ H eight 2
265
266
C h a p te r 4
M a k in g D e c is io n s
In the formula, weight is measured in pounds and height is measured in inches.
Enhance the program so it displays a message indicating whether the person has
optimal weight, is underweight, or is overweight. A person’s weight is considered to
be optimal if his or her BM I is between 18.5 and 25. If the BM I is less than 18.5, the
person is considered to be underweight. If the BM I value is greater than 25, the person is considered to be overweight.
9 .
C h a n g e fo r a D o lla r G a m e
Create a change-counting game that gets the user to enter the number of coins
required to make exactly one dollar. The program should let the user enter the number of pennies, nickels, dimes, and quarters. If the total value of the coins entered is
equal to one dollar, the program should congratulate the user for winning the game.
Otherwise, the program should display a message indicating whether the amount
entered was more than or less than one dollar.
1 0 .
F a t P e r c e n ta g e C a lc u la to r
One gram of fat has 9 calories. If you know the number of fat grams in a particular
food, you can use the following formula to calculate the number of calories that
come from fat in that food:
Calories from fat = Fat grams × 9
If you know the food’s total calories, you can use the following formula to calculate
the percentage of calories from fat:
Percentage of calories from fat = Calories from fat ÷ Total calories
Create an application that allows the user to enter:
•
•
The total number of calories for a food item
The number of fat grams in that food item
The application should calculate and display:
•
•
The number of calories from fat
The percentage of calories that come from fat
Also, the application’s form should have a CheckBox that the user can check if he or
she wants to know whether the food is considered low fat. (If the calories from fat
are less than 30% of the total calories of the food, the food is considered low fat.)
Use the following test data to determine if the application is calculating properly:
C a lo r ie s a n d F a t
200 calories, 8 fat grams
150 calories, 2 fat grams
500 calories, 30 fat grams
P ercen tage F at
Percentage of calories from fat: 36%
Percentage of calories from fat: 12% (a low-fat food)
Percentage of calories from fat: 54%
N ote: M ake sure the number of calories and fat grams are not less than 0. Also, the
number of calories from fat cannot be greater than the total number of calories. If
that happens, display an error message indicating that either the calories or fat
grams were incorrectly entered.
1 1 .
Tim e C a lc u la to r
Create an application that lets the user enter a number of seconds and works
as follows:
•
There are 60 seconds in a minute. If the number of seconds entered by the user
is greater than or equal to 60, the program should display the number of minutes
in that many seconds.
P r o g r a m m in g P r o b le m s
1 2 .
•
There are 3,600 seconds in an hour. If the number of seconds entered by the
user is greater than or equal to 3,600, the program should display the number
of hours in that many seconds.
•
There are 86,400 seconds in a day. If the number of seconds entered by the user
is greater than or equal to 86,400, the program should display the number of
days in that many seconds.
Wo r k s h o p S e le c to r
The following table shows a training company’s workshops, the number of days of
each, and their registration fees.
Wo rk sh o p
H andling Stress
Time M anagement
Supervision Skills
N egotiation
H ow to Interview
Nu mb er o f Days
3
3
3
5
1
R e g is tr a tio n F e e
$1,000
$800
$1,500
$1,300
$500
The training company conducts its workshops in the six locations shown in the following table. The table also shows the lodging fees per day at each location.
L o c a tio n
Austin
Chicago
Dallas
Orlando
Phoenix
Raleigh
L o d g in g F e e s p e r D a y
$150
$225
$175
$300
$175
$150
When a customer registers for a workshop, he or she must pay the registration fee
plus the lodging fees for the selected location. For example, here are the charges to
attend the Supervision Skills workshop in Orlando:
R e g i s t r a t i o n : $1,500
L o d g i n g : $300 × 3 days = $900
T o t a l : $2,400
Create an application that lets the user select a workshop from one ListBox and a
location from another ListBox. When the user clicks a button, the application should
calculate and display the registration cost, the lodging cost, and the total cost.
267
This page intentionally left blank
C H A P T E R
L o o p s , F ile s , a n d R a n d o m
N u m b e rs
5
T O P I C S
5 .1
5 .1
M o r e a b o u t L is t B o x e s
5 .6
U s in g F ile s fo r D a t a S t o r a g e
5 .2
T h e while L o o p
5 .7
5 .3
T h e ++ a n d −− o p e r a t o r s
T h e O p e n F ile D ia lo g a n d
S a v e F ile D ia lo g C o n t r o ls
5 .4
T h e for L o o p
5 .8
R a n d o m N u m b e rs
5 .5
T h e do-while L o o p
5 .9
T h e L o a d E v e n t
M o r e a b o u t L is t B o x e s
C O N C E P T :
L is tB o x c o n tr o ls h a v e v a r io u s m e th o d s a n d p r o p e r tie s th a t y o u c a n u s e in
c o d e to m a n ip u la te th e L is tB o x ’s c o n te n ts .
In Chapter 4, we introduced the ListBox control, which displays a list of items and allows
the user to select one or more items from the list. In this chapter, we use ListBox controls
to display output. M any of the algorithms that you will see in this chapter generate lists of
data and then display those lists in ListBox controls.
Recall from Chapter 4 that you add items to a ListBox control’s Items property, and those
items are displayed in the ListBox. At design time, you can use the Properties window to
add items to the control’s Items property. You can also write code that adds items to a
ListBox control at run time. To add an item to a ListBox control with code, you call the
control’s Items.Add m e t h o d . H ere is the method’s general format:
ListBoxName.Items.Add(Item);
L istBoxN ame is the name of the ListBox control. Item is the value to be added to the
Items property. For example, in the Chap05 folder of this book’s Student Sample
Programs, you will find a project named N ame L ist. Figure 5-1 shows the application’s
form at run time. As shown in the image on the left, the ListBox’s name is nameListBox
and the Button control’s name is addButton . At run time, when you click the
addButton control, the names shown in the image on the right are added to the
nameListBox control.
269
270
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
F ig u r e 5 -1
T h e Na me List a p p l i c a t i o n
namesListBox
addButton
H ere is the code for the addButton_Click event handler:
1 private void addButton_Click(object sender, EventArgs e)
2 {
3
namesListBox.Items.Add("Chris");
4
namesListBox.Items.Add("Alicia");
5
namesListBox.Items.Add("Justin");
6
namesListBox.Items.Add("Holly");
7 }
You can add values of other types as well. In the Chap05 folder of the book’s Student
Sample Programs, you will find a project named N umber L ist. Figure 5-2 shows the application’s form. As shown in the image on the left, the ListBox’s name is numberListBox
and the Button control’s name is addButton. At run time, when you click the addButton
control, the numbers shown in the image on the right are added to the numberListBox
control.
F ig u r e 5 -2
T h e Number List a p p l i c a t i o n
numberListBox
addButton
H ere is the code for the addButton_Click event handler:
1 private void addButton_Click(object sender, EventArgs e)
2 {
3
numberListBox.Items.Add(10);
4
numberListBox.Items.Add(20);
5
numberListBox.Items.Add(30);
6
numberListBox.Items.Add(40);
7 }
T h e It e m s .C o u n t P r o p e r t y
ListBox controls have an I t e m s . C o u n t p r o p e r t y that reports the number of items stored in
the ListBox. If the ListBox is empty, the Items.Count property equals 0. For example,
5 .2
T h e while L o o p
assume an application has a ListBox control named employeesListBox. The following
if statement displays a message box if there are no items in the ListBox:
if (employeesListBox.Items.Count == 0)
{
MessageBox.Show("There are no items in the list!");
}
The Items.Count property holds an integer value. Assuming numEmployees is an int
variable, the following statement assigns the number of items in the employeesListBox
to the numEmployees variable:
numEmployees = employeesListBox.Items.Count;
T h e Items.Clear M e t h o d
ListBox controls have an Items.Clear m e t h o d that erases all the items in the Items property. H ere is the method’s general format:
ListBoxName.Items.Clear();
For example, assume an application has a ListBox control named employeesListBox.
The following statement clears all the items in the list:
employeesListBox.Items.Clear();
C h e c k p o in t
5.1 In code, how do you add an item to a ListBox control?
5.2 H ow do you determine the number of items that are stored in a ListBox control?
5.3 H ow do you erase the contents of a ListBox control?
5 .2
T h e while L o o p
C O N C E P T :
T h e while l o o p c a u s e s a s t a t e m e n t o r s e t o f s t a t e m e n t s t o r e p e a t a s l o n g
a s a B o o le a n e x p r e s s io n is tr u e .
The while loop gets its name from the way it works: While a Boolean expression is true,
do some task. The loop has two parts: (1) a Boolean expression that is tested for a true or
false value and (2) a statement or set of statements that is repeated as long as the Boolean
expression is true. Figure 5-3 shows the logic of a while loop.
F ig u r e 5 -3
T h e l o g i c o f a while l o o p
Boolean
Expression
False
True
Statement(s)
271
272
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
The diamond symbol represents the Boolean expression that is tested. N otice what happens if the expression is true: one or more statements are executed and the program’s
execution flows back to the point just above the diamond symbol. The Boolean expression is tested again, and if it is true, the process repeats. If the Boolean expression is false,
the program exits the loop. Each time the loop executes its statement or statements, we
say the loop is iterating, or performing an i t e r a t i o n .
H ere is the general format of the while loop:
while (BooleanExpression)
{
statement;
This set of statements is repeated
statement;
while the Boolean expression is true.
etc.
}
We refer to the first line as the while c l a u s e . The while clause begins with the word
while, followed by a Boolean expression that is enclosed in parentheses. Beginning on the
next line is a set of statements enclosed in curly braces. This block of statements is known
as the b o d y of the loop.
When the while loop executes, the Boolean expression is tested. If the Boolean expression
is true, the statements that appear in the body of the loop are executed, and then the loop
starts over. If the Boolean expression is false, the loop ends and the program resumes
execution at the statement immediately following the loop.
We say that the statements in the body of the loop are conditionally executed because they
are executed only under the condition that the Boolean expression is true. If you are writing
a while loop that has only one statement in its body, you do not have to enclose the statement inside curly braces. Such a loop can be written in the following general format:
while (BooleanExpression)
statement;
When a while loop written in this format executes, the Boolean expression is tested. If it
is true, the one statement that appears on the next line is executed, and then the loop
starts over. If the Boolean expression is false, however, the loop ends.
Although the curly braces are not required when there is only one statement in the loop’s
body, it is still a good idea to use them, as shown in the following general format:
while (BooleanExpression)
{
statement;
}
When we discussed the various if statements in Chapter 4, we mentioned that this is a
good style of programming because it cuts down on errors. If you have more than one
statement in the body of a loop, those statements must be enclosed in curly braces. If you
get into the habit of always enclosing the conditionally executed statements in a set of
curly braces, it’s less likely that you will forget them.
You should also notice that the statements in the body of the loop are indented. As with
if statements, this indentation makes the code easier to read and debug. By indenting the
statements in the body of the loop, you visually set them apart from the surrounding code.
Let’s look at an example. In the Chap05 folder of this book’s Student Sample Programs,
you will find a project named while L oop D emo. Figure 5-4 shows the application’s form
at run time. As shown in the image on the left, the Button control’s name is goButton.
5 .2
F ig u r e 5 -4
T h e while L o o p
T h e while Loop Demo a p p l i c a t i o n
goButton
A t r u n t i m e , w h e n y o u c l i c k t h e goButton c o n t r o l , t h e m e s s a g e b o x s h o w n i n t h e i m a g e
o n t h e r i g h t i s d i s p l a y e d . W h e n y o u c l i c k t h e OK b u t t o n t o c l o s e t h e m e s s a g e b o x , a n o t h e r
id e n tic a l m e s s a g e b o x is d is p la y e d . T h e m e s s a g e b o x is d is p la y e d a to ta l o f fiv e tim e s .
H e r e i s t h e c o d e f o r t h e goButton_Click e v e n t h a n d l e r :
1 private void goButton_Click(object sender, EventArgs e)
2 {
3
// Declare a variable to count the loop iterations.
4
int count = 1;
5
6
// Display "Hello" in a message box five times.
7
while (count <= 5)
8
{
9
// Display the message box.
10
MessageBox.Show("Hello");
11
12
// Add one to count.
13
count = count + 1;
14
}
15 }
L e t ’ s t a k e a c l o s e r l o o k a t t h i s c o d e . I n l i n e 4 a n int v a r i a b l e n a m e d count i s d e c l a r e d a n d
i n i t i a l i z e d w i t h t h e v a l u e 1 . A while l o o p b e g i n s i n l i n e 7 . N o t i c e t h a t t h e while l o o p
t e s t s t h e e x p r e s s i o n count <= 5. T h e s t a t e m e n t s i n t h e b o d y o f t h e while l o o p r e p e a t a s
l o n g a s t h e count v a r i a b l e i s l e s s t h a n o r e q u a l t o 5 . I n s i d e t h e b o d y o f t h e l o o p , l i n e
1 0 d i s p l a y s “ H e l l o ” i n a m e s s a g e b o x , a n d t h e n l i n e 1 3 a d d s o n e t o t h e count v a r i a b l e .
T h is is th e la s t s ta te m e n t in th e b o d y o f th e lo o p , s o a fte r it e x e c u te s , th e lo o p s ta r ts o v e r .
It te s ts th e B o o le a n e x p r e s s io n a g a in , a n d if it is tr u e , th e s ta te m e n ts in th e b o d y o f th e
l o o p a r e e x e c u t e d . T h i s c y c l e r e p e a t s u n t i l t h e B o o l e a n e x p r e s s i o n count <= 5 i s f a l s e , a s
illu s tr a te d in F ig u r e 5 -5 . A flo w c h a r t fo r th e lo o p is s h o w n in F ig u r e 5 -6 .
F ig u r e 5 -5
T h e while L o o p
1 Test this Boolean expression.
3 After executing the
body of the loop,
start over.
while (count <= 5)
{
// Display the message box.
MessageBox.Show("Hello");
// Add one to count.
count = count + 1;
}
2
If the Boolean expression
is true, perform these
statements. Otherwise,
the loop ends.
273
274
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
F ig u r e 5 -6
F l o w c h a r t f o r t h e while L o o p
count
<= 5
True
Display “Hello”
Add 1 to count
False
T h e while L o o p I s a P r e t e s t L o o p
The while loop is known as a p r e t e s t l o o p , which means it tests its condition before
performing an iteration. Because the test is done at the beginning of the loop, you usually
have to perform some steps prior to the loop to make sure that the loop executes at least
once. N otice the declaration of the count variable in the while L oop D emo program:
int count = 1;
The count variable is initialized with the value 1. If count had been initialized with a
value that is greater than 5, as shown in the following program sample, the loop would
never execute:
1 private void goButton_Click(object sender, EventArgs e)
2 {
3
// Declare a variable to count the loop iterations.
4
int count = 6;
5
6
// This loop will never iterate!
7
while (count <= 5)
8
{
9
// Display the message box.
10
MessageBox.Show("Hello");
11
12
// Add one to count.
13
count = count + 1;
14
}
15 }
An important characteristic of the while loop is that the loop will never iterate if the
Boolean expression is false to start with. If you want to be sure that a while loop executes
the first time, you must initialize the relevant data in such a way that the Boolean expression starts out as true.
C o u n t e r V a r ia b le s
In the while L oop D emo application, the variable count is initialized with the value 1,
and then 1 is added to the variable count during each loop iteration. The loop executes as
long as count is less than or equal to 5. The variable count is used as a c o u n t e r v a r i a b l e ,
which means it is regularly incremented in each loop iteration. In essence, the count variable keeps count of the number of iterations the loop has performed. Counter variables
are commonly used to control the number of times that a loop iterates.
Tutorial 5-1 will give you some practice writing a loop and using a counter variable. In
the tutorial, you will write a while loop that calculates the amount of interest earned by
a bank account each month for a number of months.
5 .2
T h e while L o o p
T u t o r ia l 5 -1 :
U s in g a L o o p t o C a lc u la t e a n A c c o u n t B a la n c e
VideoNot e
T u to r ia l 5 -1 :
Using a Loop
to Calculate
an Account
Balance
In this tutorial, you complete the Ending Balance application. The project has already
been started for you and is located in the Chap05 folder of this book’s Student Sample
Programs. The application’s form is shown in Figure 5-7.
F ig u r e 5 -7
T h e Ending Ba la nce f o r m
startingBalTextBox
monthsTextBox
endingBalanceLabel
calculateButton clearButton
exitButton
When you complete the application, it will allow the user to enter an account’s starting
balance into the startingBalTextBox control and the number of months that the
account will be left to earn interest into the monthsTextBox control. When the user clicks
the calculateButton control, the application calculates the account’s balance at the
e n d o f th e tim e p e r io d . T h e a c c o u n t’s m o n th ly in te r e s t r a te is 0 .0 0 5 , a n d th e in te r e s t is
c o m p o u n d e d m o n th ly .
S t e p 1 :
S t a r t V i s u a l S t u d i o . O p e n t h e p r o j e c t n a m e d Ending Balance i n t h e Chap05
fo ld e r o f th is b o o k ’s S tu d e n t S a m p le P r o g r a m s .
S t e p 2 :
O p e n t h e F o r m 1 f o r m i n t h e D esigner. T h e f o r m i s s h o w n , a l o n g w i t h t h e n a m e s
o f th e im p o r ta n t c o n tr o ls , in F ig u r e 5 -7 .
S t e p 3 :
N o w y o u w ill c r e a te th e C lic k e v e n t h a n d le r s fo r th e B u tto n c o n tr o ls . A t th e e n d
o f th is tu to r ia l, P r o g r a m 5 -1 s h o w s th e c o m p le te d c o d e fo r th e fo r m . Y o u w ill
b e in s tr u c te d to r e fe r to P r o g r a m 5 -1 a s y o u w r ite th e e v e n t h a n d le r s .
I n t h e D esigner, d o u b l e - c l i c k t h e calculateButton c o n t r o l . T h i s o p e n s
t h e c o d e e d i t o r , a n d y o u w i l l s e e a n e m p t y e v e n t h a n d l e r n a m e d calculateButton_
Click. C o m p l e t e t h e calculateButton_Click e v e n t h a n d l e r b y t y p i n g t h e c o d e
s h o w n in lin e s 2 2 – 5 9 in P r o g r a m 5 -1 . L e t’s ta k e a c lo s e r lo o k a t th e c o d e :
L i n e 2 3 : T h i s s t a t e m e n t d e c l a r e s a c o n s t a n t decimal n a m e d INTEREST_RATE,
s e t to th e v a lu e 0 .0 0 5 . T h is is th e m o n th ly in te r e s t r a te .
L in e s 2 6 – 2 8 : T h e s e s ta te m e n ts d e c la r e th e fo llo w in g v a r ia b le s :
• balance, a decimal v a r i a b l e t o h o l d t h e a c c o u n t b a l a n c e .
• months, a n int v a r i a b l e t o h o l d t h e n u m b e r o f m o n t h s t h a t t h e a c c o u n t w i l l
b e le ft to e a r n in te r e s t.
• count, a n int t h a t i s u s e d t o c o u n t t h e m o n t h s a s a l o o p i t e r a t e s . N o t i c e t h a t
t h e count v a r i a b l e i s i n i t i a l i z e d w i t h t h e v a l u e 1 .
275
276
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
L i n e 3 1 : This if statement tries to convert startingBalTextBox.Text to a
decimal. If the conversion is successful, the result is stored in the balance
variable, and the program continues executing at line 33. If the conversion is
not successful, the program jumps to the else clause in line 55, and line 58
displays the error message I nvalid value for starting balance.
L i n e 3 4 : This if statement tries to convert monthsTextBox.Text to an int. If
the conversion is successful, the result is stored in the months variable, and the
program continues executing at line 36. If the conversion is not successful,
t h e p r o g r a m j u m p s t o t h e else c l a u s e i n l i n e 4 9 , a n d l i n e 5 2 d i s p l a y s t h e e r r o r
m e s s a g e I nvalid value for months.
L i n e 3 7 : T h i s i s t h e b e g i n n i n g o f a while l o o p . T h e l o o p e x e c u t e s a s l o n g a s t h e
e x p r e s s i o n count <= months i s t r u e .
L in e s 3 9 – 4 3 : T h e s e s ta te m e n ts a r e th e b o d y o f th e lo o p . L in e 4 0 c a lc u la te s th e
m o n t h l y i n t e r e s t a n d a d d s i t t o t h e balance v a r i a b l e . L i n e 4 3 a d d s 1 t o t h e
count v a r i a b l e .
L in e 4 7 : T h is s ta te m e n t e x e c u te s a fte r th e lo o p h a s fin is h e d a ll o f its ite r a tio n s .
I t c o n v e r t s t h e v a l u e o f t h e balance v a r i a b l e t o a s t r i n g ( f o r m a t t e d a s
c u r r e n c y ) a n d a s s i g n s t h e r e s u l t i n g s t r i n g t o t h e endingBalanceLabel
c o n tr o l’s T e x t p r o p e r ty .
S t e p 4 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e clearButton
c o n tr o l. In th e c o d e e d ito r y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
clearButton_Click. C o m p l e t e t h e clearButton_Click e v e n t h a n d l e r b y
ty p in g th e c o d e s h o w n in lin e s 6 4 – 7 0 in P r o g r a m 5 -1 .
S t e p 5 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e exitButton
c o n tr o l. In th e c o d e e d ito r y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
exitButton_Click. C o m p l e t e t h e exitButton_Click e v e n t h a n d l e r b y t y p i n g
th e c o d e s h o w n in lin e s 7 5 – 7 6 in P r o g r a m 5 -1 .
S t e p 6 :
S a v e th e p r o je c t. T h e n , p r e s s
o n t h e k e y b o a r d , o r c l i c k t h e Start D ebugging
b u tto n ( ) o n th e to o lb a r to c o m p ile a n d r u n th e a p p lic a tio n .
F i r s t , e n t e r 1000 a s t h e s t a r t i n g b a l a n c e a n d 48 a s t h e n u m b e r o f m o n t h s . C l i c k
t h e Calculate Average b u t t o n a n d $ 1 , 2 7 0 . 4 9 s h o u l d a p p e a r a s t h e e n d i n g
b a la n c e . T h in k a b o u t th e v a lu e th a t y o u e n te r e d fo r th e n u m b e r o f m o n th s .
H o w m a n y t i m e s d i d t h e while l o o p i n l i n e 3 6 i t e r a t e ? ( A n s w e r : 4 8 t i m e s . )
N e x t , c l i c k t h e Clear b u t t o n t o c l e a r t h e T e x t B o x e s a n d t h e e n d i n g b a l a n c e .
N o w , e n t e r 100 a s t h e s t a r t i n g b a l a n c e a n d 1 a s t h e n u m b e r o f m o n t h s . C l i c k
t h e Calculate Average b u t t o n a n d $ 1 0 0 . 5 0 s h o u l d a p p e a r a s t h e e n d i n g b a l a n c e .
H o w m a n y t i m e s d i d t h e while l o o p i t e r a t e t h i s t i m e ? ( A n s w e r : 1 t i m e . )
C o n tin u e to te s t th e a p p lic a tio n a s y o u w is h . W h e n y o u a r e fin is h e d , c lic k th e
Exit b u t t o n a n d t h e f o r m s h o u l d c l o s e . ( I f y o u p l a n t o c o n t i n u e t o t h e n e x t
tu to r ia l, le a v e th is p r o je c t o p e n in V is u a l S tu d io .)
P r o g r a m 5 -1
C o m p l e t e d F o r m 1 c o d e f o r t h e Ending Ba la nce a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
5 .2
T h e while L o o p
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Ending_Balance
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void calculateButton_Click(object sender, EventArgs e)
21
{
22
// Constant for the monthly interest rate.
23
const decimal INTEREST_RATE = 0.005m;
24
25
// Local variables
26
decimal balance;
// The account balance
27
int months;
// The number of months
28
int count = 1;
// Loop counter, initialized with 1
29
30
// Get the starting balance.
31
if (decimal.TryParse(startingBalTextBox.Text, out balance))
32
{
33
// Get the number of months.
34
if (int.TryParse(monthsTextBox.Text, out months))
35
{
36
// The following loop calculates the ending balance.
37
while (count <= months)
38
{
39
// Add this month's interest to the balance.
40
balance = balance + (INTEREST_RATE * balance);
41
42
// Add one to the loop counter.
43
count = count + 1;
44
}
45
46
// Display the ending balance.
47
endingBalanceLabel.Text = balance.ToString("c");
48
}
49
else
50
{
51
// Invalid number of months was entered.
52
MessageBox.Show("Invalid value for months.");
53
}
54
}
55
else
56
{
57
// Invalid starting balance was entered.
58
MessageBox.Show("Invalid value for starting balance.");
59
}
60
}
61
private void clearButton_Click(object sender, EventArgs e)
62
63
{
64
// Clear the TextBoxes and the endingBalanceLabel control.
65
startingBalTextBox.Text = "";
277
278
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
66
67
68
69
70
71
72
73
74
75
76
77
78
79 }
monthsTextBox.Text = "";
endingBalanceLabel.Text = "";
// Reset the focus.
startingBalTextBox.Focus();
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
T u t o r ia l 5 -2 :
E n h a n c i n g t h e Ending Ba la nce A p p l i c a t i o n
VideoNot e
T u to r ia l 5 -2 :
Enhancing
the Ending
Balance
Application
In this tutorial, you enhance the Ending Balance application that you created in Tutorial
5-1. First, add a ListBox control to the application’s form, as shown in Figure 5-8. Then
modify the calculateButton_Click event handler so it displays each month’s ending
balance in the ListBox. Figure 5-9 shows an example of how the form will appear at run
time, when the user has entered 1000 for the starting balance and 8 for the months.
F ig u r e 5 -8
T h e m o d i f i e d Ending Ba la nce f o r m
detailListBox
S t e p 1 :
Start Visual Studio and open the Ending Balance project that you completed in
Tutorial 5-1.
S t e p 2 :
Enlarge the form so it is roughly the size shown in Figure 5-8. (310 pixels wide
by 325 pixels high should be sufficient.)
S t e p 3 :
Create a ListBox control named detailListBox. Resize the ListBox as shown
in Figure 5-8.
5 .2
F ig u r e 5 -9
S t e p 4 :
T h e while L o o p
E x a m p le o u tp u t
Switch to the code editor and insert the code shown in lines 42–45 in Program
5-2. (The new lines of code are shown in bold.) The statement in lines 43–45
adds a string to the detailListBox control. If you examine the statement
carefully, you will see that it uses concatenation to create a string in the
following format:
The ending balance for month count is balance.
In the actual string that is created, count will be the value of the count variable
and balance will be the value of the balance variable, formatted as currency.
S t e p 5 :
Find the clearButton_Click event handler in the code editor. Update the
comment as shown in lines 69–70, and insert the line of code shown in line 74.
(The lines are shown in bold.) The statement in line 74 clears the contents of the
detailListBox control.
S t e p 6 :
Save the project. Then, press
on the keyboard or click the Start D ebugging
button ( ) on the toolbar to compile and run the application.
As shown in Figure 5-9, enter 1000 as the starting balance and 8 as the number
of months. Click the Calculate Average button. Your output should look like
that shown in Figure 5-9. Click the Clear button and enter any other values you
wish to test the application further. When you are finished, click the Exit button
and the form should close.
P r o g r a m 5 -2
C o m p l e t e d F o r m 1 c o d e f o r t h e Ending Ba la nce a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
279
280
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
11 namespace Ending_Balance
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void calculateButton_Click(object sender, EventArgs e)
21
{
22
// Constant for the monthly interest rate.
23
const decimal INTEREST_RATE = 0.005m;
24
25
// Local variables
26
decimal balance;
// The account balance
27
int months;
// The number of months
28
int count = 1;
// Loop counter, initialized with 1
29
30
// Get the starting balance.
31
if (decimal.TryParse(startingBalTextBox.Text, out balance))
32
{
33
// Get the number of months.
34
if (int.TryParse(monthsTextBox.Text, out months))
35
{
36
// The following loop calculates the ending balance.
37
while (count <= months)
38
{
39
// Add this month's interest to the balance.
40
balance = balance + (INTEREST_RATE * balance);
41
42
// Display this month's ending balance.
43
detailListBox.Items.Add("The ending balance " +
44
"for month " + count + " is " +
45
balance.ToString("c"));
46
47
// Add one to the loop counter.
48
count = count + 1;
49
}
50
51
// Display the ending balance.
52
endingBalanceLabel.Text = balance.ToString("c");
53
}
54
else
55
{
56
// Invalid number of months was entered.
57
MessageBox.Show("Invalid value for months.");
58
}
59
}
60
else
61
{
62
// Invalid starting balance was entered.
63
MessageBox.Show("Invalid value for starting balance.");
64
}
65
}
66
67
private void clearButton_Click(object sender, EventArgs e)
68
{
5 .2
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86 }
T h e while L o o p
// Clear the TextBoxes, the endingBalanceLabel control,
// and the ListBox.
startingBalTextBox.Text = "";
monthsTextBox.Text = "";
endingBalanceLabel.Text = "";
detailListBox.Items.Clear();
// Reset the focus.
startingBalTextBox.Focus();
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
In fin it e L o o p s
In all but rare cases, loops must contain a way to terminate within themselves. This means
that something inside the loop must eventually make the loop’s Boolean expression false.
The loop in Program 5-2 stops when the expression count <= months is false. If a loop
does not have a way of stopping, it is called an infinite loop. An infinite loop continues to
repeat until the program is interrupted. Infinite loops usually occur when the programmer
forgets to write code inside the loop that makes the test condition false. In most circumstances, you should avoid writing infinite loops.
The following code sample demonstrates an infinite loop. In line 1, the count variable is
declared and initialized with the value 1. The while loop that begins in line 5 executes as
long as count is less than or equal to 5. There is no code inside the loop to change the
count variable’s value, so the expression count <= 5 in line 5 is always true. As a consequence, the loop has no way of stopping.
1 // Declare a variable to count the loop iterations.
2 int count = 1;
3
4 // How many times will this loop iterate?
5 while (count <= 5)
6 {
7
// Display the message box.
8
MessageBox.Show("Hello");
9 }
C h e c k p o in t
5.4 What is a loop iteration?
5.5 What is a counter variable?
5.6 What is a pretest loop?
5.7 Does the while loop test its condition before or after it performs an iteration?
5.8 What is an infinite loop?
281
282
C h a p te r 5
5 .3
L o o p s , F ile s , a n d R a n d o m N u m b e r s
T h e ++ a n d −− o p e r a t o r s
C O N C E P T :
T o in c r e m e n t a v a r ia b le m e a n s to in c r e a s e its v a lu e , a n d to d e c r e m e n t a
v a r ia b le m e a n s to d e c r e a s e its v a lu e . C # p r o v id e s s p e c ia l o p e r a to r s to
in c r e m e n t a n d d e c r e m e n t v a r ia b le s .
To i n c r e m e n t a variable means to increase its value and to d e c r e m e n t a variable means to
decrease its value. Both of the following statements increment the variable num by 1:
num = num + 1;
num += 1;
And num is decremented by 1 in both the following statements:
num = num − 1;
num −= 1;
Incrementing and decrementing is so commonly done in programs that C# provides a set
of simple unary operators designed just for incrementing and decrementing variables. The
increment operator is ++, and the decrement operator is −−. The following statement uses
the ++ operator to add 1 to num:
num++;
After this statement executes, the value of num is increased by 1. The following statement
uses the −− operator to subtract 1 from num:
num−−;
N O T E : The ++ operator is pronounced “ plus plus,” and the −− operator is
pronounced “ minus minus.” The expression num++ is pronounced “ num plus plus,”
and the expression num−− is pronounced “ num minus minus.”
In these examples, we have written the ++ and −− operators after their operands (or, on
the right side of their operands). This is called p o s t f i x m o d e . The operators can also be
written before (or, on the left side) of their operands, which is called p r e f i x m o d e . H ere
are examples:
++num;
−−num;
When you write a simple statement to increment or decrement a variable, such as the ones
shown here, it doesn’t matter if you use prefix mode or postfix mode. The operators do
the same thing in either mode; however, if you write statements that mix these operators
with other operators or with other operations, there is a difference in the way the two
modes work. Such complex code can be difficult to understand and debug. When we use
the increment and decrement operators, we will do so only in ways that are straightforward and easy to understand, such as the statements previously shown.
We introduce these operators at this point because they are commonly used in loops. The
following code segment shows an example. In the code, the count variable is initialized
with the value 1. The while loop that begins in line 5 iterates as long as count is less than
or equal to 5. The statement in line 11 increments count. The loop will iterate 5 times.
1 // Declare a variable to count the loop iterations.
2 int count = 1;
5 .4
T h e for L o o p
3
4 // Display "Hello" in a message box five times.
5 while (count <= 5)
6 {
7
// Display the message box.
8
MessageBox.Show("Hello");
9
10
// Increment count.
11
count++;
12 }
In the next section, which discusses the for loop, you will see these operators used often.
C h e c k p o in t
5.9 What messages will the following code sample display?
int number = 5;
number++;
MessageBox.Show(number.ToString());
number−−;
MessageBox.Show(number.ToString());
5.10 H ow many times will the following loop iterate?
int count = 0;
while (count < 4)
{
MessageBox.Show(count.ToString());
count++;
}
5 .4
T h e for L o o p
C O N C E P T :
T h e for l o o p i s i d e a l f o r p e r f o r m i n g a k n o w n n u m b e r o f i t e r a t i o n s .
The for loop is specifically designed for situations requiring a counter variable to control the number of times that a loop iterates. When you write a for loop, you specify
three actions:
• Initialization: This action takes place when the loop begins. It happens only once.
• Test: A Boolean expression is tested. If the expression is true, the loop iterates.
Otherwise, the loop stops.
• Update: This action takes place at the end of each loop iteration.
Figure 5-10 shows how these three actions are used in the logic of a for loop.
H ere is the general format of the for loop:
for (InitializationExpression; TestExpression; UpdateExpression)
{
statement;
statement;
etc.
}
The statements that appear inside the curly braces are the body of the loop. These are the
statements that are executed each time the loop iterates. As with other control structures,
283
284
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
F ig u r e 5 -1 0
L o g i c o f a for l o o p
Initialization
Boolean expression
True
Statement(s)
False
Update
the curly braces are optional if the body of the loop contains only one statement, as
shown in the following general format:
for (InitializationExpression; TestExpression; UpdateExpression)
statement;
The first line of the for loop is the loop header. After the key word for, there are three
expressions inside the parentheses, separated by semicolons. (N otice that there is not a
semicolon after the third expression.)
The first expression is the i n i t i a l i z a t i o n e x p r e s s i o n . It is normally used to initialize a
counter variable to its starting value. This is the first action performed by the loop, and
it is only done once. The second expression is the t e s t e x p r e s s i o n . This is a Boolean
expression that controls the execution of the loop. As long as this expression is true, the
body of the for loop will repeat. The for loop is a pretest loop, so it evaluates the test
expression before each iteration. The third expression is the u p d a t e e x p r e s s i o n . It executes at the end of each iteration. Typically, this is a statement that increments the
loop’s counter variable.
Let’s assume that count is an int variable that has already been declared. H ere is an
example of a simple for loop that displays "Hello" in a message box 5 times:
for (count = 1; count <= 5; count++)
{
MessageBox.Show("Hello");
}
In this loop, the initialization expression is count = 1, the test expression is count <= 5,
and the increment expression is count++. The body of the loop has one statement, which
is the call to MessageBox.Show method. This is a summary of what happens when this
loop executes:
5 .4
T h e for L o o p
1. The initialization expression count = 1 is executed. This assigns 1 to the
count variable.
2. The expression count <= 5 is tested. If the expression is true, continue with Step 3.
Otherwise, the loop is finished.
3. The statement MessageBox.Show("Hello"); is executed.
4. The update expression count++ is executed. This adds 1 to the count variable.
5. Go back to Step 2.
Figure 5-11 illustrates this sequence of events. N otice that Steps 2–4 are repeated as long
as the test expression is true. Figure 5-12 shows the logic of the loop as a flowchart.
F ig u r e 5 -1 1
S e q u e n c e o f e v e n t s i n t h e for l o o p
Step 1: Perform the initialization.
Step 2: Evaluate the test expression. If
it is true, go to step 3. Otherwise, the
loop stops.
for (count = 1; count <= 5; count++)
{
MessageBox.Show("Hello");
}
Step 3: Execute the body
of the loop.
Step 4: Perform the update expression,
then go back to step 2.
F ig u r e 5 -1 2
L o g i c o f t h e for l o o p
counter = 1
counter <= 5
True
Display "Hello"
Add 1 to counter
False
Let’s look at a complete application that uses a for loop. In the Chap05 folder of this
book’s Student Sample Programs, you will find a project named Squares. The purpose of
the application is to display the numbers 1–10 and their squares. Figure 5-13 shows the
application’s form at run time. As shown in the image on the left, the ListBox’s name is
outputListBox and the Button control’s name is goButton. At run time, when you click
the goButton control, the outputListBox control displays the program’s output, as
shown in the image on the right.
285
286
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
F ig u r e 5 -1 3
T h e Squa res a p p l i c a t i o n
outputListBox
goButton
H ere is the code for the goButton_Click event handler:
1 private void goButton_Click(object sender, EventArgs e)
2 {
3
// Constant for the maximum number
4
const int MAX_VALUE = 10;
5
6
// Loop counter
7
int number;
8
9
// Display the list of numbers and their squares.
10
for (number = 1; number <= MAX_VALUE; number++)
11
{
12
outputListBox.Items.Add("The square of " +
13
number + " is " + (number * number));
14
}
15 }
Let’s take a closer look at the code:
• L i n e 4 declares an int constant named MAX_VALUE, set to the value 10. This is the
maximum number that we will use to calculate a square.
• L i n e 7 declares an int variable named number. This variable is used both as a
counter variable and in the calculation of squares.
• L i n e 1 0 is the beginning of a for loop. You can see from this line that the loop
works in the following way:
I n i t i a l i z a t i o n : The number variable is initialized with the value 1.
T e s t : The expression number <= MAX_VALUE is tested at the beginning of
each iteration.
U p d a t e : The expression number++ is executed at the end of each iteration.
• Since the MAX_VALUE constant is set to the value 10, the number variable will be
assigned the values 1 through 10 as the loop iterates.
• L i n e s 1 2 a n d 1 3 : This statement adds a line to the ListBox showing the current value
of the number variable, and the square of that value.
T h e for L o o p I s a P r e t e s t L o o p
Because the for loop tests its Boolean expression before it performs an iteration, it is a
pretest loop. It is possible to write a for loop in such a way that it will never iterate. H ere
is an example:
for (count = 6; count <= 5; count++)
{
MessageBox.Show("Hello");
}
5 .4
T h e for L o o p
Because the variable count is initialized to a value that makes the Boolean expression
false from the beginning, this loop terminates as soon as it begins.
D e c la r in g t h e C o u n t e r V a r ia b le
in t h e In it ia liz a t io n E x p r e s s io n
N ot only may the counter variable be initialized in the initialization expression, but it may
also be declared there. The following code shows an example:
for (int count = 1; count <= 5; count++)
{
MessageBox.Show("Hello");
}
In this loop, the count variable is both declared and initialized in the initialization expression. If the variable is used only in the loop, it makes sense to define it in the loop header.
This makes the variable’s purpose clearer.
When a variable is declared in the initialization expression of a for loop, the scope of the
variable is limited to the loop. This means you cannot access the variable in statements
outside the loop. For example, the following code would cause a compiler error because
the statement in line 6 cannot access the count variable.
1 for (int count = 1; count <= 5; count++)
2 {
3
MessageBox.Show("Hello");
4 }
5
6 MessageBox.Show("The value of count is " + count);
O t h e r F o r m s o f t h e U p d a t e E x p r e s s io n
In the update expression, the counter variable is typically incremented by 1. This makes it
convenient to use the ++ operator in the increment expression. This is not a requirement,
however. You can write virtually any expression you wish as the update expression. For
example, the following loop increments count by 10:
for (int count = 0; count <= 100; count += 10)
{
MessageBox.Show(count.ToString());
}
N otice that in this example the increment expression is count += 10. This means that at
the end of each iteration, 10 is added to count. During the first iteration count is set to
0, during the second iteration count is set to 10, during the third iteration count is set to
20, and so forth.
C o u n t in g B a c k w a r d b y D e c r e m e n t in g
t h e C o u n t e r V a r ia b le
Although the counter variable is usually incremented in a count-controlled loop, you can
alternatively decrement the counter variable. For example, look at the following code:
for (int count = 10; count >= 0; count−−)
{
MessageBox.Show(count.ToString());
}
MessageBox.Show("Blastoff!");
287
288
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
In this loop, the count variable is initialized with the value 10. The loop iterates as long as
count is greater than or equal to 0. At the end of each iteration, count is decremented by 1.
During the first iteration count is 10, during the second iteration count is 9, and so forth.
If this were in an actual program, it would display the numbers 10, 9, 8, and so forth,
down to 0, and then display Blastoff!
A v o id in g M o d ify in g t h e C o u n t e r V a r ia b le
i n t h e B o d y o f t h e for L o o p
Be careful not to place a statement that modifies the counter variable in the body of the for
loop. All modifications of the control variable should take place in the update expression,
which is automatically executed at the end of each iteration. If a statement in the body of
the loop also modifies the counter variable, the loop probably will not terminate when you
expect it to. The following loop, for example, increments count twice for each iteration:
for (int count = 1; count <= 10; count++)
{
MessageBox.Show(count.ToString());
count++; // Wrong!
}
You have seen several examples of the for loop. Tutorial 5-3 gives you an opportunity to
write one. In the tutorial you will complete an application that uses a for loop to convert
a series of measurements from the metric system to the English system.
T u t o r ia l 5 -3 :
U s i n g t h e for L o o p
VideoNot e
T u to r ia l 5 -3 :
Using the
for Loop
Your friend Amanda just inherited a European sports car from her uncle. Amanda lives in
the United States, and she is afraid she will get a speeding ticket because the car’s speedometer works in kilometers per hour. She has asked you to write a program that displays
a table of speeds in kilometers per hour with their values converted to miles per hour. The
formula for converting kilometers per hour to miles per hour is:
M PH = KPH * 0.6214
In the formula, M PH is the speed in miles per hour and KPH is the speed in kilometers
per hour.
The table that your program displays should show speeds from 60 kilometers per hour
through 130 kilometers per hour, in increments of 10, along with their values converted
to miles per hour. The table should look something like this:
KP H
MP H
60
37.284
70
43.498
80
49.712
etc. . . .
After thinking about this table of values, you decide that you will write a for loop that
uses a counter variable to hold the kilometers-per-hour speeds. The counter’s starting
value will be 60, its ending value will be 130, and you will increase its value by 10 in the
5 .4
T h e for L o o p
update expression. Inside the loop you will use the counter variable to calculate a speed in
miles per hour.
The project, which is named Speed Converter, has already been started for you. It is
located in the Chap05 folder of this book’s Student Sample Programs. The application’s
form, at run time, is shown in Figure 5-14. The image on the left in the figure shows the
names of the controls. The image on the right shows how the form appears after the user
clicks the D isplay Speeds button.
F ig u r e 5 -1 4
T h e Speed Converter f o r m
outputListBox
displayButton
exitButton
S t e p 1 :
Start Visual Studio. Open the project named Speed Converter in the Chap05
folder of this book’s Student Sample Programs.
S t e p 2 :
Open the Form1 form in the D esigner.
S t e p 3 :
In the D esigner, double-click the displayButton control. This opens the code
editor, and you will see an empty event handler named displayButton_
Click. Complete the displayButton_Click event handler by typing the
code shown in lines 22–41 in Program 5-3 (at the end of this tutorial). Let’s
take a closer look at the code:
L i n e s 2 3 – 2 6 : These statements declare the following named constants:
• START_SPEED, an int constant set to 60. This is the starting speed for
the list of conversions and the value with which the loop’s counter variable is initialized.
• END_SPEED, an int constant set to 130. This is the ending speed for the list of
conversions. When the counter variable exceeds this value, the loop stops.
• INTERVAL, an int constant set to 10. This is the amount that you add to
loop’s counter variable after each iteration.
• CONVERSION_FACTOR, a double constant set to 0.6214. This is the conversion factor that you use in the formula to convert KPH to M PH .
L i n e s 2 9 – 3 0 : These statements declare the following variables:
• kph, an int variable to hold the speed in kilometers per hour.
• mph, a double variable to hold the speed in miles per hour.
L i n e 3 3 : This is the beginning of a for loop that works in the following way:
I n i t i a l i z a t i o n : The kph variable is initialized with the value of START_SPEED,
which is 60.
289
290
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
T e s t : The expression kph <= END_SPEED is tested at the beginning of each iteration.
U p d a t e : The expression kph += INTERVAL is executed at the end of each iteration. This adds the value of INTERVAL (which is 10) to the kph variable.
As the loop iterates, the kph variable is assigned the values 60, 70, 80, and so
forth, through 130.
L i n e 3 6 : This statement converts the value of the kph variable to miles per hour
and assigns the result to the mph variable.
L i n e s 3 9 – 4 0 : This statement adds a line to the outputListBox control showing
the current value of the kph variable and the equivalent value in miles per hour.
S t e p 4 :
Switch your view back to the D esigner and double-click the exitButton control.
In the code editor you will see an empty event handler named exitButton_
Click. Complete the exitButton_Click event handler by typing the code shown
in lines 46–47 in Program 5-3.
S t e p 5 :
Save the project. Then, press
on the keyboard or click the Start D ebugging
button ( ) on the toolbar to compile and run the application. Click the D isplay
Speeds button, and you should see the output shown in the image on the right in
Figure 5-14. Click the Exit button to close the form.
P r o g r a m 5 -3
C o m p l e t e d F o r m 1 c o d e f o r t h e Speed Converter a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Speed_Converter
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void displayButton_Click(object sender, EventArgs e)
21
{
22
// Constants
23
const int START_SPEED = 60;
24
const int END_SPEED = 130;
25
const int INTERVAL = 10;
26
const double CONVERSION_FACTOR = 0.6214;
27
28
// Variables
29
int kph;
// Kilometers per hour
30
double mph;
// Miles per hour
31
32
// Display the table of speeds.
33
for (kph = START_SPEED; kph <= END_SPEED; kph += INTERVAL)
34
{
5 .5
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50 }
T h e do-while L o o p
// Calculate miles per hour.
mph = kph * CONVERSION_FACTOR;
// Display the conversion.
outputListBox.Items.Add(kph + " KPH is the same as " +
mph + " MPH");
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
C h e c k p o in t
5.11 N ame the three expressions that appear inside the parentheses in the first line of a
for loop.
5.12 You want to write a for loop that displays I love to program 50 times. Assume
that you will use a variable named count as the counter variable.
a. What initialization expression will you use?
b. What test expression will you use?
c. What update expression will you use?
d. Write the loop.
5.13 What would the following code display?
for (int count = 1; count <= 5; count++)
{
MessageBox.Show(count.ToString());
}
5.14 What would the following code display?
for (int count = 0; count <= 500; count += 100)
{
MessageBox.Show(count.ToString());
}
5 .5
T h e do-while L o o p
C O N C E P T :
T h e do-while l o o p i s a p o s t t e s t l o o p , w h i c h m e a n s i t p e r f o r m s a n i t e r a t i o n
b e fo r e te s tin g its B o o le a n e x p r e s s io n .
You have learned that the while loop and the for are pretest loops, which means they
test their Boolean expressions before performing an iteration. The do-while loop is a
p o s t t e s t l o o p . This means it performs an iteration before testing its Boolean expression.
As a result, the do-while loop always performs at least one iteration, even if its Boolean
expression is false to begin with. The logic of a do-while loop is shown in Figure 5-15.
In the flowchart, one or more statements are executed, and then a Boolean expression is
tested. If the Boolean expression is true, the program’s execution flows back to the point
291
292
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
F ig u r e 5 -1 5
T h e l o g i c o f a do-while l o o p
Statement(s)
Boolean
Expression
True
False
just above the first statement in the body of the loop, and this process repeats. If the
Boolean expression is false, the program exits the loop.
In code, the do-while loop looks something like an inverted while loop. H ere is the
general format of the do-while loop:
do
{
statement;
statement;
etc.
} while (BooleanExpression);
As with the while loop, the braces are optional if there is only one statement in the body
of the loop. This is the general format of the do-while loop with only one conditionally
executed statement:
do
statement;
while (BooleanExpression);
N otice that a semicolon appears at the very end of the do-while statement. This semicolon is required; leaving it out is a common error.
The do-while loop is a posttest loop. This means it does not test its Boolean expression
until it has completed an iteration. As a result, the do-while loop always performs at
least one iteration, even if the expression is false to begin with. This differs from the
behavior of a while loop. For example, in the following while loop, the statement that
calls MessageBox.Show will not execute at all:
int number = 1;
while (number < 0)
{
MessageBox.Show(number.ToString());
}
But, the statement that calls MessageBox.Show in the following do-while loop executes
one time because the do-while loop does not test the expression number < 0 until the
end of the iteration.
int number = 1;
do
{
MessageBox.Show(number.ToString());
} while (number < 0);
5 .6
U s in g F ile s fo r D a t a S t o r a g e
C h e c k p o in t
5.15 What is a posttest loop?
5.16 What is the difference between the while loop and the do-while loop?
5.17 H ow many times will the following loop iterate?
int count = 0;
do
{
MessageBox.Show(count.ToString());
count++;
} while (count < 0);
5 .6
U s in g F ile s fo r D a t a S t o r a g e
C O N C E P T :
W h e n a p r o g r a m n e e d s to s a v e d a ta fo r la te r u s e , it w r ite s th e d a ta in a
file . T h e d a ta c a n b e r e a d fr o m th e file a t a la te r tim e .
The programs you have written so far require the user to reenter data each time the
program runs because data kept in variables and control properties is stored in RAM
and disappears once the program stops running. If a program is to retain data between
the times it runs, it must have a way of saving it. Data is saved in a file, which is usually
stored on a computer’s disk. Once the data is saved in a file, it will remain there after
the program stops running. Data that is stored in a file can be retrieved and used at a
later time.
M ost of the commercial software that you use on a day-to-day basis store data in files.
The following are a few examples:
• W o r d p r o c e s s o r s : Word processing programs are used to write letters, memos,
reports, and other documents. The documents are then saved in files so they can be
edited and printed.
• I m a g e e d i t o r s : Image-editing programs are used to draw graphics and edit images,
such as the ones that you take with a digital camera. The images that you create or
edit with an image editor are saved in files.
• S p r e a d s h e e t s : Spreadsheet programs are used to work with numerical data. N umbers and mathematical formulas can be inserted into the rows and columns of the
spreadsheet. The spreadsheet can then be saved in a file for use later.
• G a m e s : M any computer games keep data stored in files. For example, some
games keep a list of player names with their scores stored in a file. These games
typically display the players’ names in order of their scores, from highest to
lowest. Some games also allow you to save your current game status in a file so
you can quit the game and then resume playing it later without having to start
from the beginning.
• W e b b r o w s e r s : Sometimes when you visit a Web page, the browser stores a small
file known as a cookie on your computer. Cookies typically contain information
about the browsing session, such as the contents of a shopping cart.
Programs that are used in daily business operations rely extensively on files. Payroll programs keep employee data in files, inventory programs keep data about a company’s
products in files, accounting systems keep data about a company’s financial operations in
files, and so forth.
293
294
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
Programmers usually refer to the process of saving data in a file as writing data to the file.
When a piece of data is written to a file, it is copied from a variable in RAM to the file.
This is illustrated in Figure 5-16. The term o u t p u t f i l e is used to describe a file to which
data is written. It is called an output file because the program stores output in it.
F ig u r e 5 -1 6
W r it in g d a t a t o a file
Data is copied from
variables to the file.
Variable
payRate
18.65
Variable
employeeID
7451Z
Variable
employeeName Cindy Chandler
handler 7451Z 18.65
Cindy C
A file on the disk
The process of retrieving data from a file is known as reading data from the file. When a
piece of data is read from a file, it is copied from the file into a variable in RAM . Figure
5-17 illustrates this. The term i n p u t f i l e is used to describe a file from which data is read.
It is called an input file because the program gets input from the file.
F ig u r e 5 -1 7
R e a d in g d a t a fr o m a file
Data is copied from
the file to variables.
Variable
payRate
18.65
Variable
employeeID
7451Z
Variable
employeeName Cindy Chandler
handler 7451Z 18.65
Cindy C
A file on the disk
In this section, we discuss ways to create programs that write data to files and read data
from files. There are always three steps that must be taken when a file is used by a program.
1. O p e n t h e f i l e —Opening a file creates a connection between the file and the program. Opening an output file usually creates the file on the disk and allows the
program to write data to it. Opening an input file allows the program to read data
from the file.
2. P r o c e s s t h e f i l e —In this step, data is either written to the file (if it is an output file)
or read from the file (if it is an input file).
3. C l o s e t h e f i l e —When the program is finished using the file, the file must be closed.
Closing a file disconnects the file from the program.
5 .6
U s in g F ile s fo r D a t a S t o r a g e
T y p e s o f F ile s
In general, there are two types of files: text and binary. A t e x t f i l e contains data that has
been encoded as text using a scheme such as Unicode. Even if the file contains numbers,
those numbers are stored in the file as a series of characters. As a result, the file may be
opened and viewed in a text editor such as N otepad. A b i n a r y f i l e contains data that has
not been converted to text. As a consequence, you cannot view the contents of a binary
file with a text editor. In this chapter, we work only with text files.
F ile A c c e s s M e t h o d s
M ost programming languages provide two different ways to access data stored in a file:
sequential access and direct access. When you work with a s e q u e n t i a l a c c e s s f i l e , you
access data from the beginning of the file to the end of the file. If you want to read a piece
of data that is stored at the very end of the file, you have to read all the data that comes
before it—you cannot jump directly to the desired data. This is similar to the way cassette
tape players work. If you want to listen to the last song on a cassette tape, you have to
either fast-forward over all of the songs that come before it or listen to them. There is no
way to jump directly to a specific song.
When you work with a d i r e c t a c c e s s f i l e (which is also known as a r a n d o m a c c e s s f i l e ),
you can jump directly to any piece of data in the file without reading the data that comes
before it. This is similar to the way a CD player or an M P3 player works. You can jump
directly to any song you want to listen to.
This chapter focuses on sequential access files. Sequential access files are easy to work
with, and you can use them to gain an understanding of basic file operations.
F ile n a m e s a n d F ile O b je c t s
Files on a disk are identified by a f i l e n a m e . For example, when you create a document
with a word processor and then save the document in a file, you have to specify a filename.
When you use a utility such as Windows Explorer to examine the contents of your disk,
you see a list of filenames. Figure 5-18 shows how three files named cat.jpg, notes.txt, and
resume.docx might be represented in Windows Explorer.
F ig u r e 5 -1 8
T h r e e file s
Each operating system has its own rules for naming files. M any systems, including Windows,
support the use of f i l e n a m e e x t e n s i o n s , which are short sequences of characters that appear
at theend of a filenameand arepreceded by a period (which isknown asa “ dot” ). For example, the files depicted in Figure 5-18 have the extensions .jpg, .txt, and .docx. The extension
usually indicates the type of data stored in the file. For example, the .jpg extension usually
indicates that the file contains a graphic image that is compressed according to the JPEG
image standard. The .txt extension usually indicates that the file contains text. The .docx
extension usually indicates that the file contains a M icrosoft Word document.
In order for a program to work with a file on the computer’s disk, the program must create
a file object in memory. A f i l e o b j e c t is an object that is associated with a specific file and
provides a way for the program to work with that file. In the program, a variable is linked
295
296
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
with the file object. We say that the variable references the object. This variable is used to
carry out any operations that are performed on the file. This concept is shown in Figure 5-19.
F ig u r e 5 -1 9
A v a r ia b le r e fe r e n c in g a file o b je c t t h a t is a s s o c ia t e d w it h a file
variableName
File object
Chand ler
Cin d y
A file on the disk
7451Z 18.65
You will be using two classes from the .N ET Framework to create file objects. When you
want to write data to a text file, you use the StreamWriter c l a s s , and when you want to
read data from a text file you use the StreamReader c l a s s . These classes are in the
System.IO namespace in the .N ET Framework, so you will need to write the following
directive at the top of your programs:
using System.IO;
N O T E : In programming terminology, files are considered streams of data. In C#, you
use a StreamWriter object to open a stream, such as a file, and write data to it. You use
a StreamReader object to open a stream, such as a file, and read data from it.
W r i t i n g D a t a t o a F i l e w i t h a StreamWriter O b j e c t
You can use the StreamWriter class’s WriteLine m e t h o d to write a line of text to a file.
Let’s suppose you want to write a program that creates a text file named courses.txt and
writes the names of the courses you are taking to the file. The following code sample
shows how you can do this:
1 StreamWriter outputFile;
2 outputFile = File.CreateText("courses.txt");
3
4 outputFile.WriteLine("Intro to Computer Science");
5 outputFile.WriteLine("English Composition");
6 outputFile.WriteLine("Calculus I");
7 outputFile.WriteLine("Music Appreciation");
8
9 outputFile.Close();
Let’s look at each line of code.
L i n e 1 : This statement declares a variable named outputFile, which can be used to
reference a StreamWriter object.
L i n e 2 : In a nutshell, this statement opens the file to which you will be writing data. It
does so by calling the File.CreateText method, passing the string "courses.txt"
as an argument. The File.CreateText method does the following:
• It creates a text file with the name specified by the argument. If the file already
exists, its contents are erased.
• It creates a StreamWriter object in memory, associated with the file.
• It returns a reference to the StreamWriter object.
5 .6
U s in g F ile s fo r D a t a S t o r a g e
Notice that an assignment operator assigns the value returned from the File.CreateText
method to the outputFile variable. This causes the outputFile variable to reference the
StreamWriter object that was created by the method.
After the statement in line 2 executes, the courses.txt file is created on the disk, a
StreamWriter object associated with the file exists in memory, and the outputFile
variable references that object.
L i n e 4 : This statement writes the string "Intro to Computer Science" to the courses.
txt file. It does that by calling the StreamWriter class’s WriteLine method, passing
the string that is to be written to the file as an argument. When the WriteLine method
writes data to a file, it writes a newline character immediately following the data. A
n e w l i n e c h a r a c t e r is an invisible character that specifies the end of a line of text.
L i n e 5 : This statement writes the string "English Composition" to the courses.txt file.
L i n e 6 : This statement writes the string "Calculus I" to the courses.txt file.
L i n e 7 : This statement writes the string "Music Appreciation" to the courses.txt file.
L i n e 9 : This statement closes the courses.txt file. It does that by calling the StreamWriter
class’s Close method.
After this code has executed, we can open the courses.txt file using a text editor and look
at its contents. Figure 5-20 show how the file’s contents will appear in N otepad.
F ig u r e 5 -2 0
C o n t e n t s o f t h e c o u r s e s .t x t file s h o w n in N o t e p a d
W r i t i n g D a t a w i t h t h e Write M e t h o d
Earlier you read that the StreamWriter class’s WriteLine method writes an item of data
to a file and then writes a newline character. The newline character specifies the end of a
line of text. For example, the following code sample opens a file named Example.txt and
then uses the WriteLine method to write the strings "One", "Two", and "Three" to the
file. Because a newline character is written after each string, the strings appear on separate
lines when viewed in a text editor. The screen shown on the left in Figure 5-21 shows how
the file would appear in N otepad.
1 StreamWriter outputFile;
2 outputFile = File.CreateText("Example.txt");
3
4 outputFile.WriteLine("One");
5 outputFile.WriteLine("Two");
6 outputFile.WriteLine("Three");
7
8 outputFile.Close();
297
298
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
F ig u r e 5 -2 1
I t e m s w r i t t e n w i t h t h e WriteLine a n d Write m e t h o d s
Items written with WriteLine
Items written with Write
In some situations, you might want to write an item to a file without a newline character
immediately following it. The StreamWriter class provides the Write m e t h o d for this
purpose. It writes an item of data to a text file without writing a newline character. The
following code sample demonstrates. The screen shown on the right in Figure 5-21 shows
how the resulting file would appear in N otepad.
1 StreamWriter outputFile;
2 outputFile = File.CreateText("Example.txt");
3
4 outputFile.Write("One");
5 outputFile.Write("Two");
6 outputFile.Write("Three");
7
8 outputFile.Close();
H a n d lin g F ile -R e la t e d E x c e p t io n s
Unexpected problems can potentially occur when working with files. For example,
your program might not have sufficient rights to create a file when it calls the File.
CreateText method, or the disk might be full when you call the StreamWriter class’s
WriteLine method. When unexpected errors such as these occur, an exception is
thrown. To handle such exceptions, you can write a try-catch statement, with the
code that performs file operations placed in the try block. H ere is an example:
1 try
2 {
3
StreamWriter outputFile;
4
outputFile = File.CreateText("courses.txt");
5
6
outputFile.WriteLine("Intro to Computer Science");
7
outputFile.WriteLine("English Composition");
8
outputFile.WriteLine("Calculus I");
9
outputFile.WriteLine("Music Appreciation");
10
11
outputFile.Close();
12 }
13 catch (Exception ex)
14 {
15
// Display an error message.
16
MessageBox.Show(ex.Message);
17 }
In Tutorial 5-4, you will complete an application that reads input from a TextBox control
and writes the input to a file.
5 .6
U s in g F ile s fo r D a t a S t o r a g e
T u t o r ia l 5 -4 :
W r it in g D a t a t o a T e x t F ile
VideoNot e
T u to r ia l 5 -4 :
Writing
Data to a
Text File
In this tutorial, you complete the Friend File application. The project has already been
started for you and is located in the Chap05 folder of this book’s Student Sample Programs. The application’s form is shown in Figure 5-22.
F ig u r e 5 -2 2
T h e Friend File f o r m
nameTextBox
writeNameButton exitButton
When you complete the application, it will allow the user to enter a name into the
nameTextBox control. When the user clicks the writeNameButton control, the application
opens a text file named Friend.txt, writes the name that was entered into the TextBox
control to the file, and then closes the file.
S t e p 1 :
Start Visual Studio. Open the project named Ending Balance in the Chap05
folder of this book’s Student Sample Programs.
S t e p 2 :
Open the Form1 form’s code in the code editor. Insert the using System.IO;
directive shown in line 10 of Program 5-4 at the end of this tutorial. This statement is necessary because the StreamWriter class is part of the System.IO
namespace in the .N ET Framework.
S t e p 3 :
Open the Form1 form in the D esigner. The form is shown, along with the names
of the important controls, in Figure 5-22. Double-click the writeNameButton
control. This opens the code editor, and you will see an empty event handler
named writeNameButton_Click. Complete the writeNameButton_Click
event handler by typing the code shown in lines 23–44 in Program 5-4. Let’s
take a closer look at the code:
L i n e 2 3 : This is the beginning of a try-catch statement. The try block appears
in lines 25–38, and the catch block appears in lines 42–43. If an exception is
thrown by any statement in the try block, the program jumps to the catch block,
and line 43 displays an error message.
L i n e 2 6 : This statement declares a StreamWriter variable named outputFile.
You use this variable to reference a StreamWriter object.
L i n e 2 9 : This statement calls the File.CreateText method to create a text file
named Friend.txt. The method also creates a StreamWriter object in memory
associated with the file. The method returns a reference to that object, which is
assigned to the outputFile variable. As a result, the outputFile variable
references the StreamWriter object. You will be able to use the outputFile
variable to perform operations on the Friend.txt file.
299
300
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
L i n e 3 2 : This statement uses the outputFile variable to call the StreamWriter
class’s WriteLine method. The nameTextBox control’s Text property is passed
as an argument. As a result, the value entered into the TextBox is written to the
Friend.txt file.
L i n e 3 5 : This statement closes the Friend.txt file.
L i n e 3 8 : This statement displays a message box to let the user know that the
name was written to the file.
S t e p 4 :
Switch your view back to the D esigner and double-click the exitButton
control. In the code editor you will see an empty event handler named
exitButton_Click. Complete the exitButton_Click event handler by typing
the code shown in lines 49–50 in Program 5-4.
S t e p 5 :
Save the project. Then, press
on the keyboard or click the Start D ebugging
button ( ) on the toolbar to compile and run the application.
Enter a name into the nameTextBox control, and then click the Write N ame
button. You should see a message box appear letting you know that the name
was written to the file. Click the O K button to dismiss the message box; then
click the Exit button on the application’s form to end the application.
S t e p 6 :
N ow you will look at the contents of the Friend.txt file that the application
created. Click File on the menu bar, then click O pen, and then click File. . .
S t e p 7 :
You should now see the O pen File window, viewing the contents of the
Friend File project folder. As shown in Figure 5-23, open the bin folder, then
open the D ebug folder, and then select the file Friend.txt. (You might not
see the .txt extension, depending on how your system is set up.) Click the
O pen button.
F ig u r e 5 -2 3
O p e n i n g t h e F r i e n d . t x t f i l e i n t h e Open File w i n d o w
1 Open the bin folder.
2 Open the Debug folder.
3 Select Friend.txt. (You might not see the .txt extension.)
5 .6
S t e p 8 :
U s in g F ile s fo r D a t a S t o r a g e
You should now see the contents of the Friend.txt file in Visual Studio, as shown
in Figure 5-24. (The example in the figure shows the contents of the file after
t h e u s e r h a s w r i t t e n Tim O wens t o t h e f i l e . ) W h e n y o u a r e f i n i s h e d e x a m i n i n g
th e c o n te n ts o f th e file , y o u c a n c lo s e its ta b . W e c o m e b a c k to th is p r o je c t in th e
n e x t tu to r ia l.
F ig u r e 5 -2 4
S a m p le c o n t e n t s o f t h e F r ie n d .t x t file s h o w n in V is u a l S t u d io
P r o g r a m 5 -4
C o m p l e t e d F o r m 1 c o d e f o r t h e Friend File a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10 using System.IO;
11
12 namespace Friend_File
13 {
14
public partial class Form1 : Form
15
{
16
public Form1()
17
{
18
InitializeComponent();
19
}
20
21
private void writeNameButton_Click(object sender, EventArgs e)
22
{
23
try
24
{
25
// Declare a StreamWriter variable.
26
StreamWriter outputFile;
27
28
// Create a file and get a StreamWriter object.
29
outputFile = File.CreateText("Friend.txt");
30
31
// Write the friend's name to the file.
32
outputFile.WriteLine(nameTextBox.Text);
33
34
// Close the file.
35
outputFile.Close();
36
301
302
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 }
// Let the user know the name was written.
MessageBox.Show("The name was written.");
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
W r it in g N u m e r ic D a t a t o a T e x t F ile
You can use the StreamWriter class’s WriteLine or Write method to write numbers
(such as ints, doubles, and decimals) to a text file, but the numbers are converted to
strings. For example, look at the following sample code (taken from the N umber File
project in the Chap05 folder of the Student Sample Programs):
1 private void writeNumbersButton_Click(object sender, EventArgs e)
2 {
3
try
4
{
5
// Declare a StreamWriter variable.
6
StreamWriter outputFile;
7
8
// Create a file and get a StreamWriter object.
9
outputFile = File.CreateText("Numbers.txt");
10
11
// Write the numbers 1 through 10 to the file.
12
for (int count = 1; count <= 10; count++)
13
{
14
outputFile.WriteLine(count);
15
}
16
17
// Close the file.
18
outputFile.Close();
19
}
20
catch (Exception ex)
21
{
22
// Display an error message.
23
MessageBox.Show(ex.Message);
24
}
25 }
When this event handler executes, line 9 creates a text file named N umbers.txt, and the
loop in lines 12–15 writes the numbers 1–10 to the file. Figure 5-25 shows how the file
appears when opened with N otepad.
5 .6
F ig u r e 5 -2 5
U s in g F ile s fo r D a t a S t o r a g e
T h e N u m b e r s .t x t file o p e n e d in N o t e p a d
A p p e n d in g D a t a t o a n E x is t in g F ile
When you call the File.CreateText method to open a file and the file specified by
the argument already exists, it is erased and a new empty file with the same name is
created. For example, when you run the Friend File application that you completed in
Tutorial 5-4, each time you click the Write N ame button, the Friend.txt file is erased
and a new file is created.
Sometimes you want to preserve an existing file and append new data to its current contents. To append data to an existing file, you open it with the File.AppendText method.
It works like the File.CreateText method, but the file is not erased if it already exists.
Any data written to the file is appended to the file’s existing contents.
For example, assume the file N ames.txt exists and contains the data shown in Figure 5-26:
F ig u r e 5 -2 6
N a m e s .t x t file
The following code opens the file and appends additional data to its existing contents:
1 StreamWriter outputFile;
2 outputFile = File.AppendText("Names.txt");
3
4 outputFile.WriteLine("Lynn");
5 outputFile.WriteLine("Steve");
6 outputFile.WriteLine("Bill");
7
8 outputFile.Close();
After this code executes, the N ames.txt file contains the data shown in Figure 5-27:
303
304
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
F ig u r e 5 -2 7
N a m e s .t x t file a ft e r d a t a h a s b e e n a p p e n d e d
T u t o r ia l 5 -5 :
A p p e n d in g D a t a t o t h e F r ie n d .t x t F ile
VideoNot e
T u to r ia l 5 -5 :
Appending
Data to the
Friend.txt
File
In this tutorial, you will modify the Friend File application so it appends data to the
Friend.txt file. When the user clicks the Write N ame button, instead of erasing the file’s
current contents, the application adds the contents of the nameTextBox control to the
Friend.txt file.
S t e p 1 :
If the Friend File project from Tutorial 5-4 is not currently open in Visual
Studio, open it now.
S t e p 2 :
Open the Form1 form’s code in the code editor. You will make modifications to
the writeNameButton_Click event handler. Program 5-5, at the end of this
tutorial, shows how the event handler code will appear after you make the
following changes:
L i n e s 8 a n d 9 : Change the comments as shown to reflect the way that the Friend.
txt file will be opened in line 10.
L i n e 1 0 : Change this statement so it calls the File.AppendText method instead
of the File.CreateText method.
L i n e s 2 1 – 2 5 : Add the new comments and statements shown in these lines. Line
22 clears the nameTextBox control’s contents, and line 25 gives the focus to the
nameTextBox control. This makes the application more convenient for adding
several names to the file.
S t e p 3 :
Save the project. Then, press
on the keyboard or click the Start D ebugging
button ( ) on the toolbar to compile and run the application.
Enter a name into the nameTextBox control and then click the Write N ame button. You should see a message box letting you know that the name was written
to the file. When you click the O K button to dismiss the message box, notice
that the nameTextBox is cleared, and the focus is given to the TextBox. Enter
another name, and click the Write N ame button. Again, you see the message
box. Click the O K button to dismiss the message box and then click the Exit
button to end the application.
S t e p 4 :
N ow you will look at the contents of the Friend.txt file. Click File on the menu
bar, then click O pen, and then click File.
You should see the O pen File window, viewing the contents of the Friend File
project folder. Open the bin folder, then open the D ebug folder, and then select
5 .6
U s in g F ile s fo r D a t a S t o r a g e
the file Friend.txt. (You might not see the .txt extension, depending on how
your system is set up.) Click the O pen button.
S t e p 5 :
You should now see the contents of the Friend.txt file in Visual Studio. Figure 5-28
shows an example. N otice that the names that you entered were appended to
the file each time you clicked the Write N ame button. When you are finished
examining the contents of the file, you can close its tab. We come back to this
project in the next tutorial.
F ig u r e 5 -2 8
S a m p le c o n t e n t s o f t h e F r ie n d .t x t file s h o w n in V is u a l S t u d io
P r o g r a m 5 -5
P a r t i a l c o d e f o r F o r m 1 i n t h e Friend File a p p l i c a t i o n
1 private void writeNameButton_Click(object sender, EventArgs e)
2 {
3
try
4
{
5
// Declare a StreamWriter variable.
6
StreamWriter outputFile;
7
8
// Open the Friend.txt file for appending,
9
// and get a StreamWriter object.
10
outputFile = File.AppendText("Friend.txt");
11
12
// Write the friend's name to the file.
13
outputFile.WriteLine(nameTextBox.Text);
14
15
// Close the file.
16
outputFile.Close();
17
18
// Let the user know the name was written.
19
MessageBox.Show("The name was written.");
20
21
// Clear the nameTextBox control.
22
nameTextBox.Text = "";
23
24
// Give the focus to the nameTextBox control.
25
nameTextBox.Focus();
26
}
27
catch (Exception ex)
28
{
29
// Display an error message.
30
MessageBox.Show(ex.Message);
31
}
32 }
305
306
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
S p e c ify in g t h e L o c a t io n o f a n O u t p u t F ile
When you call the File.CreateText or File.AppendText methods to open a file, you
pass the filename as a string argument. If the filename that you pass as an argument does
not contain the file’s path, the file’s location will be the bin\D ebug folder, under the application’s project folder. You saw this in Tutorials 5-4 and 5-5 when you opened the Friend.
txt file in Visual Studio.
If you want to open a file in a different location, you can specify a path as well as a filename in the argument that you pass to the File.CreateText or File.AppendText
method. If you specify a path in a string literal, be sure to prefix the string with the @
character. H ere is an example:
StreamWriter outputFile;
outputFile = File.CreateText(@"C:\Users\Chris\Documents\Names.txt");
T I P : You can also let the user specify the file location. See Section 5.7 for more
information on the SaveFileDialog control.
R e a d i n g D a t a f r o m a F i l e w i t h a StreamReader O b j e c t
To read data from a text file, you create a StreamReader object. You can then use the
StreamReader class’s ReadLine m e t h o d to read a line of text from a file. For example,
suppose a file named Students.txt exists and contains the four names shown in Figure 5-29.
F ig u r e 5 -2 9
C o n t e n t s o f t h e S t u d e n t s .t x t file
Let’s suppose you want to write a program that reads the four names from the Students.txt
file and displays them in message boxes. The following code sample shows how you can do
this. (This code sample is taken from the Student N ames project, in the Chap05 folder of
this book’s Student Sample Programs.)
1 try
2 {
3
// Declare a variable to hold an item read from the file.
4
string studentName;
5
6
// Declare a StreamReader variable.
7
StreamReader inputFile;
8
9
// Open the file and get a StreamReader object.
10
inputFile = File.OpenText("Students.txt");
11
5 .6
U s in g F ile s fo r D a t a S t o r a g e
12
// Read and display the first name.
13
studentName = inputFile.ReadLine();
14
MessageBox.Show(studentName);
15
16
// Read and display the second name.
17
studentName = inputFile.ReadLine();
18
MessageBox.Show(studentName);
19
20
// Read and display the third name.
21
studentName = inputFile.ReadLine();
22
MessageBox.Show(studentName);
23
24
// Read and display the fourth name.
25
studentName = inputFile.ReadLine();
26
MessageBox.Show(studentName);
27
28
// Close the file.
29
inputFile.Close();
30 }
31 catch (Exception ex)
32 {
33
// Display an error message.
34
MessageBox.Show(ex.Message);
35 }
Let’s take a closer look at the code.
L i n e 1 : This is the beginning of a try-catch statement. An exception will be thrown
in the try block if a problem occurs while the file is being opened or while an item is
being read from the file. If that happens, the program jumps to the catch clause in
line 31.
L i n e 4 : This statement declares a string variable named studentName. Each time we
read a line of text from the file, we assign it to this variable.
L i n e 7 : This statement declares a variable named inputFile that can be used to reference a StreamReader object.
L i n e 1 0 : This statement opens the file from which we will be reading data. It does so
b y c a l l i n g t h e File.OpenText m e t h o d , p a s s i n g t h e s t r i n g "Students.txt" a s a n
a r g u m e n t . T h e File.OpenText m e t h o d d o e s t h e f o l l o w i n g :
• It o p e n s a n e x is tin g te x t file w ith th e n a m e s p e c ifie d b y th e a r g u m e n t. If th e file d o e s
n o t e x is t, a n e x c e p tio n is th r o w n .
• I t c r e a t e s a StreamReader o b j e c t i n m e m o r y a s s o c i a t e d w i t h t h e f i l e .
• I t r e t u r n s a r e f e r e n c e t o t h e StreamReader o b j e c t .
N o t i c e t h a t a n a s s i g n m e n t o p e r a t o r a s s i g n s t h e v a l u e r e t u r n e d f r o m t h e File.OpenText
m e t h o d t o t h e inputFile v a r i a b l e . T h i s c a u s e s t h e inputFile v a r i a b l e t o r e f e r e n c e
t h e StreamReader o b j e c t t h a t w a s c r e a t e d b y t h e m e t h o d .
L i n e 1 3 : T h i s s t a t e m e n t c a l l s t h e inputFile.ReadLine m e t h o d , w h i c h r e a d s a l i n e o f
te x t fr o m th e file . T h e lin e o f te x t is r e tu r n e d a s a s tr in g fr o m th e m e th o d a n d a s s ig n e d
t o t h e studentName v a r i a b l e . S i n c e t h i s s t a t e m e n t r e a d s t h e f i r s t l i n e o f t e x t f r o m t h e
f i l e , t h e studentName v a r i a b l e i s a s s i g n e d t h e s t r i n g "Joe Merrell".
L i n e 1 4 : T h i s s t a t e m e n t d i s p l a y s t h e c o n t e n t s o f t h e studentName v a r i a b l e i n a m e s sage b o x .
L in e s 1 7 a n d 1 8 : T h e s ta te m e n t in lin e 1 7 r e a d s th e n e x t lin e o f te x t fr o m th e file a n d
a s s i g n s i t t o t h e studentName v a r i a b l e . A f t e r t h i s l i n e e x e c u t e s , t h e studentName
v a r i a b l e i s a s s i g n e d t h e s t r i n g "Chris Rich". T h e s t a t e m e n t i n l i n e 1 8 d i s p l a y s t h e
c o n t e n t s o f t h e studentName v a r i a b l e i n a m e s s a g e b o x .
307
308
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
L i n e s 2 1 a n d 2 2 : The statement in line 21 reads the next line of text from the file and
assigns it to the studentName variable. After this line executes, the studentName
variable is assigned the string "Kathryn Stevens". The statement in line 22 displays
the contents of the studentName variable in a message box.
L i n e s 2 5 a n d 2 6 : The statement in line 25 reads the next line of text from the file and
assigns it to the studentName variable. After this line executes, the studentName variable is assigned the string "Carly Colombo". The statement in line 26 displays the
contents of the studentName variable in a message box.
L i n e 2 9 : This statement closes the Students.txt file.
T h e R e a d P o s it io n
When a program works with an input file, a special value known as a r e a d p o s i t i o n is
internally maintained for that file. A file’s read position marks the location of the next
item that will be read from the file. When an input file is opened, its read position is initially set to the first item in the file. As items are read from the file, the read position
moves forward, toward the end of the file. Let’s see how this works in the previous code
sample (from the Student N ames project) After the statement in line 10 executes, the read
position for the Students.txt file is positioned as shown in Figure 5-30.
F ig u r e 5 -3 0
T h e in it ia l r e a d p o s it io n
Joe Merrell
newline
Chris Rich
newline
Kathryn Stevens
Carly Colombo
newline
newline
Read position
The ReadLine method call in line 13 reads an item from the file’s current read position
and assigns that item to the studentName variable. Once this statement executes, the
studentName variable is assigned the string "Joe Merrell". In addition, the file’s read
position is advanced to the next item in the file, as shown in Figure 5-31.
F ig u r e 5 -3 1
Joe Merrell
R e a d p o s i t i o n a f t e r t h e f i r s t ReadLine m e t h o d c a l l
newline
Chris Rich
newline
Kathryn Stevens
newline
Carly Colombo
newline
Read position
The ReadLine method call in line 17 reads an item from the file’s current read position
and assigns that value to the studentName variable. Once this statement executes, the
studentName variable is assigned the string "Chris Rich". The file’s read position is
advanced to the next item, as shown in Figure 5-32.
F ig u r e 5 -3 2
Joe Merrell
R e a d p o s i t i o n a f t e r t h e s e c o n d ReadLine m e t h o d c a l l
newline
Chris Rich
newline
Kathryn Stevens
Read position
newline
Carly Colombo
newline
5 .6
U s in g F ile s fo r D a t a S t o r a g e
The ReadLine method call in line 21 reads an item from the file’s current read position
and assigns that value to the studentName variable. Once this statement executes, the
studentName variable is assigned the string "Kathryn Stevens". The file’s read position
is advanced to the next item, as shown in Figure 5-33.
F ig u r e 5 -3 3
Joe Merrell
R e a d p o s i t i o n a f t e r t h e t h i r d ReadLine m e t h o d c a l l
newline
Chris Rich
newline
Kathryn Stevens
newline
Carly Colombo
newline
Read position
The last ReadLine method call appears in line 25. It reads an item from the file’s current
read position and assigns that value to the studentName variable. Once this statement
executes, the studentName variable is assigned the string "Carly Colombo". The file’s
read position is advanced to the end of the file, as shown in Figure 5-34.
F ig u r e 5 -3 4
Joe Merrell
R e a d p o s i t i o n a f t e r t h e f o u r t h ReadLine m e t h o d c a l l
newline
Chris Rich
newline
Kathryn Stevens
newline
Carly Colombo
newline
Read position
N O T E : Did you notice that the previous code sample read the items in the Students.
txt file in sequence, from the beginning of the file to the end of the file? Recall from
our discussion at the beginning of the section that this is the nature of a sequential
access file.
R e a d in g N u m e r ic D a t a fr o m a T e x t F ile
Remember that when data is stored in a text file, it is encoded as text, using a scheme such
as Unicode. Even if the file contains numbers, those numbers are stored in the file as a
series of characters. Furthermore, when you read an item from a text file with the
StreamReader class’s ReadLine method, that item is returned as a string.
Suppose a text file contains numeric data, such as that shown in Figure 5-35. When we
use the ReadLine method to read the items from the file, we get the strings "10", "20",
and "30". If we need to perform math with these values, we must convert each value from
a string to a numeric data type. We can use the Parse or TryParse families of methods
that you already know about to perform this conversion.
F ig u r e 5 -3 5
A t e x t file c o n t a in in g n u m e r ic d a t a
309
310
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
Let’s suppose you want to write a program that reads the three numbers from the
N umericData.txt file shown in Figure 5-35 and displays their total in a message box.
The following code sample shows a simple demonstration. (This code sample is taken
from the N umeric D ata project in the Chap05 folder of this book’s Student Sample
Programs.)
1 try
2 {
3
// Variables to hold the numbers read from the file
4
// and their total
5
int number1, number2, number3, total;
6
7
// A StreamReader variable.
8
StreamReader inputFile;
9
10
// Open the file and get a StreamReader object.
11
inputFile = File.OpenText("NumericData.txt");
12
13
// Read three numbers from the file.
14
number1 = int.Parse(inputFile.ReadLine());
15
number2 = int.Parse(inputFile.ReadLine());
16
number3 = int.Parse(inputFile.ReadLine());
17
// Calculate the total of the numbers.
18
19
total = number1 + number2 + number3;
20
21
// Display the total.
22
MessageBox.Show("The total is " + total);
23
// Close the file.
24
25
inputFile.Close();
26 }
27 catch (Exception ex)
28 {
29
// Display an error message.
30
MessageBox.Show(ex.Message);
31 }
Let’s take a closer look at the code.
L i n e 1 : This is the beginning of a try-catch statement. Various exceptions can be
thrown by the code in the try block, which cause the program to jump to the catch
clause in line 27.
L i n e 5 : This statement declares the int variables number1, number2, number3, and
total. These variables hold the three values read from the file and their total.
L i n e s 8 – 1 1 : After these statements have executed, the N umericData.txt file is opened
for reading, and the inputFile variable references a StreamReader object that is
associated with the file.
L i n e 1 4 : This statement does the following:
• It calls the inputFile.ReadLine method to read a line of text from the file.
• The value that is returned from the inputFile.ReadLine method (a string) is
passed as an argument to the int.Parse method.
• The value that is returned from the int.Parse method is assigned to the number1
variable.
After this statement executes, the number1 variable is assigned the first value read from
the file, converted to an int. (The number1 variable is assigned the value 10.)
5 .6
U s in g F ile s fo r D a t a S t o r a g e
L i n e 1 5 : This statement reads the next value from the file, converts it to an int, and
assigns the result to the number2 variable. (The number2 variable is assigned the
value 20.)
L i n e 1 6 : This statement reads the next value from the file, converts it to an int, and
assigns the result to the number3 variable. (The number3 variable is assigned the
value 30.)
L i n e 1 9 : This statement calculates the sum of number1, number2, and number3, and
assigns the result to total.
L i n e 2 2 : This statement displays the sum of the numbers in a message box.
L i n e 2 5 : This statement closes the file.
R e a d in g a F ile w it h a L o o p a n d D e t e c t in g
t h e E n d o f t h e F ile
Quite often a program must read the contents of a file without knowing the number of
items that are stored in the file. For example, suppose you need to write a program that
displays all the items in a file, but you do not know how many items the file contains. You
can open the file and then use a loop to repeatedly read an item from the file and display
it. H owever, an exception will be thrown if the program attempts to read beyond the end
of the file. The program needs some way of knowing when the end of the file has been
reached so it will not try to read beyond it. The following pseudocode shows the logic:
O pen the file
While not at the end of the file:
Read an item from the file
D isplay the item
End While
Close the file
StreamReader objects have a Boolean property named EndOfStream that signals
whether the end of the file has been reached. If the file’s read position is at the end of
the file (and there is no more data to read), the EndOfStream property is set to true.
Otherwise, it is set to false. When you need to read all the items in a file without
knowing how many items the file contains, you can write a loop that iterates as long as
the EndOfStream property is false.
Let’s assume inputFile references a StreamReader object that is associated with a file
that is already open. You can write the loop in the following manner:
while (inputFile.EndOfStream == false)
{
// Read an item from the file.
// Process the item.
}
H owever, most programmers prefer the following logic, which uses the ! operator:
while (!inputFile.EndOfStream)
{
// Read an item from the file.
// Process the item.
}
Recall that the ! operator is the logical N OT operator. When you read the first line of this
loop, you naturally think while N O T at the end of the stream. In Tutorial 5-6, you will
complete an application that uses this technique to display all the items in a file.
311
312
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
T u t o r ia l 5 -6 :
U s in g a L o o p t o R e a d t o t h e E n d o f a F ile
VideoNot e
T u to r ia l 5 -6 :
Using a
Loop to
Read to the
End of a File
In this tutorial, you complete the South America application that is found in the Chap05
folder of this book’s Student Sample Programs. The application’s form has already been
created and is shown in Figure 5-36. The application also has an accompanying text file
named Countries.txt that is stored in the bin\D ebug folder under the project folder. The
Countries.txt file contains the names of the countries of South America. Figure 5-37
shows the file as it appears in N otepad.
F ig u r e 5 -3 6
T h e South America a p p l i c a t i o n ’ s f o r m
countriesListBox
getCountriesButton
F ig u r e 5 -3 7
exitButton
T h e C o u n t r ie s .t x t file
When the completed application runs and the user clicks the Get Countries button,
the application reads each country name from the file and adds each one to the
countriesListBox control.
S t e p 1 :
Start Visual Studio. Open the project named South America in the Chap05
folder of this book’s Student Sample Programs.
S t e p 2 :
Open the Form1 form’s code in the code editor. Insert the using System.IO;
directive shown in line 10 of Program 5-6 at the end of this tutorial. This statement is necessary because the StreamReader class is part of the System.IO
namespace in the .NET Framework.
5 .6
S t e p 3 :
U s in g F ile s fo r D a t a S t o r a g e
Open the Form1 form in the Designer. The form is shown, along with the names of
the important controls, in Figure 5-36. Double-click the getCountriesButton
control. This opens the code editor, and you will see an empty event handler named
getCountriesButton _Click. Complete the getCountriesButton _Click event
handler by typing the code shown in lines 23–46 in Program 5-6. Let’s take a closer
look at the code:
L i n e 2 3 : This is the beginning of a try-catch statement, which handles any exceptions that are thrown while the file is being processed. If an exception is thrown by
any statement in the try block, the program jumps to the catch clause in line 50.
L i n e 2 6 : This statement declares the string variable countryName, which
holds the lines of text that are read from the file.
L i n e s 2 9 – 3 2 : After these statements have executed, the Countries.txt file is
opened for reading, and the inputFile variable references a StreamReader
object that is associated with the file.
L i n e 3 5 : This statement clears anything that might be displayed in the
countriesListBox control. (This prevents the names of the countries from
appearing multiple times in the ListBox if the user clicks the Get Countries
button multiple times.)
L i n e 3 8 : This is the beginning of a while loop that iterates as long as the end of
the Countries.txt file has not been reached.
L i n e 4 1 : This statement reads a line of text from the file and assigns it to the
countryName variable.
L i n e 4 4 : This statement adds the contents of the countryName variable to the
ListBox.
L i n e 4 8 : This statement closes the file.
S t e p 4 :
Switch your view back to the D esigner and double-click the exitButton
control. In the code editor you will see an empty event handler named
exitButton_Click. Complete the exitButton_Click event handler by typing
the code shown in lines 59–60 in Program 5-6.
S t e p 5 :
Save the project. Then, press
on the keyboard or click the Start D ebugging
button ( ) on the toolbar to compile and run the application. When the application runs, click the Get Countries button. This should fill the ListBox with the
names of the countries from the Countries.txt file, as shown in Figure 5-38.
Click the Exit button to exit the application.
F ig u r e 5 -3 8
T h e South America a p p l i c a t i o n d i s p l a y i n g t h e l i s t o f c o u n t r i e s
313
314
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
P r o g r a m 5 -6
C o m p l e t e d c o d e f o r F o r m 1 i n t h e South America a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10 using System.IO;
11
12 namespace South_America
13 {
14
public partial class Form1 : Form
15
{
16
public Form1()
17
{
18
InitializeComponent();
19
}
20
21
private void getCountriesButton_Click(object sender, EventArgs e)
22
{
23
try
24
{
25
// Declare a variable to hold a country name.
26
string countryName;
27
28
// Declare a StreamReader variable.
29
StreamReader inputFile;
30
31
// Open the file and get a StreamReader object.
32
inputFile = File.OpenText("Countries.txt");
33
34
// Clear anything currently in the ListBox.
35
countriesListBox.Items.Clear();
36
37
// Read the file's contents.
38
while (!inputFile.EndOfStream)
39
{
40
// Get a country name.
41
countryName = inputFile.ReadLine();
42
43
// Add the country name to the ListBox.
44
countriesListBox.Items.Add(countryName);
45
}
46
47
// Close the file.
48
inputFile.Close();
49
}
50
catch (Exception ex)
51
{
52
// Display an error message.
53
MessageBox.Show(ex.Message);
54
}
55
}
56
57
private void exitButton_Click(object sender, EventArgs e)
5 .6
58
59
60
61
62
63 }
U s in g F ile s fo r D a t a S t o r a g e
{
// Close the form.
this.Close();
}
}
C a lc u la t in g a R u n n in g T o t a l
M any programming tasks require you to calculate the total of a series of numbers. In this
section you learn how to calculate the total of a series of numbers that are stored in a file.
For example, suppose you have a file that contains a business’s sales for each day of a week
and you need to write a program that calculates the total of all the amounts in the file. The
program would read the values in the file and keep a total of the values as they are read.
Programs that calculate the total of a series of numbers typically use two elements:
• A loop that reads each number in the series
• A variable that accumulates the total of the numbers as they are read
The variable that is used to accumulate the total of the numbers is called an a c c u m u l a t o r .
It is often said that the loop keeps a r u n n i n g t o t a l because it accumulates the total as it
reads each number in the series. Figure 5-39 shows the general logic of a loop that calculates a running total.
F ig u r e 5 -3 9
L o g ic fo r c a lc u la t in g a r u n n in g t o t a l
Set accumulator to 0.
Is there another
number to read?
Yes
(True)
Read the next number.
Add the number to the
accumulator.
No
(False)
When the loop finishes, the accumulator will contain the total of the numbers that were
read by the loop. N otice that the first step in the flowchart is to set the accumulator variable to 0. This is a critical step. Each time the loop reads a number, it adds it to the accumulator. If the accumulator starts with any value other than 0, it will not contain the
correct total when the loop finishes.
In Tutorial 5-7, you will complete an application that calculates a running total of the
values in a file.
315
316
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
T u t o r ia l 5 -7 :
C a lc u la t in g a R u n n in g T o t a l
VideoNot e
T u to r ia l 5 -7 :
Calculating a
Running
Total
In this tutorial, you complete the Total Sales application that is found in the Chap05
folder of this book’s Student Sample Programs. The application’s form has already been
created and is shown in Figure 5-40. The application also has an accompanying text file
named Sales.txt that is stored in the bin\D ebug folder, under the project folder. The Sales.
txt file contains the amounts shown in Figure 5-41.
F ig u r e 5 -4 0
T h e Tota l Sa les a p p l i c a t i o n ’ s f o r m
totalLabel
calculateButton
F ig u r e 5 -4 1
exitButton
C o n t e n t s o f t h e S a le s .t x t file
When the completed application runs and the user clicks the Read Sales & Calculate
Total button, the application calculates the total of the values in the Sales.txt file and displays the total in the totalLabel control.
S t e p 1 :
Start Visual Studio. Open the project named Total Sales in the Chap05 folder of
this book’s Student Sample Programs.
S t e p 2 :
Open the Form1 form’s code in the code editor. Insert the using System.IO;
directive shown in line 10 of Program 5-7 at the end of this tutorial.
S t e p 3 :
Open the Form1 form in the D esigner. The form is shown, along with the names
of the important controls, in Figure 5-40. Double-click the calculateButton
control. This opens the code editor, and you will see an empty event handler
named calculateButton_Click. Complete the calculateButton_Click
5 .6
U s in g F ile s fo r D a t a S t o r a g e
event handler by typing the code shown in lines 23–56 in Program 5-7. Let’s
take a closer look at the code:
L i n e 2 3 : This is the beginning of a try-catch statement, which handles any
exceptions that are thrown while the file is being processed. If an exception is
thrown by any statement in the try block, the program jumps to the catch
clause in line 52.
L i n e s 2 6 – 2 7 : These statements declare the decimal variables sales and total.
The sales variable holds each value that is read from the file, and the total
variable is used as an accumulator. N otice that the total variable is explicitly
initialized to 0.
L i n e s 3 0 – 3 3 : After these statements have executed, the Sales.txt file is opened
for reading, and the inputFile variable references a StreamReader object that
is associated with the file.
L i n e 3 6 : This is the beginning of a while loop that iterates as long as the end of
the Countries.txt file has not been reached.
L i n e 3 9 : This statement reads a line of text from the file, converts it to a decimal,
and assigns the result to the sales variable.
L i n e 4 2 : This statement adds the sales variable to the total variable.
L i n e 4 6 : This statement closes the file.
L i n e 4 9 : This statement displays the total, formatted as currency, in the
totalLabel control.
S t e p 4 :
Switch your view back to the D esigner and double-click the exitButton
control. In the code editor you will see an empty event handler named
exitButton_Click. Complete the exitButton_Click event handler by typing
the code shown in lines 61–62 in Program 5-7.
S t e p 5 :
Save the project. Then, press
on the keyboard or click the Start D ebugging
button ( ) on the toolbar to compile and run the application. When the
application runs, click the Read Sales & Calculate Total button. The total sales
should be calculated and displayed, as shown in Figure 5-42. Click the Exit
button to exit the application.
F ig u r e 5 -4 2
T h e Tota l Sa les a p p l i c a t i o n d i s p l a y i n g t h e t o t a l s a l e s
P r o g r a m 5 -7
C o m p l e t e d c o d e f o r F o r m 1 i n t h e Tota l Sa les a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
317
318
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10 using System.IO;
11
12 namespace Total_Sales
13 {
14
public partial class Form1 : Form
15
{
16
public Form1()
17
{
18
InitializeComponent();
19
}
20
21
private void calculateButton_Click(object sender, EventArgs e)
22
{
23
try
24
{
25
// Variables
26
decimal sales;
// To hold a sales amount
27
decimal total = 0m;
// Accumulator, set to 0
28
29
// Declare a StreamReader variable.
30
StreamReader inputFile;
31
32
// Open the file and get a StreamReader object.
33
inputFile = File.OpenText("Sales.txt");
34
// Read the file's contents.
35
36
while (!inputFile.EndOfStream)
37
{
38
// Get a sales amount.
39
sales = decimal.Parse(inputFile.ReadLine());
40
// Add the sales amount to total.
41
42
total += sales;
43
}
44
45
// Close the file.
46
inputFile.Close();
47
// Display the total.
48
49
totalLabel.Text = total.ToString("C");
50
51
}
52
catch (Exception ex)
53
{
54
// Display an error message.
55
MessageBox.Show(ex.Message);
56
}
57
}
58
59
private void exitButton_Click(object sender, EventArgs e)
60
{
61
// Close the form.
62
this.Close();
63
}
64
}
65 }
5 .7
T h e O p e n F ile D ia lo g a n d S a v e F ile D ia lo g C o n t r o ls
C h e c k p o in t
5.18 What is an output file?
5.19 What is an input file?
5.20 What three steps must be taken by a program when it uses a file?
5.21 What is the difference between a text file and a binary file?
5.22 What are the two types of file access? What is the difference between these two?
5.23 What type of object do you create if you want to write data to a text file?
5.24 What type of object do you create if you want to read data from a text file?
5.25 If you call the File.CreateText method and the specified file already exists, what
happens to the existing file?
5.26 If you call the File.AppendText method and the specified file already exists, what
happens to the existing file?
5.27 What is the difference between the WriteLine and Write methods discussed in
this chapter?
5.28 What method do you call to open a text file to read data from it?
5.29 What is a file’s read position? Initially, where is the read position when an input
file is opened?
5.30 H ow do you read a line of text from a text file?
5.31 H ow do you close a file?
5.32 Assume inputFile references a StreamReader object that is associated with an
open file. Which of the following loops is written in the correct general format to
read all of the items from the file?
L oop A:
while (inputFile.EndOfStream)
{
// Read an item from the file.
}
L oop B:
while (!inputFile.EndOfStream)
{
// Read an item from the file.
}
5 .7
T h e O p e n F ile D ia lo g a n d S a v e F ile D ia lo g C o n t r o ls
C O N C E P T :
T h e O p e n F ile D ia lo g a n d S a v e F ile D ia lo g c o n tr o ls a llo w y o u r a p p lic a tio n
to d is p la y s ta n d a r d W in d o w s d ia lo g b o x e s fo r o p e n in g a n d s a v in g file s .
T h e s e a llo w th e u s e r to e a s ily s p e c ify a file ’s n a m e a n d lo c a tio n .
So far, the applications in this chapter that open a file specify the filename as a string
literal. M ost Windows users, however, are accustomed to using a dialog box to browse
their disk for a file to open or for a location to save a file. You can use the OpenFileDialog
319
320
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
and SaveFileDialog controls to equip applications with standard Windows dialog boxes
for these purposes.
T h e O p e n F ile D ia lo g C o n t r o l
The O p e n F i l e D i a l o g c o n t r o l displays a standard Windows O pen dialog box, such as the
one shown in Figure 5-43. The Open d i a l o g b o x is useful in applications that must open
an existing file because it allows the user to browse the system and select the file.
F ig u r e 5 -4 3
W i n d o w s Open d i a l o g b o x
A d d in g t h e O p e n F ile D ia lo g C o n t r o l t o Y o u r P r o je c t
To add an OpenFileDialog control to a form, double-click the OpenFileDialog tool under
the D ialogs group in the Toolbox window. When the control is created, it does not appear
on the form, but in an area at the bottom of the D esigner known as the c o m p o n e n t t r a y .
Figure 5-44 shows an example of how an OpenFileDialog control appears in the component tray. The control’s default name is OpenFileDialog1. As with other controls, you can
change the control’s N ame property to change its name.
D is p la y in g a n O p e n D ia lo g B o x
In code, you can display an O pen dialog box by calling the OpenFileDialog control’s
ShowDialog method. For example, assume that we have created an OpenFileDialog
control and changed its name to openFile. The following statement calls the control’s
ShowDialog method:
openFile.ShowDialog();
In most cases, however, you will want to know whether the user clicked the O pen button
or the Cancel button to dismiss the O pen dialog box. If the user clicked the O pen button,
it means that the user has selected a file and he or she can open it. If the user clicked the
Cancel button, it means that the user does not want to proceed.
The ShowDialog method returns a value that indicates which button the user clicked to
dismiss the dialog box. If the user clicked the O pen button, the value DialogResult.OK
is returned. If the user clicked the Cancel button, the value DialogResult.Cancel is
returned. Assuming openFile is the name of an OpenFileDialog control, the following is
5 .7
F ig u r e 5 -4 4
T h e O p e n F ile D ia lo g a n d S a v e F ile D ia lo g C o n t r o ls
A n O p e n F ile D ia lo g c o n t r o l in t h e c o m p o n e n t t r a y
OpenFileDialog control
Component tray
an example of an if-else statement that calls the ShowDialog method and determines
whether the user clicked the O pen button or the Cancel button.
if (openFile.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("You clicked the Open button.");
}
else
{
MessageBox.Show("You clicked the Cancel button.");
}
T h e F ile n a m e P r o p e r t y
When the user selects a file with the O pen dialog box, the file’s path and filename are stored
in the control’s F i l e n a m e p r o p e r t y . Assume openFile is the name of an OpenFileDialog
control. The following code is an example of how you can display an O pen dialog box and,
if the user clicks the O pen button to dismiss the dialog box, open the selected file:
1 StreamReader inputFile;
2
3 if (openFile.ShowDialog() == DialogResult.OK)
4 {
5
// Open the selected file.
6
inputFile = File.OpenText(openFile.Filename);
7
8
// Continue processing the file…
9 }
10 else
11 {
12
MessageBox.Show("Operation canceled.");
13 }
321
322
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
Let’s take a closer look at the code. The statement in line 1 declares a StreamReader
variable named inputFile. The if statement in line 3 calls the openFile control’s
ShowDialog method to display an O pen dialog box. If the user clicks the O pen button to
dismiss the dialog box, the program continues to line 6, where the name of the selected
file is retrieved from the control’s Filename property and that file is opened. Otherwise (if
the user clicks the Cancel button), the program jumps to the else clause in line 10.
T I P : When you create an OpenFileDialog control, its Filename property is initially
set to the control’s default name. For example, if the control’s default name is
openFileDialog1, then the Filename property is also set to openFileD ialog1. Always
be sure to delete the default value of the Filename property.
T h e In it ia lD ir e c t o r y P r o p e r t y
By default, the O pen dialog box displays the contents of the user’s D ocuments directory (or folder). You can specify another directory to be initially displayed by storing
its path in the I n i t i a l D i r e c t o r y p r o p e r t y . For example, the following code stores the
path C:\D ata in the openFile control’s InitialDirectory property before displaying an
O pen dialog box:
openFile.InitialDirectory = "C:\Data";
if (openFile.ShowDialog() == DialogResult.OK)
{
// Continue to process the selected file…
}
else
{
// The operation was canceled.
}
In this example, when the O pen dialog box is displayed it shows the contents of the directory C:\D ata.
T h e T it le P r o p e r t y
By default, the word O pen is displayed in an O pen dialog box’s title bar. You can change
the default text displayed in the title bar by changing the control’s T i t l e p r o p e r t y .
T h e S a v e F ile D ia lo g C o n t r o l
The S a v e F i l e D i a l o g c o n t r o l displays a standard Windows Save As dialog box, such as the
one shown in Figure 5-45. The S a v e A s d i a l o g b o x allows the user to browse the system
and select a location and name for a file that is about to be saved.
A d d in g t h e S a v e F ile D ia lo g C o n t r o l t o Y o u r P r o je c t
The SaveFileDialog control has much in common with the OpenFileDialog control. To
add a SaveFileDialog control to a form, double-click the SaveFileDialog tool under the
D ialogs group in the Toolbox window. When the control is created, it appears in the
component tray at the bottom of the D esigner. The control will be given a default
n a m e s u c h a s s a v e F ile D ia lo g 1 , b u t y o u c a n c h a n g e th e n a m e w ith th e N a m e p r o p e r ty .
D i s p l a y i n g a Save As D i a l o g B o x
I n c o d e , y o u c a n d i s p l a y a Save As d i a l o g b o x b y c a l l i n g t h e S a v e F i l e D i a l o g c o n t r o l ’ s
ShowDialog m e t h o d . F o r e x a m p l e , a s s u m e t h a t w e h a v e c r e a t e d a S a v e F i l e D i a l o g c o n t r o l
5 .7
F ig u r e 5 -4 5
T h e O p e n F ile D ia lo g a n d S a v e F ile D ia lo g C o n t r o ls
W i n d o w s Sa ve As d i a l o g b o x
and changed its name to saveFile . The following statement calls the control’s
ShowDialog method:
saveFile.ShowDialog();
The method returns a value indicating whether the user clicked the Save button or the
Cancel button to dismiss the Save As dialog box. If the user clicks the Save button, the
value DialogResult.OK is returned. If the user clicks the Cancel button, the value
DialogResult.Cancel is returned. Assume saveFile is the name of a SaveFileDialog
control. The following is an example of an if-else statement that calls the ShowDialog
method and determines whether the user clicked the Save button or the Cancel button:
if (saveFile.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("You clicked the Save button.");
}
else
{
MessageBox.Show("You clicked the Cancel button.");
}
T h e F ile n a m e P r o p e r t y
When the user specifies a location and filename with the Save As dialog box, the file’s
path and filename are stored in the control’s Filename property. Assume saveFile is the
name of a SaveFileDialog control. The following code is an example of how you can
display a Save As dialog box, and if the user clicks the Save button to dismiss the dialog
box, open the selected file:
1 StreamWriter outputFile;
2
3 if (saveFile.ShowDialog() == DialogResult.OK)
4 {
5
// Create the selected file.
6
outputFile = File.CreateText(saveFile.Filename);
7
8
// Write data to the file…
9 }
10 else
323
324
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
11 {
12
13 }
MessageBox.Show("Operation canceled.");
Let’s take a closer look at the code. The statement in line 1 declares a StreamWriter
variable named outputFile. The if statement in line 3 calls the saveFile control’s
ShowDialog method to display a Save As dialog box. If the user clicks the Save button
to dismiss the dialog box, the program continues to line 6, where the selected name and
path are retrieved from the control’s Filename property, and that file is created. Otherwise (if the user clicks the Cancel button), the program jumps to the else clause in
lin e 1 0 .
T h e In it ia lD ir e c t o r y P r o p e r t y
B y d e f a u l t , t h e Save As d i a l o g b o x d i s p l a y s t h e c o n t e n t s o f t h e u s e r ’ s D ocuments d i r e c t o r y
(o r fo ld e r ). Y o u c a n s p e c ify a n o th e r d ir e c to r y to b e in itia lly d is p la y e d b y s to r in g its p a th
i n t h e I n i t i a l D i r e c t o r y p r o p e r t y . T h e f o l l o w i n g c o d e s t o r e s t h e p a t h C:\D ata i n t h e
saveFile c o n t r o l ’ s I n i t i a l D i r e c t o r y p r o p e r t y b e f o r e d i s p l a y i n g a Save As d i a l o g b o x :
saveFile.InitialDirectory = "C:\Data";
if (saveFile.ShowDialog() == DialogResult.OK)
{
// Continue to process the file…
}
else
{
// The operation was cancelled.
}
I n t h i s e x a m p l e , w h e n t h e Save As d i a l o g b o x i s d i s p l a y e d , i t s h o w s t h e c o n t e n t s o f t h e
d i r e c t o r y C:\D ata.
T h e T it le P r o p e r t y
B y d e f a u l t t h e w o r d s Save As a r e d i s p l a y e d i n a Save As d i a l o g b o x ’ s t i t l e b a r . Y o u c a n
c h a n g e th e d e fa u lt te x t d is p la y e d in th e title b a r b y c h a n g in g th e c o n tr o l’s T itle p r o p e r ty .
C h e c k p o in t
5 .3 3
W h a t i s t h e b e n e f i t o f u s i n g a n O pen a n d / o r Save As d i a l o g b o x i n a n a p p l i c a t i o n
th a t w o r k s w ith file s ?
5 .3 4
W h a t is th e p u r p o s e o f th e fo llo w in g O p e n F ile D ia lo g a n d
p r o p e r tie s ?
S a v e F ile D ia lo g
In itia lD ir e c to r y
T itle
F ile n a m e
5 .8
R a n d o m N u m b e r s
C O N C E P T :
R a n d o m n u m b e r s a r e u s e d in a v a r ie ty o f a p p lic a tio n s . T h e .N E T
F r a m e w o r k p r o v i d e s t h e Random c l a s s t h a t y o u c a n u s e i n C # t o g e n e r a t e
ran d o m n u mb ers.
5 .8
R a n d o m N u m b e rs
Random numbers are useful for lots of different programming tasks. The following are
just a few examples:
• Random numbers are commonly used in games. For example, computer games that
let the player roll dice use random numbers to represent the values of the dice.
Programs that show cards being drawn from a shuffled deck use random numbers
to represent the face values of the cards.
• Random numbers are useful in simulation programs. In some simulations, the computer must randomly decide how a person, animal, insect, or other living being will
behave. Formulas can be constructed in which a random number is used to determine various actions and events that take place in the program.
• Random numbers are useful in statistical programs that must randomly select data
for analysis.
• Random numbers are commonly used in computer security to encrypt sensitive data.
The .N ET Framework provides a class named Random that you can use in C# to generate
random numbers. First you create an object from the Random class with a statement such
as this:
Random rand = new Random();
Let’s dissect the statement into two parts. The first part of the statement, appearing on the
left side of the = operator, is as follows:
Random rand = new Random();
This declares a variable named rand
that can reference a Random object.
This declares a variable named rand that can be used to reference a Random object. The
second part of the statement, appearing on the right side of the = operator, is as follows:
Random rand = new Random();
This creates a Random object
in memory.
The expression new Random() causes an object of the Random class to be created in
memory. The = operator causes the rand variable to reference the Random object, as
illustrated in Figure 5-46. After this statement has executed, we can use the rand variable
to work with the Random object.
F ig u r e 5 -4 6
T h e rand v a r i a b l e r e f e r e n c e s a Random o b j e c t
rand
Random object
T h e Next M e t h o d
Once you have created a Random object, you can call its Next method to get a random
integer number. The following code shows an example:
// Declare an int variable.
int number;
325
326
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
// Create a Random object.
Random rand = new Random();
// Get a random integer and assign it to number.
number = rand.Next();
After this code executes, the number variable contains a random integer. If you call the
Next method with no arguments, as shown in this example, the returned integer is somewhere between 0 and 2,147,483,647. Alternatively, you can pass an argument that specifies an upper limit to the generated number’s range. In the following statement, the value
assigned to number is somewhere between 0 and 99:
number = rand.Next(100);
The random integer’s range does not have to begin at zero. You can add or subtract a
value to shift the numeric range upward or downward. In the following statement, we call
the Next method to get a random number in the range of 0 through 9, and then we add 1
to it. So, the number assigned to number is somewhere in the range of 1 through 10:
number = rand.Next(10) + 1;
The following statement shows another example. It assigns a random integer to number
between −50 and +49:
number = rand.Next(100) − 50
T h e NextDouble M e t h o d
You can call a Random object’s NextDouble method to get a random floating-point number between 0.0 and 1.0 (not including 1.0). The following code shows an example:
// Declare a Double variable.
double number;
// Create a Random object.
Random rand = new Random();
// Get a random number and assign it to number.
number = rand.NextDouble();
After this code executes, the number variable will contain a random floating-point number in the range of 0.0 up to (but not including) 1.0.
In Tutorial 5-8, you will use random numbers to determine whether the heads or tails side
of a coin is facing up after the coin has been tossed.
T u t o r ia l 5 -8 :
S im u la t in g C o in T o s s e s
VideoNot e
T u to r ia l 5 -8 :
Simulating
Coin Tosses
In this tutorial, you create an application that simulates the tossing of a coin. Each time
the user tosses the coin, the application uses a Random object to get a random integer in
the range of 0 through 1. If the random number is 0, it means the tails side of the coin
is up, and if the random number is 1, it means the heads side is up. The application
displays an image of a coin showing either heads or tails, depending on the value of the
random number.
S t e p 1 :
Start Visual Studio and begin a new Windows Forms Application project named
Coin Toss.
5 .8
S t e p 2 :
Set up the application’s form as shown in Figure 5-47. N otice that the form’s
Text property is set to Coin Toss. The names of the controls are shown in the
figure. As you place each of the controls on the form, refer to Table 5-1 for
t h e r e l e v a n t p r o p e r t y s e t t i n g s . ( M a k e s u r e t h e headsPictureBox c o n t r o l ’ s
V i s i b l e p r o p e r t y i s s e t t o T r u e , a n d t h e tailsPictureBox c o n t r o l ’ s V i s i b l e
p r o p e r ty is s e t to F a ls e . T h is w ill c a u s e th e c o in to in itia lly a p p e a r h e a d s u p
w h e n th e a p p lic a tio n r u n s .)
F ig u r e 5 -4 7
I n i t i a l s e t u p o f t h e Coin Toss f o r m
headsPictureBox
tailsPictureBox
tossButton
T a b le 5 -1
R a n d o m N u m b e rs
exitButton
C o n t r o l p r o p e r t y s e t t in g s
Co n tro l Name
Co n tro l Typ e
P r o p e r ty S e ttin g s
headsPictureBox
P ic tu r e B o x
Im a g e : S e le c t a n d im p o r t th e H e a d s 1 .b m p file
f r o m t h e Chap05 f o l d e r o f t h e S t u d e n t S a m p l e
P ro grams.
S iz e : 1 7 0 , 1 7 0
S iz e M o d e : Z o o m
V is ib le : T r u e
tailsPictureBox
P ic tu r e B o x
Im a g e : S e le c t a n d im p o r t th e T a ils 1 .b m p file
f r o m t h e Chap05 f o l d e r o f t h e S t u d e n t S a m p l e
P ro grams.
S iz e : 1 7 0 , 1 7 0
S iz e M o d e : Z o o m
V is ib le : F a ls e
tossButton
Bu tto n
T e x t : Toss
exitButton
Bu tto n
T e x t : Exit
S t e p 3 :
A fte r y o u h a v e s e t a ll o f th e c o n tr o l p r o p e r tie s a s s h o w n in T a b le 5 -1 , m o v e th e
P ic tu r e B o x c o n tr o ls s o o n e is o n to p o f th e o th e r , a s s h o w n in F ig u r e 5 -4 8 . (In
t h e f i g u r e , t h e headsPictureBox c o n t r o l i s o n t o p , b u t i t r e a l l y d o e s n ’ t m a t t e r
w h ic h is o n to p .) A ls o , r e d u c e th e w id th o f th e fo r m a n d p o s itio n th e b u tto n
c o n tr o ls a s s h o w n in th e fig u r e .
327
328
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
F ig u r e 5 -4 8
T h e c o n t r o ls r e p o s it io n e d a n d t h e fo r m s iz e a d ju s t e d
The headsPictureBox control is on
top of the tailsPictureBox control
S t e p 4 :
N ow you will create the Click event handlers for the Button controls. At the end
of this tutorial, Program 5-8 shows the completed code for the form. You will
be instructed to refer to Program 5-8 as you write the event handlers.
In the D esigner, double-click the tossButton control. This opens the code
editor, and you will see an empty event handler named tossButton_Click.
Complete the tossButton_Click event handler by typing the code shown in
lines 22–44 in Program 5-8. Let’s take a closer look at the code:
L i n e 2 3 : This statement declares an int variable named sideUp. This variable is
used to hold a random number that indicates which side of the coin is up.
L i n e 2 6 : This statement does the following:
• It declares a variable named rand that can be used to reference a Random object.
• It creates a Random object in memory.
• The = operator causes the rand variable to reference the Random object.
L i n e 3 0 : This statement gets a random integer in the range of 0 through 1 and
assigns it to the sideUp variable. The random integer represents which side of
the coin is facing up. The value 0 means that the tails side is facing up, and the
value 1 means that the heads side is facing up.
L i n e s 3 3 – 4 4 : This if-else statement displays the side of the coin that is facing
up. If sideUp equals 0, then the statements in lines 36 and 37 display the
tailsPictureBox control and hide the headsPictureBox control. If sideUp
equals 1, then the statements in lines 42 and 43 display the headsPictureBox
control and hide the tailsPictureBox control.
S t e p 5 :
Switch your view back to the D esigner and double-click the exitButton
control. In the code editor you will see an empty event handler named
exitButton_Click. Complete the exitButton_Click event handler by typing
the code shown in lines 49–50 in Program 5-8.
S t e p 6 :
Save the project. Then, press
on the keyboard or click the Start D ebugging
button ( ) on the toolbar to compile and run the application. When the application runs, click the Toss button several times to simulate several coin tosses.
When you are finished, click the Exit button to exit the application.
5 .8
P r o g r a m 5 -8
R a n d o m N u m b e rs
C o m p l e t e d c o d e f o r F o r m 1 i n t h e Coin Toss a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Coin_Toss
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void tossButton_Click(object sender, EventArgs e)
21
{
22
// Variable to indicate which side is up
23
int sideUp;
24
25
// Create a Random object.
26
Random rand = new Random();
27
28
// Get a random integer in the range of 0 through 1.
29
// 0 means tails up, 1 means heads up.
30
sideUp = rand.Next(2);
31
32
// Display the side that is up.
33
if (sideUp == 0)
34
{
35
// Display tails up.
36
tailsPictureBox.Visible = true;
37
headsPictureBox.Visible = false;
38
}
39
else
40
{
41
// Display heads up.
42
headsPictureBox.Visible = true;
43
tailsPictureBox.Visible = false;
44
}
45
}
46
47
private void exitButton_Click(object sender, EventArgs e)
48
{
49
// Close the form.
50
this.Close();
51
}
52
}
53 }
329
330
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
R a n d o m N u m b e r S e e d s
The numbers that are generated by the Random class are not truly random. Instead, they
are p s e u d o r a n d o m n u m b e r s that are calculated by a formula. The formula used to generate random numbers has to be initialized with a value known as a seed value. The s e e d
v a l u e is used in the calculation that returns the next random number in the series. When a
Random object is created in memory, it retrieves the system time from the computer’s
internal clock and uses that as the seed value. The system time is an integer that represents
the current date and time, down to a hundredth of a second.
If a Random object uses the same seed value each time it is created, it always generates the same
series of random numbers. Because the system time changes every hundredth of a second, it is
the preferred value to use as the seed in most cases. However, you can specify a different integer value as the seed, if you desire, when you create a Random object. Here is an example:
Random rand = new Random(1000);
In this example, the Random object that is created uses 1000 as the seed value. Each time
a Random object is created with this statement, it generates the same series of random
numbers. That may be desirable in some applications, when you always want to produce
the same set of pseudorandom numbers.
C h e c k p o in t
5.35 What does a Random object’s Next method return?
5.36 What does a Random object’s NextDouble method return?
5.37 Write code that creates a Random object and then assigns a random integer in the
range of 1 through 100 to the variable randomNumber.
5.38 Write code that creates a Random object and then assigns a random integer in the
range of 100 through 399 to the variable randomNumber.
5.39 What does a Random object use as its seed value if you do not specify one?
5.40 What happens if the same seed value is used each time a Random object is created?
5 .9
T h e L o a d E v e n t
C O N C E P T :
W h e n a n a p p lic a tio n ’s fo r m lo a d s in to m e m o r y , a n e v e n t k n o w n a s th e
L o a d e v e n t ta k e s p la c e . Y o u c a n w r ite a n e v e n t h a n d le r fo r th e L o a d e v e n t,
a n d th a t h a n d le r w ill e x e c u te ju s t b e fo r e th e fo r m is d is p la y e d .
When you run an application, the application’s form is loaded into memory and an event
known as the L o a d e v e n t takes place. The Load event takes place before the form is displayed on the screen. If you want to execute some code at this point, you can write a Load
event handler containing the desired code.
To create a Load event handler for a form, simply double-click any area of the form in the
D esigner window where there is no other control. The code editor will open with an empty
Load event handler. If the form is named Form1, the event handler is named Form1_Load.
Any code that you write inside the event handler executes when the form’s Load event takes
place. H ere is an example of a Load event handler in a form named Form1:
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("Prepare to see the form!");
}
5 .9
T h e L o a d E v e n t
Keep in mind that the Load event happens before the form is displayed on the screen.
When the application containing this event handler runs, the message box is displayed
before the form appears.
Load event handlers are useful for performing setup operations. In Tutorial 5-9, you will
complete an application that uses a Load event handler to read items from a text file and
add those items to a ListBox control.
T u t o r ia l 5 -9 :
C r e a t in g a L o a d E v e n t H a n d le r
VideoNot e
T u to r ia l 5 -9 :
Creating a
Load Event
H andler
In this tutorial, you complete the L oad Event application that is found in the Chap05
folder of this book’s Student Sample Programs. This application is a variation of the
South America application that you created in Tutorial 5-6. This version of the application uses a Load event handler to read the contents of the Countries.txt file and adds
those items to a ListBox control.
The application’s form has already been created and is shown in Figure 5-49. The application also has an accompanying text file named Countries.txt, that is stored in the
bin\D ebug folder, under the project folder. The Countries.txt file contains the names of
the countries of South America.
F ig u r e 5 -4 9
T h e Loa d Event a p p l i c a t i o n ’ s f o r m
countriesListBox
exitButton
S t e p 1 :
Start Visual Studio. Open the project named L oad Event in the Chap05 folder
of this book’s Student Sample Programs.
S t e p 2 :
Open the Form1 form’s code in the code editor. Insert the using System.IO;
directive shown in line 10 of Program 5-9 at the end of this tutorial. This statement is necessary because you will be using the StreamReader class, which is
part of the System.IO namespace in the .N ET Framework.
S t e p 3 :
Open the Form1 form in the D esigner. The form is shown, along with the names
of the important controls, in Figure 5-49. Double-click any part of the form that
does not contain a control. (Be sure not to click the Label control, the ListBox
control, or the Button control.) This opens the code editor, and you will see an
empty event handler named Form1_Load. Complete the Form1_Load event handler by typing the code shown in lines 23–46 in Program 5-9. Let’s take a closer
look at the code:
331
332
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
L i n e 2 3 : This is the beginning of a try-catch statement, which handles any
exceptions that are thrown while the file is being processed. If an exception is
thrown by any statement in the try block, the program jumps to the catch
clause in line 47.
L i n e 2 6 : This statement declares the string variable countryName, which
holds the lines of text that are read from the file.
L i n e s 2 9 – 3 2 : After these statements have executed, the Countries.txt file is
opened for reading, and the inputFile variable references a StreamReader
object that is associated with the file.
L i n e 3 5 : This is the beginning of a while loop that iterates as long as the end of
the Countries.txt file has not been reached.
L i n e 3 8 : This statement reads a line of text from the file and assigns it to the
countryName variable.
L i n e 4 1 : This statement adds the contents of the countryName variable to the
ListBox.
L i n e 4 5 : This statement closes the file.
S t e p 4 :
Switch your view back to the D esigner and double-click the exitButton
control. In the code editor you will see an empty event handler named
exitButton_Click. Complete the exitButton_Click event handler by typing
the code shown in lines 56–57 in Program 5-9.
S t e p 5 :
Save the project. Then, press
on the keyboard or click the Start D ebugging
button ( ) on the toolbar to compile and run the application. When the application runs, the ListBox should appear filled with the names of the countries
from the Countries.txt file, as shown in Figure 5-50. Click the Exit button to
exit the application.
F ig u r e 5 -5 0
T h e Loa d Event a p p l i c a t i o n d i s p l a y i n g t h e l i s t o f c o u n t r i e s
P r o g r a m 5 -9
C o m p l e t e d c o d e f o r F o r m 1 i n t h e Loa d Event a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
5 .9
T h e L o a d E v e n t
10 using System.IO;
11
12 namespace Load_Event
13 {
14
public partial class Form1 : Form
15
{
16
public Form1()
17
{
18
InitializeComponent();
19
}
20
21
private void Form1_Load(object sender, EventArgs e)
22
{
23
try
24
{
25
// Declare a variable to hold a country name.
26
string countryName;
27
28
// Declare a StreamReader variable.
29
StreamReader inputFile;
30
31
// Open the file and get a StreamReader object.
32
inputFile = File.OpenText("Countries.txt");
33
34
// Read the file's contents.
35
while (!inputFile.EndOfStream)
36
{
37
// Get a country name.
38
countryName = inputFile.ReadLine();
39
40
// Add the country name to the ListBox.
41
countriesListBox.Items.Add(countryName);
42
}
43
// Close the file.
44
45
inputFile.Close();
46
}
47
catch (Exception ex)
48
{
49
// Display an error message.
50
MessageBox.Show(ex.Message);
51
}
52
}
53
54
private void exitButton_Click(object sender, EventArgs e)
55
{
56
// Close the form.
57
this.Close();
58
}
59
}
60 }
C h e c k p o in t
5.41 When does the Load event take place?
5.42 H ow do you create an event handler for the Load event?
333
334
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
K e y T e r m s
accumulator
binary file
body
component tray
counter variable
decrement
direct access file
file object
filename
filename extensions
Filename property
increment
InitialDirectory property
initialization expression
input file
Items.Add method
Items.Clear method
Items.Count property
iteration
Load event
newline character
Next method
O pen dialog box
OpenFileDialog control
output file
postfix mode
posttest loop
prefix mode
pretest loop
pseudorandom numbers
random access file
read position
ReadLine method
running total
Save As dialog box
SaveFileDialog control
seed value
sequential access file
StreamReader class
StreamWriter class
test expression
text file
Title property
update expression
while clause
Write method
WriteLine method
R e v ie w Q u e s t io n s
M u lt ip le C h o ic e
1 .
ListBox controls have an __________ method that erases all the items in the Items
property.
a. Items.Erase
b. Items.Remove
c. Items.Clear
d. Items.Empty
2 .
A __________ is commonly used to control the number of times that a loop iterates.
a.
b.
c.
d.
3 .
A(n) __________ loop tests its condition before performing an iteration.
a.
b.
c.
d.
4 .
counter variable
test expression
while clause
controlled variable
preemptive
pretest
infinite
logical
The term __________ is used to describe a file that data is written to.
a. input file
b. output file
R e v ie w Q u e s t io n s
c. saved file
d. user file
5 .
The term __________ file is used to describe a file that data is read from.
a.
b.
c.
d.
6 .
A __________ file contains data that has been encoded as text, using a scheme such
as Unicode.
a.
b.
c.
d.
7 .
input locator
accumulator
read position
sequential read value
When the user selects a file with the O pen dialog box, the file’s path and filename
are stored in the control’s __________ property.
a.
b.
c.
d.
1 2 .
data
directory
stream
file
When a program works with an input file, a special value known as a(n) __________
is internally maintained for that file and marks the location of the next item that will
be read from the file.
a.
b.
c.
d.
1 1 .
unique identifier
filename
binary sequencer
file extension
A __________ object is an object that is associated with a specific file and provides a
way for the program to work with that file.
a.
b.
c.
d.
1 0 .
direct access
random access
sequential access
binary access
Files on a disk are identified by a __________.
a.
b.
c.
d.
9 .
text
character
Unicode
system
When you work with a __________ file you access data from the beginning of the
file to the end of the file.
a.
b.
c.
d.
8 .
data
write
read
input
Filename
FilePath
Pathname
Text
The __________ control displays a standard Windows Save As dialog box.
a.
b.
c.
d.
SaveAsDialog
FileDialog
SaveFileDialog
StandardDialog
335
336
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
1 3 .
Once you have created a Random object, you can call its __________ method to get a
random integer number.
a.
b.
c.
d.
1 4 .
When generating random numbers, the __________ value is used in the calculation
that returns the next random number in the series.
a.
b.
c.
d.
1 5 .
Generate
Rand
NextInteger
Next
Start
seed
Next
sequence
When you run an application, the application’s form is loaded into memory and an
event known as the __________ event takes place.
a.
b.
c.
d.
Startup
Begin
Load
Initialize
T r u e o r F a ls e
1 .
If the ListBox is empty, the Items.Count property equals −1.
2 .
The while loop is known as a pretest loop, which means it tests its condition before
performing an iteration.
3 .
To increment a variable means to increase its value and to decrement a variable
means to decrease its value.
4 .
When a variable is declared in the initialization expression of a for loop, the scope
of the variable is limited to the loop.
5 .
The while loop always performs at least one iteration, even if its Boolean expression is false to begin with.
6 .
The term read file is used to describe a file that data is read from.
7 .
To append data to an existing file, you open it with the File.AppendText method.
8 .
As items are read from the file, the read position moves forward, toward the end of
the file.
9 .
The numbers that are generated by the Random class are truly random.
1 0 .
The Load event takes place after the form is displayed on the screen.
S h o r t A n s w e r
1 .
What is contained in the body of a loop?
2 .
Write a programming statement that uses postfix mode to increment a variable
named count.
3 .
H ow many iterations will occur if the test expression of a for loop is false to
begin with?
4 .
What are filename extensions? What do they indicate about a file?
5 .
When an input file is opened, what is its read position initially set to?
P r o g r a m m in g P r o b le m s
6 .
H ow can you read all of the items in a file without knowing how many items the
file contains?
7 .
What is a variable that is used to accumulate a total called?
8 .
By default, the O pen dialog box displays the contents of the user’s D ocuments
directory. H ow can you specify another directory to be initially displayed?
9 .
Why is the system time the preferred seed value for a Random object?
1 0 .
What kind of code should be placed in the Load event?
A lg o r it h m W o r k b e n c h
1 .
Write a loop that displays your name 10 times.
2 .
Write a loop that displays all the odd numbers from 1 through 49.
3 .
Write a loop that displays every fifth number from 0 through 100.
4 .
Write a code sample that uses a loop to write the numbers from 1 through 10 to
a file.
5 .
Assume that a file named People.txt contains a list of names. Write a code sample
that uses a while loop to read the file and display its contents in a ListBox control.
P r o g r a m m in g P r o b le m s
1 .
D is ta n c e C a lc u la to r
If you know a vehicle’s speed and the amount of time it has traveled, you can calculate the distance it has traveled as follows:
D istance = Speed × Time
For example, if a train travels 40 miles per hour for 3 hours, the distance traveled is
120 miles. Create an application with a form similar to the one shown in Figure 5-51.
The user enters a vehicle’s speed and the number of hours traveled into text boxes.
When the user clicks the Calculate button, the application should use a loop
to d is p la y in a lis t b o x th e d is ta n c e th e v e h ic le h a s tr a v e le d fo r e a c h h o u r o f th a t
tim e p e r io d .
F ig u r e 5 -5 1
T h e Dista nce Ca lcula tor a p p l i c a t i o n
337
338
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
2 .
D is ta n c e F ile
M odify the D istance Calculator p r o g r a m t h a t y o u w r o t e f o r P r o g r a m m i n g P r o b l e m 1
s o it w r ite s its o u tp u t to a file in s te a d o f d is p la y in g it in a L is tB o x c o n tr o l. O p e n th e
file in N o te p a d o r Vis u a l S tu d io to c o n fir m th e o u tp u t.
3 .
C e ls iu s to F a h r e n h e it Ta b le
A s s u m in g th a t Cis a C e ls iu s te m p e r a tu r e , th e fo llo w in g fo r m u la c o n v e r ts th e te m p e r a t u r e t o a F a h r e n h e i t t e m p e r a t u r e ( F) :
VideoNot e
S o lv in g th e
C e ls iu s to
F a h r e n h e it
T a b le
p r o b le m
F=
5
9
C+ 3 2
C r e a te a n a p p lic a tio n th a t d is p la y s a ta b le o f th e C e ls iu s te m p e r a tu r e s 0 – 2 0 a n d
th e ir F a h r e n h e it e q u iv a le n ts . T h e a p p lic a tio n s h o u ld u s e a lo o p to d is p la y th e te m p e r a tu r e s in a lis t b o x .
4 .
P o p u la tio n
C r e a te a n a p p lic a tio n th a t p r e d ic ts th e a p p r o x im a te s iz e o f a p o p u la tio n o f o r g a n is m s . T h e a p p lic a tio n s h o u ld u s e te x t b o x e s to a llo w th e u s e r to e n te r th e s ta r tin g
n u m b e r o f o r g a n is m s , th e a v e r a g e d a ily p o p u la tio n in c r e a s e (a s a p e r c e n ta g e ), a n d
th e n u m b e r o f d a y s th e o r g a n is m s w ill b e le ft to m u ltip ly . F o r e x a m p le , a s s u m e th e
u s e r e n te r s th e fo llo w in g v a lu e s :
S ta r tin g n u m b e r o f o r g a n is m s : 2
A v e r a g e d a ily in c r e a s e : 3 0 %
N u m b e r o f d a y s to m u ltip ly : 1 0
T h e a p p lic a tio n s h o u ld d is p la y th e fo llo w in g ta b le o f d a ta in a L is tB o x c o n tr o l:
Day
5 .
A p p r o x im a te P o p u la tio n
1
2
2
2 .6
3
3 .3 8
4
4 .3 9 4
5
5 .7 1 2 2
6
7 .4 2 5 8 6
7
9 .6 5 3 6 1 9
8
1 2 .5 4 9 7
9
1 6 .3 1 4 6 2
1 0
2 1 .2 0 9
P e n n ie s fo r P a y
S u s a n is h ir e d fo r a jo b , a n d h e r e m p lo y e r a g r e e s to p a y h e r e v e r y d a y . H e r e m p lo y e r
a l s o a g r e e s t h a t S u s a n ’s s a l a r y i s 1 p e n n y t h e f i r s t d a y , 2 p e n n i e s t h e s e c o n d d a y ,
4 p e n n ie s th e th ir d d a y , c o n tin u in g to d o u b le e a c h d a y . C r e a te a n a p p lic a tio n th a t
a llo w s th e u s e r to e n te r th e n u m b e r o f d a y s th a t S u s a n w ill w o r k a n d c a lc u la te s th e
to ta l a m o u n t o f p a y s h e w ill r e c e iv e o v e r th a t p e r io d o f tim e .
6 .
O c e a n L e v e ls
A s s u m i n g t h e o c e a n ’s l e v e l i s c u r r e n t l y r i s i n g a t a b o u t 1 . 5 m i l l i m e t e r s p e r y e a r , c r e a te a n a p p lic a tio n th a t d is p la y s th e n u m b e r o f m illim e te r s th a t th e o c e a n w ill h a v e
r is e n e a c h y e a r fo r th e n e x t 1 0 y e a r s . D is p la y th e o u tp u t in a L is tB o x c o n tr o l.
P r o g r a m m in g P r o b le m s
7 .
C a lo r ie s B u r n e d
Running on a particular treadmill, you burn 3.9 calories per minute. Create an
application that uses a loop to display the number of calories burned after 10, 15,
20, 25, and 30 minutes. Display the output in a ListBox control.
8 .
Tu itio n In c r e a s e
At one college the tuition for a full-time student is $6000 per semester. It has been
announced that the tuition will increase by 2 percent each year for the next five
years. Create an application with a loop that displays the projected semester tuition
amount for the next 5 years in a ListBox control.
9 .
D ic e S im u la to r
Create an application that simulates rolling a pair of dice. When the user clicks a button, the application should generate two random numbers, each in the range of
1 th r o u g h 6 , to r e p r e s e n t th e v a lu e o f th e d ic e . U s e P ic tu r e B o x c o n tr o ls to d is p la y th e
d i c e . ( I n t h e S t u d e n t S a m p l e P r o g r a m s , i n t h e Chap05 f o l d e r , y o u w i l l f i n d s i x i m a g e s
n a m e d D ie 1 .b m p , D ie 2 .b m p , D ie 3 .b m p , D ie 4 .b m p , D ie 5 .b m p , a n d D ie 6 .b m p th a t
y o u c a n u s e in th e P ic tu r e B o x e s .)
1 0 .
A d d itio n Tu to r
C r e a te a n a p p lic a tio n th a t g e n e r a te s tw o r a n d o m in te g e r s , e a c h in th e r a n g e o f 1 0 0
th r o u g h 5 0 0 . T h e n u m b e r s s h o u ld b e d is p la y e d a s a d d itio n p r o b le m s o n th e a p p lic a t i o n ’s f o r m , s u c h a s
2 4 7 + 1 2 9 = ?
T h e f o r m s h o u l d h a v e a t e x t b o x f o r t h e u s e r t o e n t e r t h e p r o b l e m ’s a n s w e r . W h e n a
b u tto n is c lic k e d , th e a p p lic a tio n s h o u ld d o th e fo llo w in g :
• Check the user’s input and display a message indicating whether it is the correct
an swer.
• Generate two new random numbers and display them in a new problem on the form.
1 1 .
R a n d o m N u m b e r G u e s s in g G a m e
C r e a te a n a p p lic a tio n th a t g e n e r a te s a r a n d o m n u m b e r in th e r a n g e o f 1 th r o u g h
1 0 0 a n d a s k s t h e u s e r t o g u e s s w h a t t h e n u m b e r i s . I f t h e u s e r ’s g u e s s i s h i g h e r t h a n
t h e r a n d o m n u m b e r , t h e p r o g r a m s h o u l d d i s p l a y “ T o o h i g h , t r y a g a i n . ” I f t h e u s e r ’s
g u e s s is lo w e r th a n th e r a n d o m n u m b e r, th e p r o g r a m s h o u ld d is p la y “ To o lo w, tr y
a g a in .” If th e u s e r g u e s s e s th e n u m b e r, th e a p p lic a tio n s h o u ld c o n g r a tu la te th e u s e r
a n d th e n g e n e r a te a n e w r a n d o m n u m b e r s o th e g a m e c a n s ta r t o v e r.
O p tio n a l E n h a n c e m e n t: E n h a n c e th e g a m e s o it k e e p s c o u n t o f th e n u m b e r o f
g u e s s e s th a t th e u s e r m a k e s . W h e n th e u s e r c o r r e c tly g u e s s e s th e r a n d o m n u m b e r,
th e p r o g r a m s h o u ld d is p la y th e n u m b e r o f g u e s s e s .
1 2 .
C a lc u la tin g th e F a c to r ia l o f a N u m b e r
I n m a t h e m a t i c s , t h e n o t a t i o n n! r e p r e s e n t s t h e f a c t o r i a l o f t h e n o n n e g a t i v e i n t e g e r n.
T h e f a c t o r i a l o f n i s t h e p r o d u c t o f a l l t h e n o n n e g a t i v e i n t e g e r s f r o m 1 t h r o u g h n.
F o r e x a m p le ,
7 ! = 1 × 2 × 3 × 4 × 5 × 6 × 7 = 5 ,0 4 0
an d
4 ! = 1 × 2 × 3 × 4 = 2 4
C r e a te a n a p p lic a tio n th a t le ts th e u s e r e n te r a n o n n e g a tiv e in te g e r a n d th e n u s e s a
lo o p to c a lc u la te th e fa c to r ia l o f th a t n u m b e r. D is p la y th e fa c to r ia l in a la b e l o r a
message b o x .
339
340
C h a p te r 5
L o o p s , F ile s , a n d R a n d o m N u m b e r s
1 3 .
R a n d o m N u m b e r F ile Wr ite r
Create an application that writes a series of random numbers to a file. Each random
number should be in the range of 1 through 100. The application should let the user
specify how many random numbers the file will hold and should use a SaveFileDialog
control to let the user specify the file’s name and location.
1 4 .
R a n d o m N u m b e r F ile R e a d e r
This exercise assumes you have completed Programming Problem 13, Random
N umber File Writer. Create another application that uses an OpenFileDialog control to let the user select the file that was created by the application that you wrote
for Problem 13. This application should read the numbers from the file, display the
numbers in a ListBox control, and then display the following data:
• The total of the numbers
• The number of random numbers read from the file
C H A P T E R
M o d u la r iz in g Y o u r C o d e
w it h M e t h o d s
6
T O P I C S
6 .1
6 .1
In t r o d u c t io n t o M e t h o d s
6 .4
P a s s in g A r g u m e n t s b y R e fe r e n c e
6 .2
void M e t h o d s
6 .5
V a lu e - R e t u r n in g M e t h o d s
6 .3
P a s s in g A r g u m e n t s t o M e t h o d s
6 .6
D e b u g g in g M e t h o d s
In t r o d u c t io n t o M e t h o d s
C O N C E P T :
M e th o d s c a n b e u s e d to b r e a k a c o m p le x p r o g r a m in to s m a ll, m a n a g e a b le
p i e c e s . A void m e t h o d s i m p l y e x e c u t e s a g r o u p o f s t a t e m e n t s a n d t h e n
te r m in a te s . A v a lu e -r e tu r n in g m e th o d r e tu r n s a v a lu e to th e s ta te m e n t th a t
c a lle d it.
In a general sense, a method is a collection of statements that performs a specific task. So
far, you have experienced methods in the following two ways:
• You have created event handlers. An event handler is a special type of method that
responds to events.
• You have executed predefined methods from the .N ET Framework, such as
MessageBox.Show and the TryParse methods.
In this chapter, you will learn how to create your own methods that can be executed just
as you execute the .N ET Framework methods.
M ethods are commonly used to break a problem into small, manageable pieces. Instead
of writing one long method that contains all the statements necessary to solve a problem,
you can write several small methods that each solve a specific part of the problem. These
small methods can then be executed in the desired order to solve the problem. This
approach is sometimes called d i v i d e a n d c o n q u e r because a large problem is divided into
several smaller problems that are easily solved. Figures 6-1 and 6-2 illustrate this idea by
comparing two programs: one that uses a long, complex event handler containing all the
statements necessary to solve a problem and another that divides a problem into smaller
problems, each of which are handled by a separate method.
341
342
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
F ig u r e 6 -1
U s in g o n e lo n g s e q u e n c e o f s t a t e m e n t s t o p e r fo r m a t a s k
namespace Example
{
public partial class Form1 : Form
{
private void myButton_Click(object sender, EventArgs e)
{
statement;
statement;
statement;
statement;
statement;
In this program the task is performed
statement;
by one long seqeunce of statements in
statement;
an event handler.
statement;
statement;
statement;
statement;
statement;
statement;
... and so on.
}
}
}
F ig u r e 6 -2
U s in g m e t h o d s t o d iv id e a n d c o n q u e r a p r o b le m
namespace Example
{
public partial class Form1 : Form
{
private void myButton_Click(object sender, EventArgs e)
{
Method2();
Event
Method3();
Handler
Method4();
}
private void Method2()
{
statement;
statement; Method 2
statement;
}
In this program the task has
been divided into smaller tasks,
each of which is performed
by a separate method.
private void Method3()
{
statement;
statement; Method 3
statement;
}
private void Method4()
{
statement;
statement; Method 4
statement;
}
}
}
In general terms, a program that is broken into smaller units of code, such as methods, is
known as a m o d u l a r i z e d p r o g r a m . M odularization tends to simplify code. If a specific
task is performed in several places in a program, a method can be written once to perform
that task and then be executed any time it is needed. This benefit of using methods is
known as c o d e r e u s e because you are writing the code to perform a task once and then
reusing it each time you need to perform the task.
6 .2
void M e t h o d s
void M e t h o d s a n d V a l u e - R e t u r n i n g M e t h o d s
In this chapter, you will learn to write two types of methods: void methods and valuereturning methods. When you call a void m e t h o d , it simply executes the statements it
contains and then terminates. When you call a v a l u e - r e t u r n i n g m e t h o d , it executes the
statements that it contains and then it returns a value back to the statement that called it.
The Parse methods are good examples of value-returning methods. The first type of
method that you will learn to write is the void method.
6 .2
void M e t h o d s
C O N C E P T :
A void m e t h o d p e r f o r m s a t a s k a n d t h e n t e r m i n a t e s . I t d o e s n o t r e t u r n a
v a lu e b a c k to th e s ta te m e n t th a t c a lle d it.
To create a method you write its definition. A method definition has two parts: a header
and a body. The m e t h o d h e a d e r , which appears at the beginning of a method definition,
lists several important things about the method, including the method’s name. The
m e t h o d b o d y is a collection of statements that are performed when the method is
executed. These statements are enclosed inside a set of curly braces. H ere is an example
of a method definition:
private void DisplayMessage()
{
MessageBox.Show("This is the DisplayMessage method.");
}
T h e M e t h o d H e a d e r
Using the previously shown method definition, Figure 6-3 points out the different parts of
the method header, which is the first line.
F ig u r e 6 -3
P a rts o f th e m e th o d h e a d e r
Access
modifier
Return
type
Method
name
Parentheses
private void DisplayMessage()
{
MessageBox.Show("This is the DisplayMessage method.");
}
Let’s take a closer look at the parts identified in the figure:
• A c c e s s m o d i f i e r —The keyword private is an access modifier. When a method is
declared as private, it can be called only by code inside the same class as the
method. Alternatively, a method that is declared as public can be called by code
that is outside the class. This is important because some applications have multiple
classes, and unless you specifically intend a method to be available to code outside
the class, you should declare it private.
• R e t u r n t y p e —Recall our previous discussion of void and value-returning methods.
When the keyword void appears here, it means that the method is a void method,
and does not return a value. As you will see later in this chapter, a value-returning
method lists a data type here.
343
344
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
• M e t h o d n a m e —You should give each method a descriptive name. In general, the
same rules that apply to variable names also apply to method names. The method in
this example is named DisplayMessage, so we can easily guess what the method
does: It displays a message.
In this book, we use P a s c a l c a s e for method names. Pascal case is like camelCase (the
convention we have been using for variable names), except in a Pascal case name the
first character is always uppercase. It is a standard convention among C# programmers to use Pascal case for method names because it differentiates method names
from variable and field names.
• P a r e n t h e s e s —In the header, the method name is always followed by a set of parentheses. As you will see later in this chapter, you sometimes write declarations inside
the parentheses, but for now, the parentheses will be empty.
N O T E :
The method header is never terminated with a semicolon.
T h e M e t h o d B o d y
Beginning at the line after the method header, one or more statements appear inside a set
of curly braces ({ }). These statements are the method’s body and are performed any time
the module is executed.
When you write a method definition, Visual Studio automatically indents the statements
in the method body. The indentation is not required, but it makes the code easier to read
and debug. By indenting the statements in the body of the method, you visually set them
apart from the surrounding code. This allows you to tell at a glance what part of the
program is part of the method.
D e c la r in g M e t h o d s In s id e a C la s s
M ethods usually belong to a class, so you must write a method’s definition inside the class
to which it is supposed to belong. In this chapter, all the methods that you will write will
belong to an application’s Form1 class. When you write a method’s definition, you write
it inside the Form1 class, as shown in Figure 6-4.
F ig u r e 6 -4
W r i t e m e t h o d d e f i n i t i o n s i n s i d e t h e Form1 c l a s s
Your method definitions will apear
here, inside the Form1 class.
6 .2
void M e t h o d s
C a llin g a M e t h o d
A method executes when it is called. Event handlers are called when specific events take place,
but other methods are executed by method call statements. When a method is called, the program branches to that method and executes the statements in its body. Here is an example of
a method call statement that calls the DisplayMessage method we previously examined:
DisplayMessage();
The statement is simply the name of the method followed by a set of parentheses. Because
it is a complete statement, it is terminated with a semicolon.
Let’s look at a complete program that uses the DisplayMessage method. In the Chap06
folder of this book’s Student Sample Programs is a project named Simple Method. Figure 6-5
shows the application’s form in the D esigner, and Program 6-1 shows the form’s code.
F ig u r e 6 -5
T h e Simple Method a p p l i c a t i o n ’ s f o r m
goButton
P r o g r a m 6 -1
C o d e f o r t h e Simple Method a p p l i c a t i o n ’ s F o r m 1 f o r m
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Simple_Method
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
private void goButton_Click(object sender, EventArgs e)
20
21
{
22
MessageBox.Show("This is the goButton_Click method.");
23
DisplayMessage();
24
MessageBox.Show("Back in the goButton_Click method.");
25
}
26
private void DisplayMessage()
27
28
{
29
MessageBox.Show("This is the DisplayMessage method.");
30
}
31
}
32 }
345
346
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
Let’s step through the code. When the user clicks the Go button, the goButton_Click
event handler executes. Inside the event handler the statement in line 22 displays This is
the goButton_Click method in a message box. Then, line 23 calls the DisplayMessage
method. As a shown in Figure 6-6, the program jumps to the DisplayMessage method
and executes the statements in its body. There is only one statement in the body of the
DisplayMessage method, which is line 29. This statement displays This is the
D isplayM essage method, and then the method ends. As shown in Figure 6-7, the program
jumps back to the part of the program that called the DisplayMessage method and
resumes execution from that point. In this case, the program resumes execution at line 24,
which displays Back in the goButton_Click method. The goButton_Click event handler
ends at line 25.
F ig u r e 6 -6
C a l l i n g t h e DisplayMessage m e t h o d
The program jumps to the
DisplayMessage method and
executes the statement in its body.
F ig u r e 6 -7
T h e DisplayMessage m e t h o d r e t u r n s
When the DisplayMessage
method ends, the program returns
to the part of the program that
called it, and resumes execution
at the point.
When a method is called, some operations are performed “ behind the scenes” so the system will know to where the program should return after the method ends. First, the system saves the memory address of the location to which it should return. This is typically
the statement that appears immediately after the method call. This memory location is
known as the r e t u r n p o i n t . Then, the system jumps to the method and executes the statements in its body. When the method ends, the system jumps back to the return point and
resumes execution.
N O T E : When a program calls a method, programmers commonly say that the control of the program transfers to that method. This simply means that the method
takes control of the program’s execution.
In Tutorial 6-1, you will get hands-on practice writing and calling methods.
6 .2
void M e t h o d s
T u t o r ia l 6 -1 :
C r e a t in g a n d C a llin g M e t h o d s
VideoNot e
T u to r ia l 6 -1 :
Creating
and Calling
M ethods
The Chap06 folder in this book’s Student Sample Programs contains a partially created
project named L ights. In this tutorial, you complete the project so it simulates a light
being turned off or on. The project’s form, in its initial setup, is shown in Figure 6-8.
F ig u r e 6 -8
T h e Lights p r o j e c t ’ s f o r m i n i t s i n i t i a l s e t u p
lightOffPictureBox
lightOnPictureBox
lightStateLabel
switchButton
exitButton
H ere are some details about specific property settings:
• The lightOnPictureBox control’s Visible property is initially set to true.
• The lightOffPictureBox control’s Visible property is initially set to false.
• The lightStateLabel displays either ON or OFF while the application runs to
indicate whether the light is on or off. Initially, this control’s Text property is set
to ON.
At run time, when the user clicks the Switch L ight button, the state of the light is
reversed. In other words, if the light is currently on, it will be turned off. If the light is
currently off, it will be turned on.
When the light is turned on, the following actions take place:
• The lightOnPictureBox control’s Visible property is set to true.
• The lightOffPictureBox control’s Visible property is set to false.
• The lightStateLabel label’s Text property is assigned the string "ON".
When the light is turned off, the following actions take place:
• The lightOffPictureBox control’s Visible property is set to true.
• The lightOnPictureBox control’s Visible property is set to false.
• The lightStateLabel label’s Text property is assigned the string "OFF".
To modularize the code, you create a method named TurnLightOn (containing the
code to turn the light on), and another method named TurnLightOff (containing the
347
348
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
code to turn the light off). When you need to turn the light on, you call the TurnLightOn
method and when you need to turn the light off you call the TurnLightOff method.
S t e p 1 :
Start Visual Studio. Open the project named L ights in the Chap06 folder of this
book’s Student Sample Programs.
S t e p 2 :
Open the Form1 form in the D esigner. The form is shown, along with the names
of the important controls, in Figure 6-8.
S t e p 3 :
M ove the PictureBox controls so one is on top of the other, as shown in Figure 6-9.
(In the figure, the lightOnPictureBox control is on top, but it really does not
matter which is on top.) Also, reduce the width of the form and position the
button controls as shown in the figure.
F ig u r e 6 -9
T h e c o n t r o ls r e p o s it io n e d a n d t h e fo r m s iz e a d ju s t e d
The lightOnPictureBox control is on
top of the lightOffPictureBox control
S t e p 4 :
Program 6-2, at the end of this tutorial, shows the form’s completed code. Open
the code editor and type the code for the TurnLightOn and the TurnLightOff
methods, shown in lines 20–42 of Program 6-2.
Let’s take a closer look at the code. Line 20 is the beginning of a method named
TurnLightOn. The purpose of this method is to simulate the light turning on.
When this method executes, line 23 makes the lightOnPictureBox control visible, line 26 makes the lightOffPictureBox control invisible, and line 29 sets
the lightStateLabel control’s Text property to "ON".
Line 32 is the beginning of a method named TurnLightOff. The purpose of this
method is to simulate the light turning off. When this method executes, line 35
makes the lightOffPictureBox control visible, line 38 makes the lightOnPictureBox control invisible, and line 41 sets the lightStateLabel control’s
Text property to "OFF".
S t e p 5 :
N ext, you create the Click event handlers for the Button controls. Switch back
to the D esigner and double-click the switchButton control. This opens the
code editor, and you will see an empty event handler named switchButton_
Click. Complete the switchButton_Click event handler by typing the code
shown in lines 46–54 in Program 6-2.
Let’s review this code. The if statement in line 47 determines whether the
lightOnPictureBox control is visible. If it is, it means the light is turned on, so
the statement in line 49 calls the TurnLightOff method to turn the light off.
6 .2
void M e t h o d s
Otherwise, the else clause in line 51 takes over, and the TurnLightOn method
is called on line 53 to turn the light on.
S t e p 6 :
Switch your view back to the D esigner and double-click the exitButton control.
In the code editor you will see an empty event handler named exitButton_
Click. Complete the exitButton_Click event handler by typing the code shown
in lines 59–60 in Program 6-2.
S t e p 7 :
Save the project. Then, press
on the keyboard, or click the Start D ebugging
button ( ) on the toolbar to compile and run the application. When the application runs, click the Switch L ight button several times to simulate several coin
tosses. When you are finished, click the Exit button to exit the application.
P r o g r a m 6 -2
C o m p l e t e d c o d e f o r F o r m 1 i n t h e Lights a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Lights
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void TurnLightOn()
21
{
22
// Display the "light on" image.
23
lightOnPictureBox.Visible = true;
24
25
// Hide the "light off" image.
26
lightOffPictureBox.Visible = false;
27
28
// Display the light's state.
29
lightStateLabel.Text = "ON";
30
}
31
32
private void TurnLightOff()
33
{
34
// Display the "light off" image.
35
lightOffPictureBox.Visible = true;
36
37
// Hide the "light on" image.
38
lightOnPictureBox.Visible = false;
39
// Display the light's state.
40
41
lightStateLabel.Text = "OFF";
42
}
43
44
private void switchButton_Click(object sender, EventArgs e)
349
350
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 }
{
// Reverse the state of the light.
if (lightOnPictureBox.Visible == true)
{
TurnLightOff();
}
else
{
TurnLightOn();
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
T o p – D o w n D e s ig n
In this section, we have discussed and demonstrated how methods work. You have seen
how the program jumps to a method when it is called and returns to the part of the program that called the method when the method ends. It is important that you understand
these mechanical aspects of methods.
Just as important as understanding how methods work is understanding how to use
methods to modularize a program. Programmers commonly use a technique known as
t o p –d o w n d e s i g n to break down an algorithm into methods. The process of top–down
design is performed in the following manner:
• The overall task that the program is to perform is broken down into a series
of subtasks.
• Each subtask is examined to determine whether it can be further broken down into
more subtasks. This step is repeated until no more subtasks can be identified.
• Once all of the subtasks have been identified, they are written in code.
This process is called top–down design because the programmer begins by looking at the
topmost level of tasks that must be performed and then breaks down those tasks into
lower levels of subtasks.
N O T E :
The top–down design process is sometimes called s t e p w i s e r e f i n e m e n t .
C h e c k p o in t
6.1 What is the difference between a void method and a value-returning method?
6.2 What two parts does a method definition have?
6.3 What does the phrase “ calling a method” mean?
6.4 When a void method is executing, what happens when the end of the method
is reached?
6.5 Describe the steps involved in the top–down design process.
6 .3
6 .3
P a s s in g A r g u m e n t s t o M e t h o d s
P a s s in g A r g u m e n t s t o M e t h o d s
C O N C E P T :
A n a r g u m e n t is a n y p ie c e o f d a ta th a t is p a s s e d in to a m e th o d w h e n th e
m e th o d is c a lle d . A p a r a m e te r is a v a r ia b le th a t r e c e iv e s a n a r g u m e n t th a t
is p a s s e d in to a m e th o d .
Sometimes it is useful not only to call a method, but also to send one or more pieces of
data into the method. Pieces of data that are sent into a method are known as a r g u m e n t s .
The method can use its arguments in calculations or other operations.
You are already familiar with how to use arguments in a method call. For example, look
at the following statement:
MessageBox.Show("Hello");
This statement calls the MessageBox.Show method and passes the string "Hello" as an
argument. H ere is another example:
number = int.Parse(str);
Assume that number is an int variable and str is a string variable. This statement calls
the int.Parse method, passing the str variable as an argument.
If you are writing a method and you want it to receive arguments when it is called, you
must equip the method with one or more parameter variables. A p a r a m e t e r v a r i a b l e ,
often simply called a p a r a m e t e r , is a special variable that receives an argument when a
method is called. H ere is an example of a method that has a parameter variable:
private void DisplayValue(int value)
{
MessageBox.Show(value.ToString());
}
N otice the int variable declaration that appears inside the parentheses (int value).
This is the declaration of a parameter variable, which enables the DisplayValue method
to accept an int value as an argument. H ere is an example of a call to the DisplayValue
method, passing 5 as an argument:
DisplayValue(5);
This statement executes the DisplayValue method. The argument that is listed inside the
parentheses is assigned to the method’s parameter variable, value. This is illustrated in
Figure 6-10.
F ig u r e 6 -1 0
P a s s i n g t h e v a l u e 5 t o t h e DisplayValue m e t h o d
DisplayValue(5);
The value 5 is assigned
to the value parameter.
private void DisplayValue(int value)
{
MessageBox.Show(value.ToString());
}
Inside the DisplayValue method, the variable value will contain the value of whatever
argument was passed into it. If we pass 5 as the argument, the method will display the
value 5 in a message box.
351
352
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
You may also pass the contents of variables and the values of expressions as arguments.
For example, the following statements call the DisplayValue method with various
arguments passed:
DisplayValue(x);
DisplayValue(x * 4);
DisplayValue(int.Parse("700"));
The first statement is simple. It passes the value of the variable x as the argument to the
DisplayValue method. The second statement is also simple, but it does a little more
work: it passes the result of the expression x * 4 as the argument to the DisplayValue
method. The third statement does even more work. It passes the value returned from the
int.Parse method as the argument to the DisplayValue method. (The int.Parse
method is called first, and its return value is passed to the DisplayValue method.)
In the Chap06 folder of this book’s Student Sample Programs, you will find a project
named Argument D emo that demonstrates this method. Figure 6-11 shows the application’s form, and Program 6-3 shows the form’s code.
F ig u r e 6 -1 1
T h e Argument Demo a p p l i c a t i o n ’ s f o r m
demo2Button
demo3Button
demo1Button
exitButton
P r o g r a m 6 -3
C o d e f o r t h e Argument Demo a p p l i c a t i o n ’ s F o r m 1 f o r m
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Argument_Demo
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void DisplayValue(int value)
21
{
22
MessageBox.Show(value.ToString());
23
}
6 .3
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 }
P a s s in g A r g u m e n t s t o M e t h o d s
private void demo1Button_Click(object sender, EventArgs e)
{
// Call DisplayValue passing 5 as an argument.
DisplayValue(5);
}
private void demo2Button_Click(object sender, EventArgs e)
{
// Call DisplayValue passing the expression 3 + 5
// as an argument.
DisplayValue(3 + 5);
}
private void demo3Button_Click(object sender, EventArgs e)
{
// Use a loop to call DisplayValue 5 times.
for (int count = 0; count < 5; count++)
{
DisplayValue(count);
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
The form has four button controls, and a Click event handler has been written for each
one. In addition to the event handlers, the code contains the DisplayValue method,
which we discussed earlier, in lines 20–23.
If you run the application and click the D emo 1 button, the demo1Button_Click event
handler executes. N otice that in line 28 the DisplayValue method is called, passing 5 as
an argument. This causes a message box to appear showing the value 5.
If you click the D emo 2 button, the demo2Button_Click event handler executes. In line
35 the DisplayValue method is called, passing the expression 3 + 5 as an argument.
This causes a message box to appear showing the value 8.
If you click the D emo 3 button, the demo3Button_Click event handler executes. In line
41 a for loop executes five times, each time passing the count variable as an argument.
This causes a message box to appear five times, showing the values 0 through 4.
N O T E : When calling a method and passing a variable as an argument, simply write
the variable name inside the parentheses of the method call. Do not write the data
type of the argument variable in the method call. For example, the following statement causes an error:
DisplayValue(int x); // Error!
The method call should appear as follows:
DisplayValue(x); // Correct
353
354
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
N O T E : In this text, the values that are passed into a method are called arguments,
and the variables that receive those values are called parameters. There are several
variations of these terms in use. In some circles these terms are switched in meaning.
Also, some call the arguments actual parameters and call the parameters formal
parameters. Others use the terms actual argument and formal argument. Regardless
of which set of terms you use, it is important to be consistent.
In Tutorial 6-2, you will complete an application that calls a method and passes an
argument to it.
T u t o r ia l 6 -2 :
P a s s in g a n A r g u m e n t t o a M e t h o d
VideoNot e
T u to r ia l 6 -2 :
Passing an
Argument to
a M ethod
In this tutorial, you complete the Cards project in the Chap06 folder of this book’s Student
Sample Programs. The project’s form, shown in Figure 6-12, has already been created for
you. The PictureBox controls show the images of three cards. Each PictureBox control’s
Visible property is set to False, so they do not initially appear when the application runs.
After you complete the application, the user can select a card’s name from the ListBox,
click the Show Card button, and the image of the selected card will appear.
F ig u r e 6 -1 2
T h e Ca rds p r o j e c t ’ s f o r m
TenHeartsPictureBox
aceSpadesPictureBox
kingClubsPictureBox
cardListBox
showCardButton
exitButton
S t e p 1 :
Start Visual Studio. Open the project named Cards in the Chap06 folder of this
book’s Student Sample Programs.
S t e p 2 :
Program 6-4, at the end of this tutorial, shows the form’s completed code. Open
the code editor and type the comments and code for the ShowCard method,
shown in lines 20–36 of Program 6-4.
The purpose of the ShowCard method is to display one of the card PictureBox
controls. Let’s take a closer look at the code.
L i n e 2 2 : This is the beginning of the method. The method has a string parameter named card. When we call the method, we pass the item that the user selected
in the ListBox as an argument, and the method displays the specified card.
6 .3
P a s s in g A r g u m e n t s t o M e t h o d s
L i n e s 2 4 – 3 5 : This is a switch statement that tests the value of the card parameter. If card is equal to "Ace of Spades", the program jumps to the case
statement in line 26 and calls the ShowAceSpades method in line 27. If card is
equal to "10 of Hearts", the program jumps to the case statement in line 29
and calls the ShowTenHearts method in line 30. If card is equal to "King of
Clubs" , the program jumps to the case statement in line 32 and calls the
ShowKingClubs method in line 33.
S t e p 3 :
Type the comments and code for the ShowAceSpades method, shown in lines
38–45 of Program 6-4. This method makes the aceSpadesPictureBox control
visible, and the other PictureBox controls invisible.
S t e p 4 :
Type the comments and code for the ShowTenHearts method, shown in lines
47–54 of Program 6-4. This method makes the tenHeartsPictureBox control
visible and the other PictureBox controls invisible.
S t e p 5 :
Type the comments and code for the ShowKingClubs method, shown in lines
56–63 of Program 6-4. This method makes the kingClubsPictureBox control
visible, and the other PictureBox controls invisible.
S t e p 6 :
N ext, you create the Click event handlers for the Button controls. Switch back
to the D esigner and double-click the showCardButton control. This opens the
code editor, and you will see an empty event handler named showCardButton_
Click. Complete the showCardButton_Click event handler by typing the code
shown in lines 67–76 in Program 6-4.
Let’s review this code. The if statement in line 68 determines whether the user
has selected an item in the cardListBox. If a value has been selected, line 70
calls the ShowCard method. N otice that the item that was selected in the ListBox
(converted to a string) is passed as an argument. If the user has not selected an
item in the cardListBox control, the else clause in line 72 takes over, and
lines 74–75 display a message box telling the user to select a card.
S t e p 7 :
Switch your view back to the D esigner and double-click the exitButton control. In the code editor you will see an empty event handler named exitButton_
Click. Complete the exitButton_Click event handler by typing the code
shown in lines 81–82 in Program 6-4.
S t e p 8 :
Save the project. Then, press
on the keyboard or click the Start D ebugging
button ( ) on the toolbar to compile and run the application. Test the application by selecting each card’s name in the ListBox and clicking the Show Card
button. When you are finished, click the Exit button to exit the application.
P r o g r a m 6 -4
C o m p l e t e d c o d e f o r F o r m 1 i n t h e Ca rds a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Cards
12 {
355
356
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// The ShowCard method accepts a string that names
// the selected card, and displays that card.
private void ShowCard(string card)
{
switch (card)
{
case "Ace of Spades" :
ShowAceSpades();
break;
case "10 of Hearts":
ShowTenHearts();
break;
case "King of Clubs":
ShowKingClubs();
break;
}
}
// The ShowAceSpades method makes the Ace of Spades
// visible and the other cards invisible.
private void ShowAceSpades()
{
aceSpadesPictureBox.Visible = true;
tenHeartsPictureBox.Visible = false;
kingClubsPictureBox.Visible = false;
}
// The ShowTenHearts method makes the Ten of Hearts
// visible and the other cards invisible.
private void ShowTenHearts()
{
tenHeartsPictureBox.Visible = true;
aceSpadesPictureBox.Visible = false;
kingClubsPictureBox.Visible = false;
}
// The ShowKingClubs method makes the King of Clubs
// visible and the other cards invisible.
private void ShowKingClubs()
{
kingClubsPictureBox.Visible = true;
aceSpadesPictureBox.Visible = false;
tenHeartsPictureBox.Visible = false;
}
private void showCardButton_Click(object sender, EventArgs e)
{
// If a card is selected in the ListBox, display it.
if (cardListBox.SelectedIndex != −1)
{
ShowCard(cardListBox.SelectedItem.ToString());
}
6 .3
72
73
74
75
76
77
78
79
80
81
82
83
84
85 }
P a s s in g A r g u m e n t s t o M e t h o d s
else
{
MessageBox.Show("Please select a card from " +
"the list box.");
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
A r g u m e n t a n d P a r a m e t e r D a t a T y p e C o m p a t ib ilit y
When you pass an argument to a method, the argument’s data type must be assignment
compatible with the receiving parameter’s data type. Otherwise, an error occurs when
you try to compile the code. We discussed assignment compatibility in Chapter 3. H ere is
a summary of how it applies to argument passing when using strings, ints, doubles,
and decimals:
• You can pass only string arguments into string parameters.
• You can pass int arguments into int parameters, but you cannot pass double or
decimal arguments into int parameters.
• You can pass either double or int arguments into double parameters, but you
cannot pass decimal values into double parameters.
• You can pass either decimal or int arguments to decimal parameters, but you
cannot pass double arguments into decimal parameters.
P a r a m e t e r V a r ia b le S c o p e
Recall from Chapter 3 that a variable’s scope is the part of the program where the variable
may be accessed. A variable is visible only to statements inside the variable’s scope. A
parameter variable’s scope is the method in which the parameter is declared. N o statement
outside the method can access the parameter variable.
P a s s in g M u lt ip le A r g u m e n t s
Often it is useful to pass more than one argument to a method. The following code sample
shows a method that accepts two arguments. The name of the method is ShowMax. It
accepts two int arguments and displays the value of the argument that is the greatest. If
the arguments are equal, it displays a message saying so. (This method can be found in the
M ax project in the Chap06 folder of this book’s Student Sample Programs.)
1 private void ShowMax(int num1, int num2)
2 {
3
if (num1 == num2)
4
{
5
MessageBox.Show("The numbers are equal.");
6
}
7
else if (num1 > num2)
8
{
357
358
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
9
10
11
12
13
14
15 }
MessageBox.Show(num1 + " is the greatest.");
}
else
{
MessageBox.Show(num2 + " is the greatest.");
}
N otice that two parameter variables, num1 and num2, are declared inside the parentheses
in the method header (line 1). This is often referred to as a parameter list. Also notice
that a comma separates the declarations. H ere is an example of a statement that calls
the method:
ShowMax(5, 10);
This statement passes the arguments 5 and 10 to the method. The arguments are passed
into the parameter variables according to their positions. In other words, the first argument is passed into the first parameter variable, the second argument is passed into the
second parameter variable, and so forth. So, this statement causes 5 to be passed into
the num1 parameter and 10 to be passed into the num2 parameter. This is illustrated in
Figure 6-13.
F ig u r e 6 -1 3
T w o a r g u m e n t s p a s s e d a c c o r d in g t o p o s it io n t o a m e t h o d
ShowMax(5, 10);
private void ShowMax(int num1, int num2)
{
if (num1 == num2)
{
MessageBox.Show("The numbers are equal.");
}
else if (num1 > num2)
{
MessageBox.Show(num1 + " is the greatest.");
}
else
{
MessageBox.Show(num2 + " is the greatest.");
}
}
Suppose we were to reverse the order in which the arguments are listed in the method call,
as shown here:
ShowMax(10, 5);
This causes 10 to be passed into the num1 parameter and 5 to be passed into the num2
parameter. The following code sample shows one more example. This time we are passing
variables as arguments.
int value1 = 2;
int value2 = 3;
ShowMax(value1, value2);
When the ShowMax method executes as a result of this code, the num1 parameter contains
2 and the num2 parameter contains 3.
6 .3
P a s s in g A r g u m e n t s t o M e t h o d s
N O T E : You have to write the data type for each parameter variable that is declared
in a parameter list. For example, a compiler error would occur if the parameter list
for the ShowMax method were written as shown here:
private void ShowMax(int num1, num2) // Error!
A data type for both the num1 and num2 parameter variables must be listed, as
shown here:
private void ShowMax(int num1, int num2)
N a m e d A r g u m e n t s
In addition to the conventional approach of positional argument passing (where the first
argument is passed into the method’s first parameter, the second argument is passed into
the method’s second parameter, and so forth), C# also allows you to specify which
parameter an argument should be passed into. To specify which parameter variable the
argument should be passed to, you use the following format to write the argument in the
method call:
parameterName : value
In this format parameterName is the name of a parameter variable and value is the value
being passed to that parameter. An argument that is written using this syntax is known as
a n a m e d a r g u m e n t . To demonstrate, look at the following method:
private void ShowName(string firstName, string lastName)
{
MessageBox.Show(firstName + " " + lastName);
}
The following statement shows how the method can be called using named arguments:
ShowName(lastName : "Smith", firstName : "Suzanne");
This statement specifies that "Smith" should be passed into the lastName parameter and
"Suzanne" should be passed into the firstName parameter. You get the same results as
if you had called the method like this, using positional arguments:
ShowName("Suzanne", "Smith");
D e fa u lt A r g u m e n t s
C# allows you to provide a d e f a u l t a r g u m e n t for a method parameter. When a default
argument is provided for a parameter, it becomes possible to call the method without
explicitly passing an argument into the parameter. H ere is an example of a method that
has a parameter with a default argument:
private void ShowTax(decimal price, decimal taxRate = 0.07m)
{
// Calculate the tax.
decimal tax = price * taxRate;
// Display the tax.
MessageBox.Show("The tax is " + tax.ToString("c"));
}
In this method definition, a default argument is provided for the taxRate parameter.
N otice that the parameter name is followed by an equal sign and a value. The value that
follows the equal sign is the default argument. In this case, the value is 0.07m is the
359
360
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
default argument for the taxRate parameter. Because the taxRate parameter has a
default argument, we have the option of omitting an argument for it when we call the
method. H ere is an example:
ShowTax(100.0m);
This statement calls the ShowTax method, passing the value 100.0m as the argument for
the price parameter. Because we did not pass an argument into the taxRate parameter,
its value will be 0.07m. If we want the taxRate parameter to have a different value, we
can specify an argument for it when we call the method, as shown here:
ShowTax(100.0m, 0.08m);
This statement calls the ShowTax method, passing 100.0m as the argument for the price
parameter and 0.08m as the argument for the taxRate parameter.
H ere are some details to keep in mind when using default arguments:
• Default arguments must be literals or constants. You cannot specify a variable as a
default argument.
• You can provide default arguments for all of the parameters in a method. H owever,
when only some of the parameters have a default argument (as in the previous
example), you must declare the parameters with the default arguments last. For
example, a compiler error would occur if we were to write the ShowTax method
header as shown here:
// Illegal method header!
private void ShowTax(decimal taxRate = 0.07m, decimal price)
• When a method has several parameters with default arguments and you leave out
one of the arguments when you call the method, you have to leave out all the arguments that come after it as well.
P a s s in g A r g u m e n t s b y V a lu e
All the example programs that you have looked at so far pass arguments by value. Arguments and parameter variables are separate items in memory. When an argument is p a s s e d
b y v a l u e , only a copy of the argument’s value is passed into the parameter variable. If the
contents of the parameter variable are changed inside the method, it has no effect on the
argument in the calling part of the program.
For example, the following code comes from the Pass By Value project in the Chap06
folder of this book’s Student Sample Programs. When you run the application and click
the Go button, you see the sequence of message boxes shown in Figure 6-14.
1 private void goButton_Click(object sender, EventArgs e)
2 {
3
int number = 99;
4
5
// Display the value of number.
6
MessageBox.Show("The value of number is " + number);
7
8
// Call ChangeMe, passing number as an argument.
9
ChangeMe(number);
10
// Display the value of number again.
11
12
MessageBox.Show("The value of number is " + number);
13 }
14
6 .3
P a s s in g A r g u m e n t s t o M e t h o d s
15 private void ChangeMe(int myValue)
16 {
17
// Change the value of the myValue parameter.
18
myValue = 0;
19
20
// Display the value of myValue.
21
MessageBox.Show("In ChangeMe, myValue is " + myValue);
22 }
F ig u r e 6 -1 4
S e q u e n c e o f m e s s a g e s d i s p l a y e d b y t h e Pa ss By Va lue a p p l i c a t i o n
This message is displayed
by line 6.
This message is displayed
by line 21.
This message is displayed
by line 12.
Inside the goButton_Click event handler, a local variable named number is declared in
line 3 and initialized with the value 99. As a result, the statement in line 6 displays The
value of number is 99. The number variable’s value is then passed as an argument to the
ChangeMe method in line 9. This means that in the ChangeMe method, the value 99 is
assigned to the myValue parameter variable.
Inside the ChangeMe method, line 18 assigns the value 0 to the myValue parameter variable. This overwrites the value 99 that was passed into the parameter when the method
was called. Line 21 displays the message I n ChangeM e, myValue is 0.
After the ChangeMe method finishes, control of the program returns to the goButton_
Click event handler. When the statement in line 12 executes, the message The value of
number is 99 is displayed. Even though the parameter variable myValue was changed in
the ChangeMe method, the number variable in the goButton_Click event handler was
not modified.
Passing by value works in most situations because arguments are usually sent to methods
for informational purposes only. Typically, when you pass a variable as an argument to a
method, you want that variable to have the same value before and after the method call.
Passing an argument by value guarantees that the argument will not be changed by the
method it is passed into. Sometimes, however, you want a method to be able to change
the value of a variable that was passed as an argument to it. This requires a slightly different type of argument passing, which is discussed in the next section.
361
362
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
C h e c k p o in t
6.6 What is the purpose of an argument?
6.7 Briefly summarize how assignment compatibility applies to argument passing.
6.8 What is the scope of a parameter variable?
6.9 What is a named argument?
6.10 What does it mean when an argument is passed by value?
6 .4
P a s s in g A r g u m e n t s b y R e fe r e n c e
C O N C E P T :
W h e n a n a r g u m e n t is p a s s e d b y r e fe r e n c e to a m e th o d , th e m e th o d c a n
c h a n g e th e v a lu e o f th e a r g u m e n t in th e c a llin g p a r t o f th e p r o g r a m .
When you want a method to be able to change the value of a variable that is passed to it
as an argument, the variable must be p a s s e d b y r e f e r e n c e . In C#, there are two ways to
pass an argument by reference:
• You can use a reference parameter in the method.
• You can use an output parameter in the method.
U s in g R e fe r e n c e P a r a m e t e r s
A r e f e r e n c e p a r a m e t e r is a special type of parameter variable. When you pass an argument
into a reference parameter, the reference parameter does not receive a copy of the argument’s
value. Instead, it becomes a reference to the argument that was passed into it. Anything that is
done to the reference parameter is actually done to the argument that it references.
Reference parameters are useful for establishing two-way communication between
methods. When a method calls another method and passes an argument by reference,
communication between the methods can take place in the following ways:
• The calling method can communicate with the called method by passing an argument.
• The called method can communicate with the calling method by modifying the value
of the argument via the reference parameter.
In C#, you declare a reference parameter by writing the ref keyword before the parameter variable’s data type. For example, look at the following method:
private void SetToZero(ref int number)
{
number = 0;
}
Inside the parentheses, the keyword ref indicates that number is a reference variable.
The method assigns 0 to the number parameter. Because number is a reference
parameter, this action is actually performed on the variable that was passed to the
method as an argument.
When you call a method that has a reference parameter, you must also write the keyword
ref before the argument. The following code sample shows an example:
int myVar = 99;
SetToZero(ref myVar);
6 .4
P a s s in g A r g u m e n t s b y R e fe r e n c e
The first statement declares myVar as an int variable, initialized with the value 99. The
second statement calls the SetToZero method, passing myVar by reference. After the
method call, the myVar variable is set to the value 0.
When you pass an argument to a ref parameter, that argument must already be set to
some value. For example, if a variable has not been initialized or assigned a value, you
cannot pass it as an argument into a ref parameter. The following code sample causes a
compiler error:
int myVar;
// Declare myVar with no initial value.
SetToZero(ref myVar); // Error! myVar is not set to a value.
Let’s look at a complete program that uses the SetToZero method. In the Chap06 folder
of this book’s Student Sample Programs, you will find a project named Pass By Ref.
Figure 6-15 shows the application’s form, and Program 6-5 shows the form’s code.
F ig u r e 6 -1 5
T h e Pa ss By Ref a p p l i c a t i o n ’ s f o r m
outputListBox
goButton
P r o g r a m 6 -5
exitButton
C o d e f o r t h e Pa ss By Ref a p p l i c a t i o n ’ s F o r m 1 f o r m
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Pass_By_Ref
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
// The SetToZero method accepts an int argument
21
// by reference and sets it to zero.
22
private void SetToZero(ref int number)
23
{
24
number = 0;
363
364
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56 }
}
private void goButton_Click(object sender, EventArgs e)
{
// Declare some local int variables.
int x = 99, y = 100, z = 101;
// Display the values in those variables.
outputListBox.Items.Clear();
outputListBox.Items.Add("x is set to " + x);
outputListBox.Items.Add("y is set to " + y);
outputListBox.Items.Add("z is set to " + z);
// Pass each variable to SetToZero.
SetToZero(ref x);
SetToZero(ref y);
SetToZero(ref z);
// Display the values in those variables again.
outputListBox.Items.Add("--------------------");
outputListBox.Items.Add("x is set to " + x);
outputListBox.Items.Add("y is set to " + y);
outputListBox.Items.Add("z is set to " + z);
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
N otice that the form has a ListBox control named outputListBox. This ListBox is used
to display the program’s output. The SetToZero method that we previously discussed
appears in lines 22–25. The method accepts an int argument by reference and assigns the
value 0 to the argument.
In the goButton_Click method, line 30 declares the int variables x, y, and z and initializes them to the values 99, 100, and 101, respectively. Line 33 clears the outputListBox
control, and lines 34–36 display the values of the x, y, and z variables in the ListBox.
In lines 39–41 x, y, and z variables are passed as arguments, by reference, to the SetToZero
method. Each time SetToZero is called, the variable that is passed as an argument is
assigned the value 0. This is shown when the x, y, and z variables are displayed again in
lines 45–47. Figure 6-16 shows the application’s form after the Go button has been clicked.
F ig u r e 6 -1 6
T h e Pa ss By Ref a p p l i c a t i o n ’ s o u t p u t
6 .4
P a s s in g A r g u m e n t s b y R e fe r e n c e
U s in g O u t p u t P a r a m e t e r s
An o u t p u t p a r a m e t e r works like a reference parameter. When you pass an argument into an
output parameter, the output parameter becomes a reference to the argument that is passed
into it. Anything that is done to the output parameter is actually done to the argument that it
references. Output parameters are different from reference parameters in the following ways:
• An argument does not have to be set to a value before it is passed into an output parameter. For example, an uninitialized variable can be passed into an
output parameter.
• A method that has an output parameter must set the output parameter to some
value before it finishes executing.
In C#, you declare an output parameter by writing the out keyword before the parameter
variable’s data type. For example, we could modify the SetToZero method in the following way to make the number parameter an output parameter:
private void SetToZero(out int number)
{
number = 0;
}
When you call a method that has an output parameter, you must also write the keyword
out before the argument. The following code sample shows an example:
int myVar;
SetToZero(out myVar);
The first statement declares myVar as an uninitialized int variable. The second statement
calls the SetToZero method, passing myVar into the output parameter. After the method
call, the myVar variable is set to the value 0.
Tutorial 6-3 gives you some experience writing a method that uses an ouput parameter.
T u t o r ia l 6 -3 :
U s in g a n O u t p u t P a r a m e t e r
VideoNot e
T u to r ia l 6 -3 :
Using an
Output
Parameter
In this tutorial, you complete the N orth America application that is found in the Chap06
folder of this book’s Student Sample Programs. The application’s form has already been
created and is shown in Figure 6-17. The application also has an accompanying text file
F ig u r e 6 -1 7
T h e North America a p p l i c a t i o n ’ s f o r m
countriesListBox
getCountriesButton
exitButton
365
366
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
named N orthAmerica.txt that is stored in the Chap06 folder. The N orthAmerica. txt file
contains the names of the countries of N orth America.
When the completed application runs and the user clicks the Get Countries button, the
application uses an OpenFileDialog control to let the user select a file. The application reads
each country name from the file and adds each one to the countriesListBox control.
S t e p 1 :
Start Visual Studio. Open the project named N orth America in the Chap06
folder of this book’s Student Sample Programs.
S t e p 2 :
Open Form1 in the D esigner and add an OpenFileDialog control to the form.
Change the control’s name to openFile and clear the contents of the control’s
Filename property.
S t e p 3 :
Open the Form1 form’s code in the code editor. Insert the using System.IO;
directive shown in line 10 of Program 6-6 at the end of this tutorial. This statement is necessary because you will be using the StreamReader class, which is
part of the System.IO namespace in the .N ET Framework.
S t e p 4 :
Type the comments and code for the GetFileName method, shown in lines
21–34 of Program 6-6. The purpose of the GetFileName method is to let the
user select the file that should be opened. Let’s take a closer look at the code.
L i n e 2 4 : This is the beginning of the method. The method has a string output
parameter named selectedFile. When we call the method, we pass a string
variable as an argument. The method lets the user select the file that should be
opened and stores its filename and path in the selectedFile parameter.
L i n e s 2 6 – 3 3 : This if statement calls the openFile control’s ShowDialog
method. If the user clicks the O pen button, the method returns the value
DialogResult.OK, and line 28 assigns the name of the selected file to the
selectedFile parameter. If the user clicks the Cancel button, line 32 assigns
an empty string to the selectedFile parameter.
S t e p 5 :
Type the comments and code for the GetCountries method, shown in lines
36–70 of Program 6-6. In a nutshell, this method accepts a filename as an
argument, reads the contents of the specified file, and adds them to the
countriesListBox control. H ere is a more detailed description of each part
of the method:
L i n e 4 1 : This is the beginning of a try-catch statement, which handles any
exceptions that are thrown while the file is being processed. If an exception is
thrown by any statement in the try block, the program will jump to the catch
clause in line 68.
L i n e 4 4 : This statement declares the string variable countryName, which
holds the lines of text that are read from the file.
L i n e 4 7 : This statement declares the StreamReader variable inputFile.
L i n e 5 0 : After this statement has executed, the file specified by the filename
parameter is opened for reading, and the inputFile variable references a
StreamReader object that is associated with the file.
L i n e 5 3 : This statement clears anything that might be displayed in the
countriesListBox control.
L i n e 5 6 : This is the beginning of a while loop that iterates as long as the end of
the file has not been reached.
L i n e 5 9 : This statement reads a line of text from the file and assigns it to the
countryName variable.
6 .4
P a s s in g A r g u m e n t s b y R e fe r e n c e
L i n e 6 2 : This statement adds the contents of the countryName variable to the
ListBox.
L i n e 6 6 : This statement closes the file.
S t e p 6 :
Open the Form1 form in the D esigner. Double-click the getCountriesButton
control. This opens the code editor, and you will see an empty event handler
named getCountriesButton_Click. Complete the getCountriesButton_
Click event handler by typing the code shown in lines 77–83 in Program 6-6.
Let’s take a closer look at the code:
L i n e 7 7 : This statement declares a string variable named filename.
L i n e 8 0 : This statement calls the GetFileName method, passing the filename
variable as an argument. When the method returns, the filename variable contains the name of the file selected by the user.
L i n e 8 3 : This statement calls the GetCountries method, passing the filename
variable as an argument. The method opens the specified file and fills the
countriesListBox control with its contents.
S t e p 7 :
Switch your view back to the D esigner and double-click the exitButton control.
In the code editor you will see an empty event handler named exitButton_
Click. Complete the exitButton_Click event handler by typing the code shown
in lines 88–89 in Program 6-6.
S t e p 8 :
Save the project. Then, press
on the keyboard or click the Start D ebugging
button ( ) on the toolbar to compile and run the application. When the application runs, click the Get Countries button. An O pen dialog box should appear.
N avigate to the Chap06 folder in the Student Sample Programs, select the
N orthAmerica.txt file, and click the O pen button. This should fill the ListBox
with the names of the countries from the selected file, as shown in Figure 6-18.
Click the Exit button to exit the application.
F ig u r e 6 -1 8
T h e North America a p p l i c a t i o n d i s p l a y i n g t h e l i s t o f c o u n t r i e s
P r o g r a m 6 -6
C o m p l e t e d c o d e f o r F o r m 1 i n t h e North America a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
367
368
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10 using System.IO;
11
12 namespace North_America
13 {
14
public partial class Form1 : Form
15
{
16
public Form1()
17
{
18
InitializeComponent();
19
}
20
21
// The GetFileName method gets a filename from the
22
// user and assigns it to the variable passed as
23
// an argument.
24
private void GetFileName(out string selectedFile)
25
{
26
if (openFile.ShowDialog() == DialogResult.OK)
27
{
28
selectedFile = openFile.FileName;
29
}
30
else
31
{
32
selectedFile = "";
33
}
34
}
35
36
// The GetCountries method accpets a filename as an
37
// argument. It opens the specified file and displays
38
// its contents in the countriesListBox control.
39
private void GetCountries(string filename)
40
{
41
try
42
{
43
// Declare a variable to hold a country name.
44
string countryName;
45
46
// Declare a StreamReader variable.
47
StreamReader inputFile;
48
49
// Open the file and get a StreamReader object.
50
inputFile = File.OpenText(filename);
51
52
// Clear anything currently in the ListBox.
53
countriesListBox.Items.Clear();
54
55
// Read the file's contents.
56
while (!inputFile.EndOfStream)
57
{
58
// Get a country name.
59
countryName = inputFile.ReadLine();
60
61
// Add the country name to the ListBox.
62
countriesListBox.Items.Add(countryName);
63
}
64
6 .5
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92 }
V a lu e - R e t u r n in g M e t h o d s
// Close the file.
inputFile.Close();
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
}
}
private void getCountriesButton_Click(object sender, EventArgs e)
{
string filename;
// To hold the filename
// Get the filename from the user.
GetFileName(out filename);
// Get the countries from the file.
GetCountries(filename);
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
C h e c k p o in t
6.11 What is a reference parameter?
6.12 H ow can methods communicate using reference parameters?
6.13 What keyword is used to specify a reference parameter?
6.14 What is an output parameter?
6 .5
V a lu e -R e t u r n in g M e t h o d s
C O N C E P T :
A v a lu e -r e tu r n in g m e th o d is a m e th o d th a t r e tu r n s a v a lu e to th e p a r t o f
th e p r o g r a m th a t c a lle d it.
A value-returning method is like a void method in the following ways:
• It contains a group of statements that perform a specific task.
• When you want to execute the method, you call it.
When a value-returning method finishes, however, it returns a value to the statement that
called it. The value that is returned from a method can be used like any other value: It can
be assigned to a variable, displayed on the screen, used in a mathematical expression (if it
is a number), and so forth.
You have already used many of the value-returning methods that are in the .N ET Framework. For example, the int.Parse method accepts a string as an argument and returns
369
370
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
the value of the string converted to an int. Let’s review how that method works. In the
following statement, assume number is an int variable:
number = int.Parse("100");
F ig u r e 6 -1 9
A s t a t e m e n t t h a t c a l l s t h e int.Parse m e t h o d
Argument
number = int.Parse("100");
Method call
The part of the statement that reads int.Parse("100") is a call to the int.Parse method,
with the string "100" passed as an argument. Figure 6-19 illustrates this part of the statement.
N otice that the call to the int.Parse method appears on the right side of an = operator.
When the method is called, it returns an integer. The integer that is returned is assigned to
the number variable, as shown in Figure 6-20.
F ig u r e 6 -2 0
T h e int.Parse m e t h o d r e t u r n s a v a l u e
100
number = int.Parse("100");
The value 100 is returned from the
method and assigned to number.
W r it in g Y o u r O w n V a lu e -R e t u r n in g M e t h o d s
You write a value-returning method in the same way that you write a void method, with
two exceptions:
• You must specify a data type for a value-returning method. The value that is returned
from the method must be of the specified data type.
• A value-returning method must have a return statement. The return statement
causes a value to be returned from the method.
H ere is the general format of a value-returning method definition in C#:
AccessModifier DataType MethodName(ParameterList)
{
statement;
statement;
etc.
return expression;
}
• AccessModifier is an access modifier such as private or public.
• DataType is the data type of the value that the method returns. We commonly call
this the method’s r e t u r n t y p e . For example, if the method returns an integer, the
word int appears here. If the method returns a double value, then the word double
appears here. Likewise, if the method returns a decimal value, the word decimal
appears here.
• MethodName is the name of the method.
• ParameterList is an optional parameter list. If the method does not accept arguments,
then an empty set of parentheses appears.
6 .5
V a lu e - R e t u r n in g M e t h o d s
One of the statements inside the method must be a return statement, which takes the
following form:
return expression;
The value of the expression that follows the keyword return is sent back to the statement that called the method. This can be any value, variable, or expression that has a
value (such as a math expression). The value that is returned must be of the same data
type as that specified in the method header or a compiler error will occur.
H ere is an example of a value-returning method:
private int Sum(int num1, int num2)
{
return num1 + num2;
}
Figure 6-21 illustrates the various parts of the method header. N otice that the method
returns an int, the method’s name is sum, and the method has two int parameters named
num1 and num2.
F ig u r e 6 -2 1
P a rts o f th e m e th o d h e a d e r
This is a private
method
The method
returns an int
The method’s
name is Sum
num1 and num2
are parameters
private int Sum(int num1, int num2)
{
return num1 + num2;
}
The purpose of this method is to accept two int values as arguments and return their
sum. N otice that the return statement returns the value of the expression num1 + num2.
When the return statement executes, the method ends its execution and sends the value
of num1 + num2 back to the part of the program that called the method.
Let’s look at a complete program that demonstrates the Sum method. In the Chap06 folder
of this book’s Student Sample Programs, you will find a project named Sum. Figure 6-22
shows the application’s form, and Program 6-7 shows the form’s code. When you run the
application, you enter two integers into the age1TextBox and age2TextBox controls.
When you click the Calculate Combined Age button, the sum of the two integers is
displayed in the combinedAgeLabel control.
F ig u r e 6 -2 2
T h e Sum a p p l i c a t i o n ’ s f o r m
age1TextBox
age2TextBox
combinedAgeLabel
calculateButton
exitButton
371
372
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
P r o g r a m 6 -7
C o d e f o r t h e Sum a p p l i c a t i o n ’ s F o r m 1 f o r m
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Sum
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
// The Sum method accepts two int arguments
21
// and returns the sum of the arguments.
22
private int Sum(int num1, int num2)
23
{
24
return num1 + num2;
25
}
26
27
private void calculateButton_Click(object sender, EventArgs e)
28
{
29
// Declare variables to hold two ages and their sum.
30
int userAge, friendAge, combinedAge;
31
32
// Get the user's age.
33
if (int.TryParse(age1TextBox.Text, out userAge))
34
{
35
// Get the best friend's age age.
36
if (int.TryParse(age2TextBox.Text, out friendAge))
37
{
38
// Get the sum of the ages.
39
combinedAge = Sum(userAge, friendAge);
40
41
// Display the combined age.
42
combinedAgeLabel.Text = combinedAge.ToString();
43
}
44
else
45
{
46
// Display an error message.
47
MessageBox.Show("Enter an integer for your age.");
48
}
49
}
50
else
51
{
52
// Display an error message.
53
MessageBox.Show("Enter an integer for your age.");
54
}
55
}
56
57
private void exitButton_Click(object sender, EventArgs e)
58
{
59
// Close the form.
6 .5
60
61
62
63 }
V a lu e - R e t u r n in g M e t h o d s
this.Close();
}
}
In line 33, the value entered into the age1TextBox control is converted to an int and
stored in the userAge variable. In line 36, the value entered into the age2TextBox
control is converted to an int and stored in the friendAge variable. Line 39 passes the
userAge and friendAge variables as arguments to the Sum method. The sum of the two
variables is returned from the method and assigned to the combinedAge variable. In line
42 the value of the combinedAge variable is converted to a string and displayed in the
combinedAgeLabel control.
Let’s assume the userAge variable is set to the value 23 and the friendAge variable is set
to the value 25. Figure 6-23 shows how the arguments are passed to the method and how
a value is returned from the method.
F ig u r e 6 -2 3
A r g u m e n t s p a s s e d t o Sum a n d a v a l u e r e t u r n e d
combinedAge = Sum(userAge, friendAge);
25
23
48
private int Sum(int num1, int num2)
{
return num1 + num2;
}
When you call a value-returning method, you usually want to do something meaningful
with the value it returns. In line 39 of Program 6-7 the value that is returned from the Sum
method is assigned to a variable. This is commonly how return values are used, but you
can do many other things with them. For example, the following code shows a math
expression that uses a call to the Sum method:
int x = 10, y = 15;
double average;
average = Sum(x, y) / 2.0;
In the last statement, the Sum method is called with x and y as its arguments. The method’s return value, which is 25, is divided by 2.0. The result, 12.5, is assigned to average.
H ere is another example:
int x = 10, y = 15;
MessageBox.Show("The sum is " + Sum(x, y));
This code sends the Sum method’s return value to MessageBox.Show, so it can be displayed on the screen. The message The sum is 25 is displayed. Remember, a valuereturning method returns a value of a specific data type. You can use the method’s
return value anywhere that you can use a regular value of the same data type. This
means that anywhere an int value can be used, a call to an int value-returning method
can be used. Likewise, anywhere a double value can be used, a call to a double valuereturning method can be used. The same is true for all other data types.
In Tutorial 6-4, you complete an application that converts a value from one unit
of measurement to another. The code will use a value-returning method to perform
the conversion.
373
374
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
T u t o r ia l 6 -4 :
W r it in g a V a lu e - R e t u r n in g M e t h o d
VideoNot e
T u to r ia l 6 -4 :
Writing a
ValueReturning
M ethod
Cups and fluid ounces are common units of measurement for food items. Sometimes,
when a recipe calls for an item measured in cups, you find that in the grocery store the
item is sold in fluid ounces. To know how much you need to purchase for the recipe, you
need to convert the required number of cups to fluid ounces. The formula is:
O unces = Cups × 8
In this tutorial, you complete the Cups To O unces application that is found in the Chap06
folder of this book’s Student Sample Programs. The application’s form has already been
created and is shown in Figure 6-24. When you complete the application, you will be able
to enter a number of cups into the cupsTextBox control, click the Convert button, and
see the equivalent number of fluid ounces in the ouncesLabel control.
F ig u r e 6 -2 4
T h e Cups To Ounces a p p l i c a t i o n ’ s f o r m
cupsTextBox
ouncesLabel
convertButton
exitButton
S t e p 1 :
Start Visual Studio. Open the project named Cups To O unces in the Chap06
folder of this book’s Student Sample Programs.
S t e p 2 :
Open the Form1 form in the D esigner. The form is shown, along with the names
of the important controls, in Figure 6-24.
S t e p 3 :
Program 6-8, at the end of this tutorial, shows the form’s completed code. Open
the code editor and type the comments and code for the CupsToOunces method
shown in lines 20–26 of Program 6-8. The purpose of the method is to accept a
number of cups as an argument and return that value converted to fluid ounces.
You can see in line 23 that the method has a double parameter named cups,
and in line 25 the method returns the value of cups multiplied by 8.
S t e p 4 :
N ow you will create the Click event handlers for the Button controls. Switch
back to the D esigner and double-click the convertButton control. This opens
the code editor, and you will see an empty event handler named convertButton_
Click. Complete the convertButton_Click event handler by typing the code
shown in lines 30–46 in Program 6-8. Let’s review this code:
L i n e 3 1 : This statement declares the cups and ounces variables, which hold the
number of cups and ounces.
L i n e s 3 4 – 4 6 : The if statement in line 34 converts the cupsTextBox control’s
Text property to a double, and the result is stored in the cups variable. If the
6 .5
V a lu e - R e t u r n in g M e t h o d s
conversion is successful, line 37 calls the CupsToOunces method, passing cups
as an argument. The value that is returned from the method is assigned to the
ounces variable, and in line 40 the value of the ounces variable is displayed in
the ouncesLabel control. If the conversion is not successful, line 45 displays an
error message.
S t e p 5 :
Switch your view back to the D esigner and double-click the exitButton control.
In the code editor you will see an empty event handler named exitButton_
Click. Complete the exitButton_Click event handler by typing the code shown
in lines 51–52 in Program 6-8.
S t e p 6 :
Save the project. Then, press
on the keyboard, or click the Start D ebugging
button ( ) on the toolbar to compile and run the application. When the application runs, enter the value 1 into the cupsTextBox control and click the
Convert button. The application should display 8.0 as the number of fluid
ounces. Continue to test the application with other values. When you are finished,
click the Exit button to exit the application.
P r o g r a m 6 -8
C o m p l e t e d c o d e f o r F o r m 1 i n t h e Cups To Ounces a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Cups_To_Ounces
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
// The CupsToOunces method accepts a number
21
// of cups as an argument and returns the
22
// equivalent number of fluid ounces.
23
private double CupsToOunces(double cups)
24
{
25
return cups * 8.0;
26
}
27
28
private void convertButton_Click(object sender, EventArgs e)
29
{
30
// Variables to hold cups and ounces
31
double cups, ounces;
32
// Get the number of cups.
33
34
if (double.TryParse(cupsTextBox.Text, out cups))
35
{
36
// Convert the cups to ounces.
375
376
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55 }
ounces = CupsToOunces(cups);
// Display the ounces.
ouncesLabel.Text = ounces.ToString("n1");
}
else
{
// Display an error message.
MessageBox.Show("Enter a valid number.");
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
B o o le a n M e t h o d s
A Boolean method returns either true or false. You can use a Boolean method to test a
condition, and then return either true or false to indicate whether the condition exists.
Boolean methods are useful for simplifying complex conditions that are tested in decision
and repetition structures.
For example, suppose you are writing a program that will ask the user to enter a number
and then determine whether that number is even or odd. The following code shows how
you can make that determination. Assume number is an int variable containing the number entered by the user.
if (number % 2 == 0)
{
MessageBox.Show("The number is even.");
}
else
{
MessageBox.Show("The number is odd.");
}
The meaning of the Boolean expression being tested by this if-else statement is not
clear, so let’s take a closer look at it:
number % 2 == 0
This expression uses the % operator, which was introduced in Chapter 3. Recall that the
% operator divides two integers and returns the remainder of the division. So, this code
is saying, If the remainder of number divided by 2 is equal to 0, then display a message
indicating the number is even, or else display a message indicating the number is odd.
Because dividing an even number by 2 always gives a remainder of 0, this logic works.
The code would be easier to understand, however, if you could somehow rewrite it to say,
If the number is even, then display a message indicating it is even, or else display a message indicating it is odd. As it turns out, this can be done with a Boolean method. In this
example, you could write a Boolean method named IsEven that accepts an int as an
argument and returns true if the number is even or false otherwise. H ere is an example
how the IsEven method might be written:
6 .5
V a lu e - R e t u r n in g M e t h o d s
private bool IsEven(int number)
{
// Local variable to hold true or false
bool numberIsEven;
// Determine whether the number is even.
if (number % 2 == 0)
{
numberIsEven = true;
}
else
{
numberIsEven = false;
}
// Return the result.
return numberIsEven;
}
Then you can rewrite the if-else statement so it calls the IsEven method to determine
whether number is even:
if (IsEven(number))
{
MessageBox.Show("The number is even.");
}
else
{
MessageBox.Show("The number is odd.");
}
N ot only is this logic easier to understand, but now you have a method that you can call
in the program any time you need to test a number to determine whether it is even. (The
Chap06 folder of this book’s Student Sample Programs has a project named Even N umber
that demonstrates the IsEven method.)
U s in g a B o o le a n M e t h o d t o M o d u la r iz e In p u t V a lid a t io n
Boolean methods can be useful for modularizing input validation. When a form has multiple TextBox controls, the input validation usually requires multiple, nested if statements.
In many cases, you can simplify the code by creating a Boolean method that performs all the
input validation and returns true if all of the input is valid or false if any of it is invalid.
In Tutorial 6-5, you will complete an application that uses this approach.
T u t o r ia l 6 -5 :
M o d u la r iz in g In p u t V a lid a t io n w it h a B o o le a n M e t h o d
VideoNot e
T u to r ia l 6 -5 :
M odularizing
Input
Validation
with a Boolean
M ethod
In addition to regular pay, a company pays its employees an annual bonus. The company
also contributes 5 percent of an employee’s total compensation (gross pay plus bonus) to
a retirement account. In this tutorial, you complete an application that lets you enter an
employee’s gross pay and bonus amount and calculates the amount of retirement contribution. The project is named Pay and Bonus and is found in the Chap06 folder of this
book’s Student Sample Programs. Figure 6-25 shows the application’s form, which has
already been created for you.
S t e p 1 :
Start Visual Studio. Open the project named Pay and Bonus in the Chap06
folder of this book’s Student Sample Programs.
377
378
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
F ig u r e 6 -2 5
T h e Pa y a nd Bonus a p p l i c a t i o n ’ s f o r m
grossPayTextBox
bonusTextBox
contributionLabel
calculateButton
exitButton
S t e p 2 :
Open the Form1 form’s code in the code editor. Insert the comment and constant field declaration shown in lines 15 and 16 of Program 6-9. This constant,
which is set to the value 0.05, is used in the calculation of the retirement
account contribution.
S t e p 3 :
Type the comments and code for the InputIsValid method, shown in lines 23
through 54 of Program 6-9. N otice in line 27 that the method has reference
parameters for gross pay and the bonus amount. The purpose of the method is
to get the values entered by the user, convert them to decimal values, and assign
them to the parameter variables. If the input is successfully converted, the
method returns true. Otherwise, an error message is displayed and the method
returns false to indicate that the input is not valid.
S t e p 4 :
Open the Form1 form in the D esigner. Double-click the calculateButton
control. This opens the code editor, and you will see an empty event handler
named calculateButton_Click. Complete the calculateButton_Click
event handler by typing the code shown in lines 58–68 in Program 6-9. Let’s
take a closer look at the code:
L i n e 5 9 : This statement declares decimal variables to hold the gross pay, bonus
amount, and contribution amount.
L i n e s 6 1 – 6 8 : This if statement calls the InputIsValid method, passing the
grosspay and bonus variables, by reference, as arguments. If the method
returns true, the variables will contain the gross pay and bonus amount entered
by the user. In that case, line 64 calculates the amount of contribution to the
retirement account, and line 67 displays that amount.
S t e p 5 :
Switch your view back to the D esigner and double-click the exitButton control.
In the code editor you will see an empty event handler named exitButton_
Click. Complete the exitButton_Click event handler by typing the code shown
in lines 73–74 in Program 6-9.
S t e p 6 :
Save the project. Then, press
on the keyboard or click the Start D ebugging
button ( ) on the toolbar to compile and run the application. When the application runs, enter 80000 for the gross pay and 20000 for the bonus amount.
Click the Calculate Contribution button. The application should display
$5,000.00 as the amount of contribution. Try other values if you wish. Click
the Exit button to exit the application.
6 .5
P r o g r a m 6 -9
V a lu e - R e t u r n in g M e t h o d s
C o m p l e t e d c o d e f o r F o r m 1 i n t h e Pa y a nd Bonus a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Pay_and_Bonus
12 {
13
public partial class Form1 : Form
14
{
15
// Constant field for the contribution rate
16
private const decimal CONTRIB_RATE = 0.05m;
17
18
public Form1()
19
{
20
InitializeComponent();
21
}
22
// The InputIsValid method converts the user input and stores
23
24
// it in the arguments (passed by reference). If the conversion
25
// is successful, the method returns true. Otherwise it returns
26
// false.
27
private bool InputIsValid(ref decimal pay, ref decimal bonus)
28
{
29
// Flag variable to indicate whether the input is good
30
bool inputGood = false;
31
32
// Try to convert both inputs to decimal.
33
if (decimal.TryParse(grossPayTextBox.Text, out pay))
34
{
35
if (decimal.TryParse(bonusTextBox.Text, out bonus))
36
{
37
// Both inputs are good.
38
inputGood = true;
39
}
40
else
41
{
42
// Display an error message for the bonus.
43
MessageBox.Show("Bonus amount is invalid.");
44
}
45
}
46
else
47
{
48
// Display an error message for gross pay.
49
MessageBox.Show("Gross pay is invalid.");
50
}
51
52
// Return the result.
53
return inputGood;
54
}
55
56
private void calculateButton_Click(object sender, EventArgs e)
57
{
379
384
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
S t e p 3 :
Press the key to run the application in debug mode, enter 80000 for the gross
pay and 20000 for the bonus amount.
S t e p 4 :
Click the Calculate Contribution button. The application enters break mode
with the breakpoint line highlighted.
S t e p 5 :
N otice that the highlighted line contains a call to the InputIsValid method.
Press to execute the Step I nto command.
S t e p 6 :
Because you pressed , the first line of the InputIsValid method is highlighted next. You will now single-step through the statements inside the
InputIsValid method. Continue pressing the
key to single-step through the
InputIsValid method. When the method’s closing brace (}) is highlighted,
press once more to return to the line that called the method.
S t e p 7 :
N ow you can exit break mode, and resume normal execution. Perform one of
the following procedures:
• Click the
button on the toolbar.
• Press .
• Click D ebug on the menu bar, and then click Continue.
After performing any one of these procedures, the application will exit break
mode and resume normal execution. Click the Exit button on the application’s
form to end execution. Leave the project open in Visual Studio. You will use it
in the next tutorial.
T u t o r ia l 6 -7 :
P r a c t i c i n g t h e Step Over C o m m a n d
S t e p 1 :
VideoNot e
T u to r ia l 6 -7 :
Practicing the
Step Over
Command
M ake sure the Pay and Bonus project is still open in Visual Studio from Tutorial
6-6. The breakpoint should still be set as shown in Figure 6-29.
F ig u r e 6 -2 9
S t e p 2 :
L o c a t io n o f b r e a k p o in t
Press the key to run the application in debug mode, enter 80000 for the gross
pay and 20000 for the bonus amount.
6 .6
D e b u g g in g M e t h o d s
S t e p 3 :
Click the Calculate Contribution button. The application enters break mode
with the breakpoint line highlighted.
S t e p 4 :
N otice that the highlighted line contains a call to the InputIsValid method.
Press to execute the Step O ver command. This executes the method without
stepping through it. The next line is now highlighted.
S t e p 5 :
N ow you can exit break mode, and resume normal execution. Perform one of
the following procedures:
• Click the
button on the toolbar.
• Press .
• Click D ebug on the menu bar, and then click Continue.
After performing any one of these procedures, the application will exit break
mode and resume normal execution. Click the Exit button on the application’s
form to end execution. Leave the project open in Visual Studio. You will use it
in the next tutorial.
T u t o r ia l 6 -8 :
P r a c t i c i n g t h e Step Out C o m m a n d
S t e p 1 :
VideoNot e
T u to r ia l 6 -8 :
Practicing the
Step O ut
Command
M ake sure the Pay and Bonus project is still open in Visual Studio from Tutorial
6-6. The breakpoint should still be set as shown in Figure 6-30.
F ig u r e 6 -3 0
L o c a t io n o f b r e a k p o in t
S t e p 2 :
Press the
key to run the application in debug mode, enter 80000 for the
gross pay and 20000 for the bonus amount.
S t e p 3 :
Click the Calculate Contribution button. The application enters break mode
with the breakpoint line highlighted.
S t e p 4 :
N otice that the highlighted line contains a call to the InputIsValid method.
Press to execute the Step I nto command.
385
386
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
S t e p 5 :
Because you pressed
, the first line of the InputIsValid method is
highlighted next. Press the
key once again to advance to the next line in
the method.
S t e p 6 :
Instead of continuing to step through the method, you will now step out of the
method. Press the
+
keys to execute the Step O ut command. Singlestepping is suspended while the remaining statements in the InputIsValid
method execute. You are returned to the calculateButton_Click event
handler at the line containing the method call.
S t e p 7 :
N ow you can exit break mode, and resume normal execution. Perform one
of the following procedures:
• Click the
button on the toolbar.
• Press .
• Click D ebug on the menu bar, and then click Continue.
After performing any one of these procedures, the application will exit
break mode and resume normal execution. Click the Exit button on the
application’s form to end execution.
T I P : When the current execution point does not contain a method call, the Step
I nto and Step O ver commands perform identically.
R e v ie w Q u e s t io n s
K e y T e r m s
arguments
code reuse
default argument
divide and conquer
method body
method header
modularized program
named argument
output parameter
parameter
parameter variable
Pascal case
passed by reference
passed by value
reference parameter
return point
return type
Step I nto command
Step O ut command
Step O ver command
stepwise refinement
top–down design
value-returning method
void method
R e v ie w Q u e s t io n s
M u lt ip le C h o ic e
1 .
In general terms, a program that is broken into smaller units of code, such as methods, is known as a(n) __________.
a. object-oriented program
b. modularized program
c. procedural program
d. method-driven program
2 .
Writing the code to perform a task once and then reusing it each time you need to
perform the task is a benefit of using methods called __________.
a. code reuse
b. the single-use philosophy
c. method recycling
d. code reprocessing
3 .
When you call a(n) __________, it simply executes the statements it contains and
then terminates.
a. intrinsic method
b. empty method
c. logical method
d. void method
4 .
The __________, which appears at the beginning of a method definition, lists several
important things about the method, including the method’s name.
a. method title
b. method description
c. method header
d. method declaration
5 .
The __________ is a collection of statements enclosed inside a set of curly braces
that are performed when the method is executed.
a. method body
b. method designation
c. method code
d. method classification
387
388
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
6 .
The __________ is the memory address that is saved by the system when a method is
called and is the location to which the system should return after a method ends.
a. calling address
b. method address
c. return point
d. come back position
7 .
Programmers commonly use a technique known as __________ to break down an
algorithm into methods.
a. prototyping
b. method modeling
c. algorithm division
d. top–down design
8 .
Pieces of data that are sent into a method are known as __________.
a. arguments
b. references
c. method variables
d. data entries
9 .
A(n) __________ is a special variable that receives an argument when a method is called.
a. reference variable
b. argument variable
c. parameter variable
d. method variable
1 0 .
A __________ specifies which parameter an argument should be passed into.
a.
b.
c.
d.
1 1 .
When a(n)__________ is provided for a parameter, it becomes possible to call the
method without explicitly passing an argument into the parameter.
a.
b.
c.
d.
1 2 .
a named constant
passed by association
passed by reference
passed by value
When you want a method to be able to change the value of a variable that is passed
to it as an argument, the variable must be __________.
a.
b.
c.
d.
1 4 .
local argument
empty argument
default argument
expressional argument
When an argument is __________, only a copy of the argument’s value is passed into
the parameter variable.
a.
b.
c.
d.
1 3 .
named argument
special argument
constant argument
literal argument
passed by reference
a local variable
passed by value
a named constant
A __________ a special type of parameter variable that is useful for establishing
two-way communication between methods.
a. communication variable
b. reference parameter
R e v ie w Q u e s t io n s
c. method parameter
d. global variable
1 5 .
A(n) __________ can have an uninitialized value passed into it, but it must be set to
some value before the method it belongs to finishes executing.
a.
b.
c.
d.
1 6 .
input parameter
reference parameter
output parameter
default parameter
A method’s __________ is the type of value that the method returns.
a.
b.
c.
d.
data type
return type
value type
method type
T r u e o r F a ls e
1 .
Dividing a large problem into several smaller problems that are easily solved is
sometimes called divide and conquer.
2 .
In a Pascal case name, the first character is always uppercase.
3 .
If a method belongs to a class, then you must write a method’s definition inside
the class.
4 .
The contents of variables and the values of expressions cannot be passed as arguments.
5 .
You do not have to write the data type for each parameter variable that is declared
in a parameter list if they are all of the same data type.
6 .
An output parameter works like a by value parameter.
7 .
A value-returning method must contain a return statement.
8 .
A Boolean method returns either yes or no.
S h o r t A n s w e r
1 .
What do you call a method that executes the statements it contains and then returns
a value back to the statement that called it?
2 .
What is the standard naming convention used among C# programmers for method
names? Why?
3 .
What is another name for the top-down design process?
4 .
What is a parameter list?
5 .
H ow do you specify a named argument?
6 .
H ow are output parameters different from reference parameters?
7 .
H ow is a value-returning method like a void method? H ow is it different?
8 .
Can Boolean methods be used to modularize input validation? Why or why not?
A lg o r it h m W o r k b e n c h
1 .
Examine the following method header; then write an example call to the method.
private void ShowValue()
2 .
The following statement calls a method named ShowHalf. The ShowHalf method
displays a value that is half that of the argument. Write the method.
ShowHalf(50);
389
390
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
3 .
4 .
Write the method header for a method named ShowRetailPrice. The method should
include parameter variables for a list price and a markup percentage. Write the method
so that the default argument for the markup percentage is set to 50 percent.
Examine the following method header; then write an example call to the method.
private void ResetValue(ref int value)
5 .
A program contains the following value-returning method:
private int Square(int value)
{
return value * value;
}
Write a statement that passes the value 10 as an argument to this method and assigns
its return value to the variable result.
P r o g r a m m in g P r o b le m s
1 .
R e ta il P r ic e C a lc u la to r
Create an application that lets the user enter an item’s wholesale cost and its markup
percentage. It should then display the item’s retail price. For example:
• If an item’s wholesale cost is $5.00 and its markup percentage is 100 percent,
then the item’s retail price is $10.00.
• If an item’s wholesale cost is $5.00 and its markup percentage is 50 percent, then
the item’s retail price is $7.50.
The program should have a method named CalculateRetail that receives the
wholesale cost and the markup percentage as arguments and returns the retail price
of the item.
2 .
F a llin g D is ta n c e
When an object is falling because of gravity, the following formula can be used to
determine the distance the object falls in a specific time period:
1 2
gt
2
The variables in the formula are as follows: d is the distance in meters, g is 9.8, and
t is the amount of time in seconds that the object has been falling. Create an application that allows the user to enter the amount of time that an object has fallen and
then displays the distance that the object fell. The application should have a method
named FallingDistance. The FallingDistance method should accept an object’s
falling time (in seconds) as an argument. The method should return the distance in
meters that the object has fallen during that time interval.
d=
3 .
K in e tic E n e r g y
In physics, an object that is in motion is said to have kinetic energy. The following
formula can be used to determine a moving object’s kinetic energy:
VideoNot e
Solving the
Kinetic Energy
problem
KE =
1
mv2
2
In the formula KE is the kinetic energy, m is the object’s mass in kilograms, and v is
the object’s velocity in meters per second. Create an application that allows the user
to enter an object’s mass and velocity and then displays the object’s kinetic energy.
The application should have a method named KineticEnergy that accepts an
object’s mass (in kilograms) and velocity (in meters per second) as arguments. The
method should return the amount of kinetic energy that the object has.
P r o g r a m m in g P r o b le m s
4 .
C a lo r ie s fr o m F a t a n d C a r b o h y d r a te s
A nutritionist who works for a fitness club helps members by evaluating their diets.
As part of her evaluation, she asks members for the number of fat grams and
carbohydrate grams that they consume in a day. Then, she calculates the number of
calories that result from the fat using the following formula:
Calories from fat = Fat grams × 9
N ext, she calculates the number of calories that result from the carbohydrates using
the following formula:
Calories from carbs = Carbs grams × 4
Create an application that will make these calculations. In the application, you
should have the following methods:
• FatCalories–This method should accept a number of fat grams as an argument
and return the number of calories from that amount of fat.
• CarbCalories– T hi s met hod shoul d accept a number of car bohydr at e
g r a m s a s a n a r g u m e n t a n d r e tu r n th e n u m b e r o f c a lo r ie s fr o m th a t a m o u n t
o f c a r b o h y d r a te s .
5 .
J o e ’s A u t o m o t i v e
J o e ’s A u t o m o t i v e p e r f o r m s t h e f o l l o w i n g r o u t i n e m a i n t e n a n c e s e r v i c e s :
•
•
•
•
•
•
•
Oil change—$26.00
Lube job—$18.00
Radiator flush—$30.00
Transmission flush—$80.00
Inspection—$15.00
M uffler replacement—$100.00
Tire rotation—$20.00
J o e a ls o p e r fo r m s o th e r n o n r o u tin e s e r v ic e s a n d c h a r g e s fo r p a r ts a n d la b o r ($ 2 0 p e r
h o u r ) . C r e a t e a n a p p l i c a t i o n t h a t d i s p l a y s t h e t o t a l f o r a c u s t o m e r ’s v i s i t t o J o e ’s .
T h e fo r m s h o u ld r e s e m b le th e o n e s h o w n in F ig u r e 6 -3 1 .
F ig u r e 6 -3 1
Automotive f o r m
391
392
C h a p te r 6
M o d u la r iz in g Y o u r C o d e w it h M e t h o d s
The application should have the following value-returning methods:
• OilLubeCharges—Returns the total charges for an oil change and/or a lube job,
if any.
• FlushCharges—Returns the total charges for a radiator flush and/or a transmission flush, if any.
• MiscCharges—Returns the total charges for an inspection, muffler replacement,
and/or a tire rotation, if any.
• OtherCharges—Returns the total charges for other services (parts and labor),
if any.
• TaxCharges—Returns the amount of sales tax, if any. Sales tax is 6% and is
charged only on parts. If the customer purchases services only, no sales tax
is charged.
• TotalCharges—Returns the total charges.
The application should have the following void methods, called when the user
clicks the Clear button:
• ClearOilLube—Clears the check boxes for oil change and lube job.
• ClearFlushes—Clears the check boxes for radiator flush and transmission flush.
• ClearMisc—Clears the check boxes for inspection, muffler replacement, and
tire rotation.
• ClearOther—Clears the text boxes for parts and labor.
• ClearFees —Clears the labels that display the labels in the section marked
Summary.
6 .
H o s p ita l C h a r g e s
Create an application that calculates the total cost of a hospital stay. The daily base
charge is $350. The hospital also charges for medication, surgical fees, lab fees, and
physical rehab. The application should accept the following input:
•
•
•
•
•
The number of days spent in the hospital
The amount of medication charges
The amount of surgical charges
The amount of lab fees
The amount of physical rehabilitation charges
Create and use the following value-returning methods in the application:
• CalcStayCharges—Calculates and returns the base charges for the hospital
stay. This is computed as $350 times the number of days in the hospital.
• CalcMiscCharges—Calculates and returns the total of the medication, surgical,
lab, and physical rehabilitation charges.
• CalcTotalCharges—Calculates and returns the total charges.
7 .
P r e s e n t Va lu e
Suppose you want to deposit a certain amount of money into a savings account and
then leave it alone to draw interest for the next 10 years. At the end of 10 years you
would like to have $10,000 in the account. H ow much do you need to deposit today
to make that happen? You can use the following formula, which is known as the
present-value formula, to find out:
F
P=
(1 + r)n
The terms in the formula are as follows:
•
•
•
•
P is the present value, or the amount that you need to deposit today.
F is the future value that you want in the account. (In this case, F is $10,000.)
r is the annual interest rate.
n is the number of years that you plan to let the money sit in the account.
P r o g r a m m in g P r o b le m s
Write a method named PresentValue that performs this calculation. The method
should accept the future value, annual interest rate, and number of years as arguments. It should return the present value, which is the amount that you need to
deposit today. Demonstrate the method in an application that lets the user experiment with different values for the formula’s terms.
8 .
P r im e N u m b e r s
A prime number is a number that can be evenly divided by only itself and 1. For
example, the number 5 is prime because it can be evenly divided by only 1 and 5.
The number 6, however, is not prime because it can be evenly divided by 1, 2, 3, and
6. Write a Boolean method named IsPrime that takes an integer as an argument
and returns true if the argument is a prime number or false otherwise. Use the
method in an application that lets the user enter a number and then displays a message indicating whether the number is prime.
T I P : Recall that the % operator divides one number by another and returns the
remainder of the division. In an expression such as num1 % num2, the % operator
returns 0 if num1 is evenly divisible by num2.
9 .
P r im e N u m b e r L is t
This exercise assumes you have already written the IsPrime method in Programming
Problem 8. Create another application that uses this method to display all the prime
numbers from 1 through 100 in a list box. The program should have a loop that calls
the IsPrime method.
1 0 .
R o c k , P a p e r, S c is s o r s G a m e
Create an application that lets the user play the game of Rock, Paper, Scissors against
the computer. The program should work as follows:
1. When the program begins, a random number in the range of 1 through 3 is generated. If the number is 1, then the computer has chosen rock. If the number is
2, then the computer has chosen paper. If the number is 3, then the computer
has chosen scissors. (Do not display the computer’s choice yet.)
2. The user selects his or her choice of rock, paper, or scissors. To get this input
you can use Button controls, or clickable PictureBox controls displaying some
of the artwork that you will find in the student sample files.
3. The computer’s choice is displayed.
4. A winner is selected according to the following rules:
• If one player chooses rock and the other player chooses scissors, then rock
wins. (Rock smashes scissors.)
• If one player chooses scissors and the other player chooses paper, then scissors wins. (Scissors cuts paper.)
• If one player chooses paper and the other player chooses rock, then paper
wins. (Paper wraps rock.)
• If both players make the same choice, the game must be played again to
determine the winner.
Be sure to modularize the program into methods that perform each major task.
393
This page intentionally left blank
C H A P T E R
7
A r r a y s a n d L is t s
T O P I C S
7 .1
7 .1
V a lu e T y p e s a n d R e fe r e n c e T y p e s
7 .2
A r r a y B a s ic s
7 .3
7 .6
A d v a n c e d A lg o r it h m s fo r S o r t in g a n d
S e a r c h in g A r r a y s
W o r k in g w it h F ile s a n d A r r a y s
7 .7
T w o - D im e n s io n a l A r r a y s
7 .4
P a s s in g A r r a y s a s A r g u m e n t s t o
M e th o d s
7 .8
Ja g g e d A r r a y s
7 .9
T h e List C o l l e c t i o n
7 .5
S o m e U s e fu l A r r a y A lg o r it h m s
V a lu e T y p e s a n d R e fe r e n c e T y p e s
C O N C E P T :
T h e d a ta ty p e s in C # a n d th e .N E T F r a m e w o r k fa ll in to tw o c a te g o r ie s :
v a lu e ty p e s a n d r e fe r e n c e ty p e s .
In this chapter, you will gain more experience working with objects. Specifically, you
will work with arrays and collections, which are objects that store groups of data. Before
we go into the details of creating and working with those objects, it will be helpful for
you to understand how objects are stored in memory. In this section, we discuss the
ways that different types of objects are internally stored by the .N ET Framework. As a
result, you will better understand the concepts presented in this chapter, and chapters
to c o m e .
A ll th e d a ta ty p e s in C # — a n d th e u n d e r ly in g .N E T F r a m e w o r k — fa ll in to tw o c a te g o r ie s :
v a lu e ty p e s a n d r e fe r e n c e ty p e s . O f th e C # d a ta ty p e s th a t y o u h a v e u s e d s o fa r , th e fo ll o w i n g a r e v a l u e t y p e s : int, double, decimal, a n d bool. ( T h e r e a r e o t h e r v a l u e t y p e s i n
a d d itio n to th e s e , b u t th e s e a r e th e o n e s w e fo c u s o n in th is b o o k .)
W h e n y o u d e c la r e a v a lu e ty p e v a r ia b le , th e c o m p ile r s e ts a s id e , o r a llo c a te s , a c h u n k
o f m e m o r y th a t is b ig e n o u g h fo r th a t v a r ia b le . F o r e x a m p le , lo o k a t th e fo llo w in g
v a r ia b le d e c la r a tio n s :
int wholeNumber;
double realNumber;
decimal moneyNumber;
395
396
C h a p te r 7
A r r a y s a n d L is t s
Recall from Chapter 3 that an int uses 32 bits of memory (4 bytes), a double uses 64 bits
of memory (8 bytes), and a decimal uses 128 bits of memory (16 bytes). These declaration statements cause memory to be allocated as shown in Figure 7-1.
F ig u r e 7 -1
M e m o r y a llo c a te d
int wholeNumber;
4 bytes
8 bytes
double realNumber;
16 bytes
decimal moneyNumber;
The memory that is allocated for a value type variable is the actual location that will hold
any value that is assigned to that variable. For example, suppose we use the following
statements to assign values to the variables shown in Figure 7-1:
wholeNumber = 99;
realNumber = 123.45;
moneyNumber = 800.0m;
Figure 7-2 shows how the assigned values are stored in each variable’s memory location.
F ig u r e 7 -2
V a lu e s a s s ig n e d t o t h e v a r ia b le s
int wholeNumber;
99
double realNumber;
123.45
decimal moneyNumber;
800.0
As you can see from these illustrations, value types are very straightforward. When you
are working with a value type, you are using a variable that holds a piece of data.
This is different from the way that reference types work. When you are working with a
reference type, you are using two things:
• An object that is created in memory
• A variable that references the object
The object that is created in memory holds data of some sort and performs operations of some
sort. (Exactly what the data and operations are depends on what kind of object it is.) In order
to work with the object in code, you need some way to refer to it. That’s where the variable
comes in. The variable does not hold an actual piece of data with which your program will
work. Instead, it holds a special value known as a r e f e r e n c e , which links the variable to the
object.1 When you want to work with the object, you use the variable that references it.
1
A reference is similar to a memory address. It is a value that identifies the object’s memory location.
7 .1
V a lu e T y p e s a n d R e fe r e n c e T y p e s
A variable that is used to reference an object is commonly called a r e f e r e n c e v a r i a b l e . Reference variables can be used only to reference objects. Figure 7-3 illustrates two objects
that have been created in memory, each referenced by a variable.
F ig u r e 7 -3
T w o o b je c t s r e fe r e n c e d b y v a r ia b le s
Reference
variable
Object
Reference
variable
Object
To understand how reference variables and objects work together, think about flying a
kite. In order to fly a kite, you need a spool of string attached to it. When the kite is airborne, you use the spool of string to hold onto the kite and control it. This is similar to the
relationship between an object and the variable that references the object. As shown in
Figure 7-4, the object is like the kite, and the variable that references the object is like the
spool of string.
F ig u r e 7 -4
T h e k it e a n d s t r in g m e t a p h o r
Object
Variable referencing
the object
Creating a reference type object typically requires the following two steps:
1. You declare a reference variable.
2. You create the object and associate it with the reference variable.
After you have performed these steps, you can use the reference variable to work with the
object. Let’s look at an example that you have already learned about: creating objects of
the Random class. Recall from Chapter 5 that the Random class allows your program to
generate random numbers. H ere is an example of how you create an object from the
Random class:
Random rand = new Random();
Let’s look at the different parts of this statement:
• The first part of the statement, appearing on the left side of the = operator, reads
Random rand. This declares a variable named rand that can be used to reference an
object of the Random type.
• The second part of the statement, appearing on the right side of the = operator,
reads new Random(). The new o p e r a t o r creates an object in memory and returns a
397
398
C h a p te r 7
A r r a y s a n d L is t s
reference to that object. So, the expression new Random() creates an object from the
Random class and returns a reference to that object.
• The = operator assigns the reference that was returned from the new operator to the
rand variable.
After this statement executes, the rand variable references a Random object, as shown in
Figure 7-5. The rand variable can then be used to perform operations with the object,
such as generating random numbers.
F ig u r e 7 -5
T h e rand v a r i a b l e r e f e r e n c i n g a Random o b j e c t
rand
Random object
C h e c k p o in t
7.1 Into what two categories do the data types in C# and the underlying .N ET Framework fall?
7.2 What is the difference in the way you work with value types and reference types?
7.3 H ow is the relationship between an object and a reference variable similar to a kite
and a spool of string?
7.4 Is a variable of the Random class a reference type or a value type?
7 .2
A r r a y B a s ic s
C O N C E P T :
A n a r r a y a llo w s y o u to s to r e a g r o u p o f ite m s o f th e s a m e d a ta ty p e to g e th e r
in m e m o r y . P r o c e s s in g a la r g e n u m b e r o f ite m s in a n a r r a y is u s u a lly e a s ie r
th a n p r o c e s s in g a la r g e n u m b e r o f ite m s s to r e d in s e p a r a te v a r ia b le s .
In the programs you have written so far, you have used variables to store data in memory.
The simplest way to store a value in memory is to store it in a variable. Variables work
well in many situations, but they have limitations. For example, they can hold only one
value at a time. Consider the following variable declaration:
int number = 99;
This statement declares an int variable named number, initialized with the value 99.
Consider what happens if the following statement appears later in the program:
number = 5;
This statement assigns the value 5 to number, replacing the value 99 that was previously
stored there. Because number is an ordinary variable, it can hold only one value at a time.
Because variables hold only a single value, they can be cumbersome in programs that process lists of data. For example, suppose you are asked to write a program that holds the
names of 50 employees. Imagine declaring 50 variables to hold all those names:
string employee1;
string employee2;
string employee3;
7 .2
A r r a y B a s ic s
and so forth . . .
string employee50
Then, imagine writing the code to process all 50 names. For example, if you wanted to
display the contents of the variables in a ListBox, you would write code such as this:
employeeListBox.Items.Add(employee1);
employeeListBox.Items.Add(employee2);
employeeListBox.Items.Add(employee3);
// Display employee 1
// Display employee 2
// Display employee 3
and so forth . . .
employeeListBox.Items.Add(employee50);
// Display employee 50
As you can see, variables are not well suited for storing and processing lists of data. Each
variable is a separate item that must be declared and individually processed.
Fortunately, you can use an array as an alternative to a group of variables. An a r r a y is an
object that can hold a group of values that are all the same data type. You can have an array
of int values, an array of double values, and array of decimal values, or an array of
string values, but you cannot store a mixture of data types in an array. Once you create an
array, you can write simple and efficient code to process the values that are stored in it.
Arrays are reference type objects. Recall from Section 7.1 that two steps are required to
create and use a reference type object:
1. You declare a reference variable.
2. You create the object and associate it with the reference variable.
Suppose you want to create an array that can hold int values. H ere is an example of how
you might declare a reference variable for the array:
int[] numbersArray;
This statement declares a reference variable named numbersArray. N otice that this statement looks like a regular int variable declaration except for the set of brackets ( [] ) that
appear after the keyword int. The expression int[] indicates that this variable is a reference to an int array. So, we cannot use this variable to store an int value. Rather, we can
use it to reference an int array.
The next step in the process is to create the array object and associate it with the numbersArray variable. The following statement shows an example:
numbersArray = new int[6];
As previously mentioned, the new keyword creates an object in memory. The expression
that appears after the new keyword specifies what type of object to create. In this case, the
expression int[6] specifies that the object should be an array large enough to hold six
int values. The number inside the brackets is the array’s s i z e d e c l a r a t o r . It indicates the
number of values that the array should be able to hold.
The new keyword also returns a reference to the object that it creates. In the previously
shown statement, the new keyword creates an int array and returns a reference to that
array. The = operator assigns the reference to the numbersAray variable. After this statement executes, the numbersArray variable will reference an int array that can hold six
values. This is shown in Figure 7-6.
F ig u r e 7 -6
T h e numbersArray v a r i a b l e r e f e r e n c i n g a n int a r r a y
numbersArray
variable
Array that can hold six int values
399
400
C h a p te r 7
A r r a y s a n d L is t s
In the previous example, we used two statements to (1) declare a reference variable and (2)
create an array object. These two steps can be combined into one statement, as shown here:
int[] numbersArray = new int[6];
You can create arrays of any data. The following are all valid array declarations:
double[] temperatures = new double[100];
decimal[] prices = new decimal[50];
string[] nameArray = new string[1200];
An array’s size declarator must be a nonnegative integer expression. It can be a literal
value, as shown in the previous examples, or a variable. It is a preferred practice to use a
named constant as a size declarator, however. H ere is an example:
const int SIZE = 6;
int[] numbersArray = new int[SIZE];
This practice can make programs easier to maintain. As you will see later in this chapter,
many array-processing techniques require you to refer to the array’s size. When you use a
named constant as an array’s size declarator, you can use the constant to refer to the size
of the array in your algorithms. If you ever need to modify the program so the array is a
different size, you need only change the value of the named constant.
A r r a y E le m e n t s a n d S u b s c r ip t s
The storage locations in an array are known as e l e m e n t s . In memory, an array’s elements
are located in consecutive memory locations. Each element in an array is assigned a unique
number known as a s u b s c r i p t . Subscripts are used to identify specific elements in an array.
The first element is assigned the subscript 0, the second element is assigned the subscript 1,
and so forth. For example, suppose a program has the following declarations:
const int SIZE = 5;
int[] numbersArray = new int[SIZE];
As shown in Figure 7-7, the array referenced by numbersArray has five elements. The
elements are assigned the subscripts 0–4. (Because subscript numbering starts at 0, the
subscript of the last element in an array is 1 less than the total number of elements in
th e a r r a y .)
F ig u r e 7 -7
A r r a y s u b s c r ip t s
numbersArray
variable
0
0
0
0
0
Element
0
Element
1
Element
2
Element
3
Element
4
A r r a y E le m e n t D e fa u lt V a lu e s
N o tic e th a t F ig u r e 7 -7 s h o w s e a c h e le m e n t o f th e a r r a y c o n ta in in g th e v a lu e 0 . W h e n y o u
c r e a te a n u m e r ic a r r a y in C # , its e le m e n ts a r e s e t to th e v a lu e 0 b y d e fa u lt.
R e m e m b e r , y o u c a n c r e a te a n a r r a y to h o ld a n y ty p e o f v a lu e . It is p o s s ib le to c r e a te a n
a r r a y o f r e fe r e n c e ty p e o b je c ts . If y o u c r e a te a n a r r a y o f r e fe r e n c e ty p e o b je c ts , e a c h e le m e n t o f th e a r r a y a c ts a s a r e fe r e n c e v a r ia b le . B y d e fa u lt, th e e le m e n ts o f a n a r r a y o f r e fe r e n c e t y p e o b j e c t s a r e s e t t o t h e s p e c i a l v a l u e null. T h e v a l u e null i n d i c a t e s t h a t a r e f e r e n c e
v a r ia b le is n o t s e t to a v a lid o b je c t a n d c a n n o t b e u s e d fo r a n y m e a n in g fu l p u r p o s e .
7 .2
A r r a y B a s ic s
N O T E : As you will see in Chapter 8, strings are actually reference types, so the
default value of a string array’s elements is null.
W o r k in g w it h A r r a y E le m e n t s
You access the individual elements in an array by using their subscripts. For example,
the following code creates an int array with five elements and assigns values to each of
its elements.
const int SIZE = 5;
int[] numbersArray = new int[SIZE];
numbersArray[0] = 20;
numbersArray[1] = 30;
numbersArray[2] = 40;
numbersArray[3] = 50;
numbersArray[4] = 60;
This code assigns the value 20 to element 0, the value 30 to element 1, and so forth.
Figure 7-8 shows the contents of the array after these statements execute.
F ig u r e 7 -8
V a lu e s a s s ig n e d t o e a c h e le m e n t
numbersArray
variable
20
30
40
50
60
Element
0
Element
1
Element
2
Element
3
Element
4
N O T E : The expression numbersArray[0] is pronounced “ numbersArray
sub zero.”
The following code shows another example. It creates a string array with three elements
and assigns strings to each of its elements.
const int SIZE = 3;
string[] names = new string[SIZE];
names[0] = "Chris";
names[1] = "Laurie";
names[2] = "Joe";
The following code sample shows how values can be assigned from TextBox controls
to array elements. Assume that an application’s form has three TextBox controls
named amount1TextBox, amount2TextBox, and amount3TextBox and that the user
has entered a numeric value into each one. The following code creates a decimal
array named amounts and assigns each of the TextBox control’s input value to an
array element.
const int SIZE = 3;
decimal[] amounts = new decimal[SIZE];
amounts[0] = decimal.Parse(amount1TextBox.Text);
amounts[1] = decimal.Parse(amount2TextBox.Text);
amounts[2] = decimal.Parse(amount3TextBox.Text);
401
402
C h a p te r 7
A r r a y s a n d L is t s
Let’s look at a complete program that demonstrates how to assign values to an array and then
display the values in the array. In the Chap07 folder of this book’s Student Sample Programs,
you will find a project named Display Elements. Figure 7-9 shows the application’s form.
F ig u r e 7 -9
T h e Displa y Elements a p p l i c a t i o n ’ s f o r m
name2TextBox
name3TextBox
name1TextBox
getNamesButton
exitButton
H ere is the code for the getNamesButton_Click event handler:
1 private void getNamesButton_Click(object sender, EventArgs e)
2 {
3
// Create an array to hold three strings.
4
const int SIZE = 3;
5
string[] names = new string[SIZE];
6
7
// Get the names.
8
names[0] = name1TextBox.Text;
9
names[1] = name2TextBox.Text;
10
names[2] = name3TextBox.Text;
11
12
// Display the names.
13
MessageBox.Show(names[0]);
14
MessageBox.Show(names[1]);
15
MessageBox.Show(names[2]);
16 }
Run the application, enter a name into each of the TextBox controls, and then click the
Get N ames button. The following actions take place:
• In line 5, an array to hold three strings is created.
• In lines 8–10, the names that you entered into the TextBox controls are assigned to
the array elements.
• In lines 13–15, each element of the array is displayed in a message box.
The D isplay Elements application displays the contents of a string array. Because the
array’s elements are strings, we can pass each element directly to the MessageBox.Show
method without performing a data type conversion. If you want to pass a numeric array
element to the MessageBox.Show method, however, you will have to call the element’s
ToString method. The following code sample demonstrates:
1 // Create an array to hold three integers.
2 const int SIZE = 3;
3 int[] myValues = new int[SIZE];
4
5 // Assign some values to the array elements.
6 myValues[0] = 10;
7 myValues[1] = 20;
8 myValues[2] = 30;
9
10 // Display the array elements.
7 .2
A r r a y B a s ic s
11 MessageBox.Show(myValues[0].ToString());
12 MessageBox.Show(myValues[1].ToString());
13 MessageBox.Show(myValues[2].ToString());
A r r a y In it ia liz a t io n
When you create an array, you can optionally initialize it with a group of values. H ere is
an example:
const int SIZE = 5;
int[] numbersArray = new int[SIZE] { 10, 20, 30, 40, 50 };
The series of values inside the braces and separated with commas is called an i n i t i a l i z a t i o n
l i s t . These values are stored in the array elements in the order they appear in the list. (The
first value, 10, is stored in numbersArray[0] , the second value, 20, is stored in
numbersArray[1], and so forth.)
When you provide an initialization list, the size declarator can be left out. The compiler
determines the size of the array from the number of items in the initialization list. H ere is
an example:
int[] numbersArray = new int[] { 10, 20, 30, 40, 50 };
In this example, the compiler determines that the array should have five elements because
five values appear in the initialization list.
You can also leave out the new operator and its subsequent expression when an initialization list is provided. H ere is an example:
int[] numbersArray = { 10, 20, 30, 40, 50 };
H ere are three separate examples that declare and initialize a string array named days.
Each of these examples results in the same array:
// Example 1
const int SIZE = 7;
string[] days = new string[SIZE] = { "Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday" };
// Example 2
string[] days = new string[] = { "Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday" };
// Example 3
string[] days = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday",
"Saturday" };
U s in g a L o o p t o S t e p t h r o u g h a n A r r a y
You can store a number in an int variable and then use that variable as a subscript. This
makes it possible to use a loop to step through an array, performing the same operation
on each element. For example, look at the following code sample:
1 // Create an array to hold three integers.
2 const int SIZE = 3;
3 int[] myValues = new int[SIZE];
4
5 // Assign 99 to each array element.
6 for (int index = 0; index < SIZE; index++)
7 {
8
myValues[index] = 99;
9 }
403
404
C h a p te r 7
A r r a y s a n d L is t s
Line 3 creates an int array named myValues with three elements. The for loop that
starts in line 6 uses an int variable named index as its counter. The index variable is
initialized with the value 0 and is incremented after each loop iteration. The loop iterates
as long as index is less than 3. So, the loop will iterate three times. As it iterates, the
index variable is assigned the values 0, 1, and 2.
Inside the loop, the statement in line 8 assigns the value 99 to an array element, using the
index variable as the subscript. This is what happens as the loop iterates:
• The first time the loop iterates, index is set to 0, so 99 is assigned to myValues[0].
• The second time the loop iterates, index is set to 1, so 99 is assigned to myValues[1].
• The third time the loop iterates, index is set to 2, so 99 is assigned to myValues[2].
In v a lid S u b s c r ip t s
When working with an array, it is important that you do not use an invalid subscript.
You cannot use a subscript that is less than 0 or greater than the size of the array minus 1.
For example, suppose an array has 100 elements. The valid subscripts for the array are
the integers 0 through 99. If you try to use any value outside this range, an exception will
be thrown at runtime. The following code sample demonstrates how a loop that is not
carefully written can cause such an exception to be thrown:
1 // Create an array to hold three integers.
2 const int SIZE = 3;
3 int[] myValues = new int[SIZE];
4
5 // Will this loop cause an exception?
6 for (int index = 0; index <= SIZE; index++)
7 {
8
myValues[index] = 99;
9 }
N otice that the for loop iterates as long as index is less than or equal to 3. During the
loop’s last iteration, index is set to 3, so the statement in line 8 attempts to make an
assignment to myValues[3]. There is no element in the array with the subscript 3, so an
exception will be thrown.
T h e L e n g t h P r o p e r t y
In C#, all arrays have a L e n g t h p r o p e r t y that is set to the number of elements in the array.
For example, consider an array created by the following statement:
double[] temperatures = new double[25];
The temperatures array’s Length property will be set to 25. If we executed the following
statement, it would display the message “ The temperatures array has 25 elements.”
MessageBox.Show("The temperatures array has " +
temperatures.Length + " elements.");
The Length property can be useful when processing the entire contents of an array with a
loop. The subscript of the last element is always 1 less than the array’s Length property.
H ere is an example:
for (int index = 0; index < temperatures.Length; index++)
{
MessageBox.Show(temperatures[index].ToString());
}
7 .2
N O T E :
A r r a y B a s ic s
An array’s Length property is read only, so you cannot change its value.
In Tutorial 7-1, you complete an application that generates a set of random numbers
similar to those used in lotteries. The numbers will be stored in an array.
T u t o r ia l 7 -1 :
U s in g a n A r r a y t o H o ld a L is t o f R a n d o m L o t t e r y N u m b e r s
VideoNot e
T u to r ia l 7 -1 :
Using an
Array to
H old a List
of Random
Lottery
N umbers
In this tutorial, you complete an application that randomly generates lottery numbers.
The application’s form is shown in Figure 7-10. When the Generate N umbers button is
clicked, the application will generate five two-digit integer numbers and store them in an
array. The contents of the array will then be displayed in Label controls.
F ig u r e 7 -1 0
T h e Lottery Numbers a p p l i c a t i o n ’ s f o r m
secondLabel
thirdLabel
fourthLabel
firstLabel
fifthLabel
generateButton
exitButton
S t e p 1 :
Start Visual Studio. Open the project named L ottery N umbers in the Chap07
folder of this book’s Student Sample Programs.
S t e p 2 :
Open the Form1 form in the D esigner. Double-click the generateButton control. This will open the code editor, and you will see an empty event handler
named generateButton_Click. Complete the generateButton_Click event
handler by typing the code shown in lines 22–41 in Program 7-1. Let’s take a
closer look at the code:
L i n e 2 3 : This statement declares an int constant named SIZE, set to the value
5. This is used as an array size declarator.
L i n e 2 4 : This statement creates an int array named lotteryNumbers with
five elements.
L i n e 2 7 : This statement creates a Random object, referenced by a variable
named rand.
L i n e 3 1 : This for loop uses an int variable named index as its counter. The
index variable is initialized with the value 0 and is incremented after each loop
iteration. The loop iterates as long as index is less than lotteryNumbers.Length
(which is 5). So, the loop will iterate five times. As it iterates, the index variable
is assigned the values 0, 1, 2, 3, and 4.
L i n e 3 3 : This statement gets a random number in the range of 0 through 99 and
assigns it to lotteryNumbers[index]. The first time the loop iterates, this statement assigns a random number to lotteryNumbers[0]. The second time the
loop iterates, this statement assigns a random number to lotteryNumbers[1].
405
406
C h a p te r 7
A r r a y s a n d L is t s
This continues until the loop is finished. At that time, each element in the array is
assigned a random number.
L i n e s 3 7 – 4 1 : These statements display the array elements in the firstLabel,
secondLabel, thirdLabel, fourthLabel, and fifthLabel controls.
S t e p 3 :
Switch your view back to the D esigner and double-click the exitButton
control. In the code editor you will see an empty event handler named
exitButton_Click. Complete the exitButton_Click event handler by typing
the code shown in lines 46–47 in Program 7-1.
S t e p 4 :
Save the project. Then, press
on the keyboard, or click the Start D ebugging
button ( ) on the toolbar to compile and run the application. When the application runs, click the Generate N umbers button. The application should display
a set of random numbers in the Label controls. Click the Generate N umbers
button several more times to see different sets of random numbers. When you
are finished, click the Exit button to exit the application.
P r o g r a m 7 -1
C o m p l e t e d c o d e f o r F o r m 1 i n t h e Lottery Numbers a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Lottery_Numbers
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void generateButton_Click(object sender, EventArgs e)
21
{
22
// Create an array to hold the numbers.
23
const int SIZE = 5;
24
int[] lotteryNumbers = new int[SIZE];
25
26
// Create a Random object.
27
Random rand = new Random();
28
29
// Fill the array with random numbers, in the range
30
// of 0 through 99.
31
for (int index = 0; index < lotteryNumbers.Length; index++)
32
{
33
lotteryNumbers[index] = rand.Next(100);
34
}
35
36
// Display the array elements in the Label controls.
37
firstLabel.Text = lotteryNumbers[0].ToString();
38
secondLabel.Text = lotteryNumbers[1].ToString();
7 .2
39
40
41
42
43
44
45
46
47
48
49
50 }
A r r a y B a s ic s
thirdLabel.Text = lotteryNumbers[2].ToString();
fourthLabel.Text = lotteryNumbers[3].ToString();
fifthLabel.Text = lotteryNumbers[4].ToString();
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
W a t c h in g fo r O ff-b y -O n e E r r o r s
Because array subscripts start at 0 rather than 1, you have to be careful not to perform an
off-by-one error. An o f f - b y - o n e e r r o r occurs when a loop iterates one time too many or
one time too few. For example, look at the following code sample:
1 // Create an array to hold three integers.
2 const int SIZE = 100;
3 int[] myValues = new int[SIZE];
4
5 // Assign 99 to each array element.
6 for (int index = 1; index < myValues.Length; index++)
7 {
8
myValues[index] = 99;
9 }
The intent of this code is to create an int array with 100 elements and assign the value 99
to each element; however, this code has an off-by-one error. During the loop’s execution,
the index variable is assigned the values 1 through 99 when it should be assigned the
values 0 through 99. As a result, the first element, which is at subscript 0, is skipped.
U s i n g t h e foreach L o o p w i t h A r r a y s
C# provides a special loop that, in many circumstances, simplifies array processing. It is
known as the foreach l o o p . When you use the foreach loop with an array, the loop
automatically iterates once for each element in the array. For example, if you use the
foreach loop with an eight-element array, the loop will iterate eight times. Because the
foreach loop automatically knows the number of elements in an array, you do not have
to use a counter variable to control its iterations, as with a regular for loop.
The foreach loop is designed to work with a temporary, read-only variable known as the
i t e r a t i o n v a r i a b l e . Each time the foreach loop iterates, it copies an array element to the iteration variable. For example, the first time the loop iterates, the iteration variable will contain
the value of element 0, the second time the loop iterates, the iteration variable will contain the
value of element 1, and so forth.
H ere is the general format of the foreach loop:
foreach(Type VariableName in ArrayName)
{
statement;
statement;
etc.
}
407
408
C h a p te r 7
A r r a y s a n d L is t s
The statements that appear inside the curly braces are the body of the loop. These are the
statements executed each time the loop iterates. As with other control structures, the curly
braces are optional if the body of the loop contains only one statement, as shown in the
following general format:
foreach(Type VariableName in ArrayName)
statement;
Let’s take a closer look at the items appearing inside the parentheses:
•
•
•
•
Type is the data type of the values in the array.
VariableName is the name of the iteration variable.
in is a keyword that must appear after the VariableName.
ArrayName is the name of an array.
Suppose we have the following array declaration:
int[] numbers = { 3, 6, 9 };
We can use the following foreach loop to display the contents of the numbers array:
foreach (int val in numbers)
{
MessageBox.Show(val.ToString());
}
Because the numbers array has three elements, this loop will iterate three times. The first
time it iterates, val will contain the value of numbers[0], so a message box will display
the value 3. During the second iteration, val will contain the value of numbers[1] , so a
message box will display the value 6. During the third iteration, val will contain the value
of numbers[2], so a message box will display the value 9.
T h e foreach L o o p v e r s u s t h e for L o o p
When you need to read the values that are stored in an array from the first element to the
last element, the foreach loop is simpler to use than the for loop. With the foreach
loop, you do not have to be concerned about the size of the array, and you do not have to
create a counter variable to hold subscripts; however, because the iteration variable is
read only, there are circumstances in which the foreach loop is not adequate. You cannot
use the foreach loop if you need to do any of the following:
•
•
•
•
Change the contents of an array element
Work through the array elements in reverse order
Access some, but not all, of the array elements
Simultaneously work with two or more arrays within the loop
In any of these circumstances, you should use the for loop to process the array.
R e a s s ig n in g a n A r r a y R e fe r e n c e V a r ia b le
It is possible to reassign an array reference variable to a different array, as demonstrated
by the following code sample:
1 // Create an array referenced by the numbers variable.
2 int[] numbers = new int[6];
3
4 // Reassign the numbers variable to a new array.
5 numbers = new int[3];
The statement in line 2 creates a six-element int array. A reference to the array is assigned
to the numbers variable. Figure 7-11 shows how the numbers variable references the sixelement array after this statement executes.
7 .2
F ig u r e 7 -1 1
A r r a y B a s ic s
T h e numbers v a r i a b l e r e f e r e n c i n g a s i x - e l e m e n t a r r a y
numbers
variable
Array that can hold six int values
Then, the statement in line 5 creates a new, three-element int array. A reference to
the new array is assigned to the numbers variable. When line 5 executes, the reference
that is currently stored in the numbers variable will be replaced by a reference to the
three-element array. After this statement executes, the numbers variable will reference the three-element array instead of the six-element array. This is illustrated in
Figure 7-12.
F ig u r e 7 -1 2
T h e numbers v a r i a b l e r e f e r e n c i n g a t h r e e - e l e m e n t a r r a y
numbers
variable
Array that can hold six int values
Array that can hold
three int values
N otice in Figure 7-12 that the six-element array still exists in memory, but it is no longer
referenced by any variables. Because it is no longer referenced, it cannot be accessed.
When an object is no longer referenced, it becomes eligible for garbage collection.
G a r b a g e c o l l e c t i o n is a process that periodically runs, removing all unreferenced objects
from memory.
C h e c k p o in t
7.5 Write a statement that declares a reference variable named monthlyPay for an
array that can hold decimal values.
7.6 Write a statement so that the monthlyPay variable from Checkpoint 7.5 references
a decimal array that can hold 12 values.
7.7 Combine the statements from Checkpoints 7.5 and 7.6 into a single statement, and
use a named constant for a size declarator.
7.8 Write a statement that creates an array of 3 string values referenced by a variable
named fullName. Provide an initialization list for the array using string values for
a first, middle, and last name.
7.9 Under what circumstances should you use a for loop rather than a foreach loop
to process data stored in an array?
7.10 What happens when an object such as an array is no longer referenced by
a variable?
409
410
C h a p te r 7
7 .3
A r r a y s a n d L is t s
W o r k in g w it h F ile s a n d A r r a y s
C O N C E P T :
F o r s o m e p r o b le m s , file s a n d a r r a y s c a n b e u s e d to g e th e r e ffe c tiv e ly . Y o u c a n
e a s ily w r ite a lo o p th a t s a v e s th e c o n te n ts o f a n a r r a y to a file , a n d v ic e v e r s a .
Some tasks may require you to save the contents of an array to a file so the data can be
used at a later time. Likewise, some situations may require you to read the data from a file
into an array. For example, suppose you have a file that contains a set of values and you
want to reverse the order of the values. One technique for doing this is to read the file’s
values into an array and then write the values in the array back to the file from the end of
the array to the beginning.
W r it in g a n A r r a y ’s C o n t e n t s t o a F ile
Writing the contents of an array to a file is a straightforward procedure: Open the file and
use a loop to step through each element of the array, writing its contents to the file. For
example, in the Chap07 folder of the Student Sample Programs, you will find a project
named Array To File. When you click the O K button, the application writes the contents of
an int array to a file. The following code shows the Click event handler for the O K button.
1 private void okButton_Click(object sender, EventArgs e)
2 {
3
try
4
{
5
// Create an array with some values.
6
int[] numbers = { 10, 20, 30, 40, 50 };
7
8
// Declare a StreamWriter variable.
9
StreamWriter outputFile;
10
11
// Create the file and get a StreamWriter object.
12
outputFile = File.CreateText("Values.txt");
13
14
// Write the array's contents to the file.
15
for (int index =0; index < numbers.Length; index++)
16
{
17
outputFile.WriteLine(numbers[index]);
18
}
19
20
// Close the file.
21
outputFile.Close();
22
23
// Let the user know it's done.
24
MessageBox.Show("Done");
25
}
26
catch (Exception ex)
27
{
28
// Display an error message.
29
MessageBox.Show(ex.Message);
30
}
31 }
The try-catch statement handles any file-related errors. H ere is a summary of the code
inside the try block:
• Line 6 creates an int array with five elements, initialized to the values 10, 20, 30,
40, and 50.
7 .3
W o r k in g w it h F ile s a n d A r r a y s
• Line 9 declares a StreamWriter variable named outputFile. (You do not see it in
this code sample, but the directive using System.IO; appears at the top of the file.
This is required for the StreamWriter declaration in line 9.)
• Line 12 creates a file named Values.txt for writing. After this statement executes, the
outputFile variable will reference a StreamWriter object that is associated with
the file.
• Line 15 is the beginning of a for loop. The loop iterates once for each element of the
array. During the loop’s iterations, the index variable will be assigned the values 1,
2, 3, 4 and 5.
• Inside the loop, line 17 writes the array element numbers[index] to the file.
• Line 21 closes the file.
• Line 24 displays a message box letting the user know the operation is done.
Figure 7-13 shows the contents of the Values.txt file, opened in N otepad, after the O K
button has been clicked.
F ig u r e 7 -1 3
C o n t e n t s o f t h e V a lu e s .t x t file
R e a d in g V a lu e s fr o m a F ile a n d
S t o r in g T h e m in a n A r r a y
Reading the contents of a file into an array is also straightforward: Open the file and
use a loop to read each item from the file, storing each item in an array element. The
loop should iterate until either the array is filled or the end of the file is reached. For
example, in the Chap07 folder of the Student Sample Programs, you will find a project
named File To Array. When you click the Get Values button, the application reads values from a file named Values.txt into an int array. The contents of the array are then
displayed in a list box. The following code shows the Click event handler for the Get
Values button.
1 private void getValuesButton_Click(object sender, EventArgs e)
2 {
3
try
4
{
5
// Create an array to hold items read from the file.
6
const int SIZE = 5;
7
int[] numbers = new int[SIZE];
8
9
// Counter variable to use in the loop
10
int index = 0;
411
412
C h a p te r 7
A r r a y s a n d L is t s
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 }
// Declare a StreamReader variable.
StreamReader inputFile;
// Open the file and get a StreamReader object.
inputFile = File.OpenText("Values.txt");
// Read the file's contents into the array.
while (index < numbers.Length && !inputFile.EndOfStream)
{
numbers[index] = int.Parse(inputFile.ReadLine());
index++;
}
// Close the file.
inputFile.Close();
// Display the array elements in the list box.
foreach (int value in numbers)
{
outputListBox.Items.Add(value);
}
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
}
The try-catch statement handles any file-related errors. H ere is a summary of the code
inside the try block:
• Lines 6 and 7 create an int array with five elements.
• Line 10 declares an int variable named index, initialized with the value 0. This
variable will be used in a loop to hold subscript values.
• Line 13 declares a StreamReader variable named inputFile. (You do not see it in
this code sample, but the directive using System.IO; appears at the top of the file.
This is required for the StreamReader declaration in line 13.)
• Line 16 opens a file named Values.txt for reading. After this statement executes,
the inputFile variable references a StreamReader object that is associated with
the file.
• Line 19 is the beginning of a while loop that reads items from the file and assigns
them to elements of the numbers array. N otice that the loop tests two Boolean
expressions connected by the && operator. The first expression is index < numbers.
Length. The purpose of this expression is to prevent the loop from writing beyond
the end of the array. When the array is full, the loop stops. The second expression is
!inputFile.EndOfStream. The purpose of this expression is to prevent the loop
from reading beyond the end of the file. When there are no more values to read from
the file, the loop stops.
• Inside the loop, line 21 reads a line of text from the file, converts it to an int, and
assigns the int to numbers[index]. Then, line 22 increments index.
• Line 26 closes the file.
• The foreach loop in lines 29–32 displays the array elements in the outputListBox
control.
Figure 7-14 shows the application’s form after the Get Values button has been clicked.
7 .4
F ig u r e 7 -1 4
7 .4
P a s s in g A r r a y s a s A r g u m e n t s t o M e t h o d s
T h e File To Arra y f o r m
P a s s in g A r r a y s a s A r g u m e n t s t o M e t h o d s
C O N C E P T :
An array can b e p assed as an argu men t to a meth o d . To p ass an array, yo u
p a s s th e v a r ia b le th a t r e fe r e n c e s th e a r r a y .
Sometimes you will want to write a method that accepts an entire array as an argument
and performs an operation on the array. For example, the following code shows a method
named ShowArray. The method accepts an array of strings as an argument and displays
each element in a message box.
1 private void ShowArray(string[] strArray)
2 {
3
foreach (string str in strArray)
4
{
5
MessageBox.Show(str);
6
}
7 }
N otice in line 1 that the method has a parameter variable named strArray and that the
parameter’s data type is string[]. The expression string[] indicates that this parameter variable is a reference to a string array. When you call this method, you must pass a
string array as an argument.
When you call a method and pass an array as an argument, you simply pass the variable
that references the array. The following code shows an example of how the ShowArray
method (previously shown) might be called:
1 // Create an array of strings.
2 string[] people = { "Bill", "Jill", "Phil", "Will" };
3
4 // Pass the array to the ShowArray method.
5 ShowArray(people);
Line 2 creates an array of strings named people and initializes it with four strings. Line 5
calls the ShowArray method passing the people array as an argument.
Keep in mind that arrays are always passed by reference. When you pass an array as an
argument, the thing that is passed into the parameter variable is a reference to the array.
This is illustrated in Figure 7-15. As shown in the figure, the people variable contains a
reference to an array. When the people variable is passed to the ShowArray method, the
reference to the array is passed into the strArray parameter variable. Figure 7-16 shows
that while the ShowArray method is executing, the people variable and the strArray
parameter variable reference the same array in memory.
413
414
C h a p te r 7
A r r a y s a n d L is t s
F ig u r e 7 -1 5
A n a rra y p a s s e d a s a n a rg u m e n t
"Bill"
"Jill"
"Phil"
"Will"
showArray(people);
Reference
private void showArray(string[] strArray)
{
foreach (string str in strArray)
{
MessageBox.Show(str);
}
}
F ig u r e 7 -1 6
T h e people a n d strArray v a r i a b l e s r e f e r e n c i n g t h e s a m e a r r a y
"Bill"
"Jill"
"Phil"
"Will"
ShowArray(people);
private void ShowArray(string[] strArray)
{
foreach (string str in strArray)
{
MessageBox.Show(str);
}
}
Because arrays are always passed by reference, a method that receives an array as an argument has access to the actual array (not a copy of the array). For example, in the Chap07
folder of the Student Sample Programs, you will find a project named Array Argument.
Figure 7-17 shows the application’s form just after the user has clicked the Go button.
F ig u r e 7 -1 7
T h e Arra y Argument a p p l i c a t i o n
outputListBox
goButton exitButton
7 .4
P a s s in g A r r a y s a s A r g u m e n t s t o M e t h o d s
The following code shows the Click event handler for the Go button, and a method
named SetToZero:
1 // Click event handler for the goButton control.
2 private void goButton_Click(object sender, EventArgs e)
3 {
4
// Create an int array.
5
int[] numbers = { 1, 2, 3 };
6
7
// Display the array in the list box.
8
outputListBox.Items.Add("The array's original contents:");
9
foreach (int number in numbers)
10
{
11
outputListBox.Items.Add(number);
12
}
13
14
// Pass the array to the SetToZero method.
15
SetToZero(numbers);
16
17
// Display the array in the list box again.
18
outputListBox.Items.Add("");
19
outputListBox.Items.Add("After calling SetToZero:");
20
foreach (int number in numbers)
21
{
22
outputListBox.Items.Add(number);
23
}
24 }
25
26 // The SetToZero method accepts an int array as an
27 // argument and sets its elememts to 0.
28 private void SetToZero(int[] iArray)
29 {
30
for (int index = 0; index < iArray.Length; index++)
31
{
32
iArray[index] = 0;
33
}
34 }
Let’s take a closer look at the goButton_Click event handler:
• Line 5 creates an int array named numbers, initialized with the values 1, 2, and 3.
• Line 8 displays the string "The array's original contents:" in the outputListBox
control.
• The foreach loop in lines 9–12 displays the contents of the numbers array in the
outputListBox control. Look at Figure 7-17 and notice that the arrays values are
1, 2, and 3.
• Line 15 calls the SetToZero method, passing the numbers array as an argument.
• Line 18 displays a blank line in the outputListBox control, and line 19 displays the
string "After calling SetToZero:".
• The foreach loop in lines 9–12 displays the contents of the numbers array in the
outputListBox control. Look at Figure 7-17 and notice that the array’s values are
now 0, 0, and 0.
As you can see from Figure 7-17, the SetToZero method changed the values stored in the
numbers array. Let’s look at the SetToZero method:
• N otice in line 28 that the method accepts an int array as an argument. The parameter variable’s name is iArray.
415
416
C h a p te r 7
A r r a y s a n d L is t s
• Line 30 is the beginning of a for loop that steps through the array. As the loop
iterates, the index variable is assigned the values 0, 1, 2, and so forth. The loop
iterates as long as index is less than iArray.Length.
• The statement in line 32 assigns 0 to the array element iArray[index].
Because the iArray parameter is a reference to the array that was passed as an argument,
the statement in line 32 assigns 0 to an element of the numbers array.
U s i n g ref a n d out w i t h A r r a y P a r a m e t e r s
You saw in the previous example that arrays are always passed by reference. When you
pass an array as an argument to a method, the method has direct access to the array
through its parameter variable. H owever, the method cannot access the original reference
variable that was used to pass the array. For example, in the Chap07 folder of the Student
Sample Programs, you will find a project named Change Array 1. Figure 7-18 shows the
application’s form just after the user has clicked the Go button. The following code shows
the Click event handler for the Go button and a method named ChangeArray:
F ig u r e 7 -1 8
T h e Change Array Demo 1 a p p l i c a t i o n
outputListBox
goButton
exitButton
1 private void goButton_Click(object sender, EventArgs e)
2 {
3
// Create an int array.
4
int[] numbers = { 1, 2, 3 };
5
6
// Display the numbers array's contents.
7
outputListBox.Items.Add("The array's original contents:");
8
foreach (int value in numbers)
9
{
10
outputListBox.Items.Add(value);
11
}
12
13
// Pass the numbers array to the ChangeArray method.
14
ChangeArray(numbers);
15
16
// Display the numbers array's contents.
17
outputListBox.Items.Add("After calling ChangeArray:");
18
foreach (int value in numbers)
19
{
20
outputListBox.Items.Add(value);
21
}
22 }
23
24 private void ChangeArray(int[] iArray)
7 .4
25 {
26
27
28
29
30
31
32
33
34
35
36 }
P a s s in g A r r a y s a s A r g u m e n t s t o M e t h o d s
const int NEW_SIZE = 5;
// Make iArray reference a different array.
iArray = new int[NEW_SIZE];
// Set the new array's elements to 99.
for (int index = 0; index < iArray.Length; index++)
{
iArray[index] = 99;
}
Let’s take a closer look at the goButton_Click event handler:
• Line 4 creates an int array named numbers, initialized with the values 1, 2, and 3.
• Lines 7–11 display the array’s contents in the outputListBox control. Look at
Figure 7-18 and notice that the array’s values are 1, 2, and 3.
• Line 14 calls the ChangeArray method, passing the numbers array as an argument.
• Lines 17–21 display the contents of the numbers array in the outputListBox control after the ChangeArray method has executed. Look at Figure 7-18 and notice
that the array’s values are still 1, 2, and 3. Apparently, the method did not change
the array.
Let’s look at the ChangeArray method:
• N otice in line 24 that the method accepts an int array as an argument. The parameter variable’s name is iArray. Keep in mind that when we call this method in line
14, passing numbers as an argument, the iArray parameter and the numbers variable reference the same array in memory.
• Line 26 declares an int constant named NEW_SIZE, set to the value 5.
• Line 29 creates a new int array in memory with five elements. A reference to the
array is assigned to the iArray parameter variable. As shown in Figure 7-19,
F ig u r e 7 -1 9
A ft e r lin e 2 9 e x e c u t e s
private void go tton_C ic (o
{
Create an int array
int[] n
ers = {
ect sender
EventArgs e)
Three-element int array
and so forth . . .
ChangeArray(n
ers)
and so forth . . .
private void ChangeArray(int[] iArray)
{
const int NEW_SIZE =
Five-element int array
a e iArray re erence a different array
iArray = ne int[NEW_SIZE]
Set the ne array s e e ents to
or (int inde =
inde
iArray
{
iArray[inde ] =
ength
inde
)
417
418
C h a p te r 7
A r r a y s a n d L is t s
this causes the iArray parameter variable to no longer reference the array that
was passed as an argument. Instead, the iArray parameter references the new
array.
• The for loop in lines 32–35 assigns the value 99 to each element of array referenced
by iArray. This does not affect the numbers array.
When you use either the ref or out keywords with an array parameter, the receiving
method not only has access to the array, but it also has access to the reference variable
that was used to pass the array. For example, the Change Array 2 project, in the Chap07
folder of the Student Sample Programs, is identical to the Change Array 1 project, except
that the iArray parameter is declared with the ref keyword in the ChangeArray
method. The following code shows the Click event handler for the Go button, and the
ChangeArray method.
1 private void goButton_Click(object sender, EventArgs e)
2 {
3
// Create an int array.
4
int[] numbers = { 1, 2, 3 };
5
6
// Display the number array's contents.
7
outputListBox.Items.Add("The array's original contents:");
8
foreach (int value in numbers)
9
{
10
outputListBox.Items.Add(value);
11
}
12
13
// Pass the number array to the ChangeArray method.
14
ChangeArray(ref numbers);
15
16
// Display the number array's contents.
17
outputListBox.Items.Add("After calling ChangeArray:");
18
foreach (int value in numbers)
19
{
20
outputListBox.Items.Add(value);
21
}
22 }
23
24 private void ChangeArray(ref int[] iArray)
25 {
26
const int NEW_SIZE = 5;
27
28
// Make iArray reference a different array.
29
iArray = new int[NEW_SIZE];
30
31
// Set the new array's elements to 99.
32
for (int index = 0; index < iArray.Length; index++)
33
{
34
iArray[index] = 99;
35
}
36 }
N otice that in line 24 the iArray parameter is declared with the ref keyword,
a n d i n l i n e 1 4 t h e ref k e y w o r d i s u s e d t o p a s s numbers a s a n a r g u m e n t t o t h e
ChangeArray m e t h o d . I n t h i s c o d e , t h e iArray p a r a m e t e r r e f e r s t o t h e numbers
v a r i a b l e . A n y t h i n g t h a t i s d o n e t o t h e iArray p a r a m e t e r i s a c t u a l l y d o n e t o t h e
numbers v a r i a b l e . F i g u r e 7 - 2 0 s h o w s h o w l i n e 2 9 c a u s e s t h e numbers v a r i a b l e t o
r e fe r e n c e th e n e w fiv e -e le m e n t a r r a y .
7 .4
F ig u r e 7 -2 0
P a s s in g A r r a y s a s A r g u m e n t s t o M e t h o d s
A f t e r l i n e 2 9 e x e c u t e s i n t h e Cha nge Arra y 2 a p p l i c a t i o n
private void go tton_C ic (o
{
Create an int array
int[] n
ers
{
ect sender
EventArgs e)
Three-element int array
X
and so forth . . .
ChangeArray(ref n
Five-element int array
ers)
and so forth . . .
private void ChangeArray(ref int[] iArray)
{
const int NEW_SIZE
a e iArray reference a different array
iArray
ne int[NEW_SIZE]
Set the ne array s e e ents to
for (int inde
inde
iArray
{
iArray[inde ]
ength
inde
)
Figure 7-21 shows the application’s form just after the user has clicked the Go button.
N otice from the program’s output that after the ChangeArray method has been called,
the numbers variable references a five-element array, and each element’s value is 99.
F ig u r e 7 -2 1
T h e Cha nge Arra y 1 a p p l i c a t i o n
C h e c k p o in t
7.11 When you pass an array as an argument, what is passed into the parameter variable?
7.12 Does a method that receives an array as an argument have access to the actual
array or only a copy of the array?
7.13 What is the result when you use either the ref or out keyword with an
array parameter?
419
420
C h a p te r 7
7 .5
A r r a y s a n d L is t s
S o m e U s e fu l A r r a y A lg o r it h m s
T h e S e q u e n t ia l S e a r c h
Programs commonly need to search for data that is stored in an array. Various techniques
known as s e a r c h a l g o r i t h m s have been developed to locate a specific item in a larger
collection of data, such as an array. In this section, we discuss the simplest of all search
algorithms—the sequential search. The s e q u e n t i a l s e a r c h a l g o r i t h m uses a loop to
sequentially step through an array, starting with the first element. It compares each
element with the value being searched for and stops when the value is found or the end of
the array is encountered. If the value being searched for is not in the array, the algorithm
unsuccessfully searches to the end of the array.
Let’s look at an example. In the Chap07 folder of the Student Sample Programs, you will
find a project named American Colonies. The application is a game that tests your
knowledge of U.S. history. As shown in Figure 7-22, the application’s form displays a list
of states in a ListBox control. Only one of the states shown in the ListBox was an original
American colony. You select the state that you believe was a colony and click the O K
button to see if you were correct.
F ig u r e 7 -2 2
T h e America n Colonies a p p l i c a t i o n
selectionListBox
okButton
exitButton
The following code is taken from the application. It shows a method named
SequentialSearch and the Click event handler for the O K button.
1 // The SequentialSearch method searches a string array
2 // for a specified value. If the value is found, its
3 // position is returned. Otherwise, −1 is returned.
4 private int SequentialSearch(string[] sArray, string value)
5 {
6
bool found = false; // Flag indicating search results
7
int index = 0;
// Used to step through the array
8
int position = −1;
// Position of value, if found
9
10
// Search the array.
11
while (!found && index < sArray.Length)
12
{
13
if (sArray[index] == value)
14
{
15
found = true;
16
position = index;
17
}
18
19
index++;
20
}
7 .5
S o m e U s e fu l A r r a y A lg o r it h m s
21
22
// Return
23
return position;
24 }
25
26 private void okButton_Click(object sender, EventArgs e)
27 {
28
string selection;
// To hold the user's selection
29
30
// Create an array with the colony names.
31
string[] colonies = { "Delaware", "Pennsylvania", "New Jersey",
32
"Georgia", "Connecticut", "Massachusetts",
33
"Maryland", "South Carolina", "New Hampshire",
34
"Virginia", "New York", "North Carolina",
35
"Rhode Island" };
36
37
if (selectionListBox.SelectedIndex != −1)
38
{
39
// Get the selected item.
40
selection = selectionListBox.SelectedItem.ToString();
41
42
// Determine if the item is in the array.
43
if (SequentialSearch(colonies, selection) != −1)
44
{
45
MessageBox.Show("Yes, that was one of the colonies.");
46
}
47
else
48
{
49
MessageBox.Show("No, that was not one of the colonies.");
50
}
51
}
52 }
The SequentialSearch method, which begins in line 4, searches a string array for a
specified value. It accepts a string array and a string search value as arguments. If
the search value is found in the array, the method returns the value’s subscript. If the
search value is not found in the array, the method returns −1. Let’s take a closer look at
the method:
• Line 6 declares a bool variable named found. The found variable is used as a flag.
Setting found to false indicates that the search value has not been found. Setting
found to true indicates that the search value has been found. N otice that found is
initialized with false.
• Line 7 declares an int variable named index that will be used to step through the
elements of the array. N otice that index is initialized with the value 0.
• Line 8 declares an int variable named position. If the search value is found in the
array, we save its subscript in the position variable. N otice that the position
variable is initialized with the value −1.
• The while loop that begins in line 11 searches the array for the specified value. It
iterates as long as found is not true and index is less than the array’s length.
• The if statement in line 13 determines whether sArray[index] is equal to value.
If this is true, then the search value has been found in the array. In that case, line 15
sets found to true, and line 16 assigns index to position.
• Line 19 increments index.
• When the loop finishes, line 23 returns the value of the position variable. If the
search value was found in the array, the position variable will contain the value’s
subscript. If the search value was not found in the array, the position variable will
still be set to −1.
421
422
C h a p te r 7
A r r a y s a n d L is t s
The Click event handler for the O K button begins in line 26. Let’s take a closer look at the
event handler’s code:
• Line 28 declares a string variable named selection. This variable will hold the
item that is selected from the ListBox control.
• Lines 31–35 declare a string array named colonies. The array is initialized with
the names of the U.S. colonies.
• The if statement that begins in line 37 determines whether an item has been selected
in the selectionListBox control. If an item has been selected, the following actions
take place:
• Line 40 gets the selected item and assigns it to the selection variable.
• The if statement in line 43 calls the SequentialSearch method, passing
t h e colonies a r r a y a n d t h e selection v a r i a b l e a s a r g u m e n t s . I f t h e v a l u e o f t h e
selection v a r i a b l e i s f o u n d i n t h e colonies a r r a y , t h e m e t h o d r e t u r n s a v a l u e
other than −1, and line 45 displays a message box informing the user that
the selected item was one of the colonies. H owever, if the value of the selection
variable is not found in the colonies array, the method will return −1, and line
49 displays a message box informing the user that the selected item was not one
of the colonies.
C o p y in g a n A r r a y
Because an array is an object, there is a distinction between an array and the variable that
references it. The array and the reference variable are two separate entities. This is important
to remember when you wish to copy the contents of one array to another. You might be
tempted to write something like the following code, thinking that you are copying an array:
int[] array1 = { 2, 4, 6, 8, 10 };
int[] array2 = array1; // This does not copy array1.
The first statement creates an array referenced by the array1 variable. The second statement assigns array1 to array2. This does not make a copy of the array referenced by
array1. Rather, it assigns the reference that is in array1 to array2. After this statement
executes, both the array1 and array2 variables will reference the same array. This type
of assignment operation is called a r e f e r e n c e c o p y . Only a reference to the array object is
copied, not the contents of the array object. This is illustrated in Figure 7-23.
F ig u r e 7 -2 3
B o t h array1 a n d array2 r e f e r e n c i n g t h e s a m e a r r a y
array1
variable
2
4
6
8
10
array2
variable
If you want to make a copy of an array, you must create the second array in memory and
then copy the individual elements of the first array to the second. This is usually best done
with a loop, such as the following:
1 const int SIZE = 5;
2 int[] firstArray = { 5, 10, 15, 20, 25 };
3 int[] secondArray = new int[SIZE];
4
7 .5
S o m e U s e fu l A r r a y A lg o r it h m s
5 for (int index = 0; index < firstArray.length; index++)
6 {
7
secondArray[index] = firstArray[index];
8 }
The loop in this code copies each element of firstArray to the corresponding element of
secondArray.
C o m p a r in g A r r a y s
You cannot use the == operator to compare two array reference variables and determine
whether the arrays are equal. For example, the following code appears to compare two
arrays, but in reality it does not:
1 int[] firstArray = { 5, 10, 15, 20, 25 };
2 int[] secondArray = { 5, 10, 15, 20, 25 };
3
4 if (firstArray == secondArray) // This is a mistake.
5 {
6
MessageBox.Show("The arrays are the same.");
7 }
8 else
9 {
10
MessageBox.Show("The arrays are not the same.");
11 }
When you use the == operator with reference variables, the operator compares the
references that the variables contain, not the contents of the objects referenced by the
variables. Because the firstArray and secondArray variables in this example reference
different objects in memory, the result of the Boolean expression firstArray ==
secondArray is false, and the code reports that the arrays are not the same.
To compare the contents of two arrays, you must compare the elements of the two arrays.
For example, look at the following code:
1 int[] firstArray = { 2, 4, 6, 8, 10 };
2 int[] secondArray = { 2, 4, 6, 8, 10 };
3 boolean arraysEqual = true; // Flag variable
4 int index = 0;
// To hold array subscripts
5
6 // First determine whether the arrays are the same size.
7 if (firstArray.length != secondArray.length)
8 {
9
arraysEqual = false;
10 }
11
12 // Next determine whether the elements contain the same data.
13 while (arraysEqual && index < firstArray.length)
14 {
15
if (firstArray[index] != secondArray[index])
16
{
17
arraysEqual = false;
18
}
19
index++;
20 }
21
22 if (arraysEqual)
23 {
24
MessageBox.Show("The arrays are equal.");
25 }
26 else
423
424
C h a p te r 7
A r r a y s a n d L is t s
27 {
28
29 }
MessageBox.Show("The arrays are not equal.");
This code determines whether firstArray and secondArray (declared in lines 1 and 2)
contain the same values. A Boolean flag variable, arraysEqual, is declared and initialized
to true in line 3. The arraysEqual variable used to signal whether the arrays are equal.
Another variable, index, is declared and initialized to 0 in line 4. The index variable is
used in a loop to step through the arrays.
First, the if statement in line 7 determines whether the two arrays are the same length. If
they are not the same length, then the arrays cannot be equal, so the flag variable
arraysEqual is set to false in line 9. Then a while loop begins in line 13. The loop
executes as long as arraysEqual is true and the index variable is less than firstArray.
length. During each iteration, it compares a different set of corresponding elements in
the arrays. When it finds two corresponding elements that have different values, the flag
variable arraysEqual is set to false.
After the loop finishes, an if statement examines the arraysEqual variable in line
22. If the variable is true, then the arrays are equal and a message indicating so is
displayed in line 24. Otherwise, they are not equal, so a different message is displayed
in line 28.
T o t a lin g t h e V a lu e s in a n A r r a y
To calculate the total of the values in a numeric array, you use a loop with an accumulator variable. First, the accumulator is initialized with 0. Then, the loop steps through the
array, adding the value of each array element to the accumulator.
1 // Create an int array.
2 int[] units = { 2, 4, 6, 8, 10 };
3
4 // Declare and initialize an accumulator variable.
5 int total = 0;
6
7 // Step through the array, adding each element to
8 // the accumulator.
9 for (int index = 0; index < units.Length; index++)
10 {
11
total += units[index];
12 }
13
14 // Display the total.
15 MessageBox.Show("The total is " + total);
A v e r a g in g t h e V a lu e s in a n A r r a y
The first step in calculating the average of all the values in a numeric array is to get the
total of the values. The second step is to divide the total by the number of elements in the
array. The following code shows an example:
1 // Create an array.
2 double[] scores = { 92.5, 81.6, 65.7, 72.8 }
3
4 // Declare and initialize an accumulator variable.
5 double total = 0.0;
6
7 // Declare a variable to hold the average.
7 .5
S o m e U s e fu l A r r a y A lg o r it h m s
8 double average;
9
10 // Step through the array, adding each element to
11 // the accumulator.
12 for (int index = 0; index < scores.Length; index++)
13 {
14
total += scores[index];
15 }
16
17 // Calculate the average.
18 average = total / scores.Length;
19
20 // Display the average.
21 MessageBox.Show("The average is " + average);
When this code finishes, the average variable will contain the average of the values in the
scores array. N otice that the last statement, which divides total by scores.length, is
not inside the loop. This statement should execute only once, after the loop has finished
its iterations.
F in d in g t h e H ig h e s t a n d L o w e s t V a lu e s in a n A r r a y
Some programming tasks require you to find the highest value in a set of data. Examples
include programs that report the highest sales amount for a given time period, the highest
test score in a set of test scores, the highest temperature for a given set of days, and
so forth.
The algorithm for finding the highest value in an array works like this: You create a variable to hold the highest value (the following example names this variable highest). Then,
you assign the value at element 0 to the highest variable. N ext, you use a loop to step
through the rest of the array elements, beginning at element 1. Each time the loop iterates,
it compares an array element to the highest variable. If the array element is greater than
the highest variable, then the value in the array element is assigned to the highest variable. When the loop finishes, the highest variable will contain the highest value in the
array. The flowchart in Figure 7-24 illustrates this logic.
The following code demonstrates this algorithm:
1 // Create an array.
2 int[] numbers = { 8, 1, 12, 6, 2 };
3
4 // Declare a variable to hold the highest value, and
5 // initialize it with the first value in the array.
6 int highest = numbers[0];
7
8 // Step through the rest of the array, beginning at
9 // element 1. When a value greater than highest is found,
10 // assign that value to highest.
11 for (int index = 1; index < numbers.Length; index++)
12 {
13
if (numbers[index] > highest)
14
{
15
highest = numbers[index];
16
}
17 }
18
19 // Display the highest value.
20 MessageBox.Show("The highest value is " + highest);
425
426
C h a p te r 7
A r r a y s a n d L is t s
F ig u r e 7 -2 4
F lo w c h a r t fo r fin d in g t h e h ig h e s t v a lu e in a n a r r a y
highest = array[0]
index = 1
True
index < array.Length
False
array[index] >
highest
True
highest = array[index]
False
index = index + 1
In some programs, you are more interested in finding the lowest value than the highest value in a set of data. For example, suppose you are writing a program that stores
several players’ golf scores in an array and you need to find the best score. In golf, the
lower the score the better, so you need an algorithm that finds the lowest value in
th e a r r a y .
T h e a lg o r ith m fo r fin d in g th e lo w e s t v a lu e in a n a r r a y is v e r y s im ila r to th e a lg o r ith m fo r
fin d in g th e h ig h e s t s c o r e . It w o r k s lik e th is : Y o u c r e a te a v a r ia b le to h o ld th e lo w e s t
v a l u e ( t h e f o l l o w i n g e x a m p l e n a m e s t h i s v a r i a b l e lowest) . T h e n , y o u a s s i g n t h e v a l u e a t
e l e m e n t 0 t o t h e lowest v a r i a b l e . N e x t , y o u u s e a l o o p t o s t e p t h r o u g h t h e r e s t o f t h e
a r r a y e le m e n ts , b e g in n in g a t e le m e n t 1 . E a c h tim e th e lo o p ite r a te s , it c o m p a r e s a n a r r a y
e l e m e n t t o t h e lowest v a r i a b l e . I f t h e a r r a y e l e m e n t i s l e s s t h a n t h e lowest v a r i a b l e ,
t h e n t h e v a l u e i n t h e a r r a y e l e m e n t i s a s s i g n e d t o t h e lowest v a r i a b l e . W h e n t h e l o o p
f i n i s h e s , t h e lowest v a r i a b l e c o n t a i n s t h e l o w e s t v a l u e i n t h e a r r a y . T h e f l o w c h a r t i n
F ig u r e 7 -2 5 illu s tr a te s th is lo g ic .
7 .5
F ig u r e 7 -2 5
S o m e U s e fu l A r r a y A lg o r it h m s
F lo w c h a r t fo r fin d in g t h e lo w e s t v a lu e in a n a r r a y
lowest = array[0]
index = 1
True
index <= SIZE - 1
False
array[index] <
lowest
True
lowest = array[index]
False
index = index + 1
The following code demonstrates this algorithm:
1 // Create an array.
2 int[] numbers = { 8, 1, 12, 6, 2 };
3
4 // Declare a variable to hold the lowest value, and
5 // initialize it with the first value in the array.
6 int lowest = numbers[0];
7
8 // Step through the rest of the array, beginning at
9 // element 1. When a value less than lowest is found,
10 // assign that value to lowest.
11 for (int index = 1; index < numbers.Length; index++)
12 {
13
if (numbers[index] < lowest)
14
{
15
lowest = numbers[index];
16
}
17 }
18
19 // Display the lowest value.
20 MessageBox.Show("The lowest value is " + lowest);
427
428
C h a p te r 7
A r r a y s a n d L is t s
P a r t ia lly F ille d A r r a y s
Sometimes you need to store a series of items in an array, but you do not know the
number of items in the series. As a result, you do not know the exact number of elements
needed for the array. One solution is to make the array large enough to hold the largest
possible number of items. This can lead to another problem, however. If the actual number
of items stored in the array is less than the number of elements, the array will be only
partially filled. When you process a partially filled array, you must process only the
elements that contain valid data items.
A partially filled array is normally used with an accompanying integer variable that
holds the number of items that are actually stored in the array. If the array is empty, then
0 is stored in this variable because there are no items in the array. Each time an item is
added to the array, the variable is incremented. When code steps through the array’s elements, the value of this variable is used instead of the array’s size to determine the
maximum subscript.
For example, in the Chap07 folder of the Student Sample Programs, you will find a project named Partially Filled Array. When you click the Go button, the application reads up
to 100 values from a file named Values.txt and stores them in a 100-element int array. If
the file contains fewer than 100 values, the application will partially fill the array. The
contents of the array are then displayed in a list box. Figure 7-26 shows the application’s
form just after the user has clicked the Go button. The following code shows the Click
event handler for the Get Values button.
F ig u r e 7 -2 6
T h e Partially Filled Array a p p l i c a t i o n
1 private void goButton_Click(object sender, EventArgs e)
2 {
3
try
4
{
5
// Create an array to hold items read from the file.
6
const int SIZE = 100;
7
int[] numbers = new int[SIZE];
8
9
// Variable to hold the number of items stored in
10
// the array
11
int count = 0;
12
13
// Declare a StreamReader variable.
14
StreamReader inputFile;
15
16
// Open the file and get a StreamReader object.
17
inputFile = File.OpenText("Values.txt");
18
19
// Read the file's contents into the array until the
7 .5
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 }
S o m e U s e fu l A r r a y A lg o r it h m s
// end of the file is reached, or the array is full.
while (!inputFile.EndOfStream && count < numbers.Length)
{
// Read the next item from the file.
numbers[count] = int.Parse(inputFile.ReadLine());
// Increment count.
count++;
}
// Close the file.
inputFile.Close();
// Display the array elements in the list box.
outputListBox.Items.Add("The file contains " + count +
" items:");
for (int index = 0; index < count; index++)
{
outputListBox.Items.Add(numbers[index]);
}
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
}
Let’s examine the code in detail:
• Line 3 is the beginning of a try-catch statement that handles any errors that might
result while reading data from the file.
• Line 6 declares a constant, SIZE, initialized with the value 100.
• Line 7 declares an int array named numbers using SIZE as the size declarator. As a
result, the values array has 100 elements.
• Line 11 declares an int variable named count, which holds the number of items
that are stored in the numbers array. N otice that count is initialized with 0 because
there are no values stored in the array.
• Line 14 declares a StreamReader variable named inputFile. (You do not see it in
this code sample, but the directive using System.IO; appears at the top of the file.
This is required for the StreamReader declaration in line 14.)
• Line 17 opens a file named Values.txt for reading. After this statement executes,
the inputFile variable references a StreamReader object that is associated with
the file.
• Line 21 is the beginning of a while loop that reads items from the file and assigns
them to elements of the numbers array. N otice that the loop tests two Boolean
expressions connected by the && operator. The first expression is !inputFile.
EndOfStream. The purpose of this expression is to prevent the loop from reading
beyond the end of the file. When there are no more values to read from the file, the
loop stops. The second expression is count < numbers.Length. The purpose of
this expression is to prevent the loop from writing beyond the end of the array.
When the array is full, the loop will stop.
• Inside the loop, line 24 reads a line of text from the file, converts it to an int, and
assigns the int to numbers[index].
• Then, line 27 increments the count variable. Each time a number is assigned to an
array element, the count variable is incremented. As a result, the count variable
holds the number of items that are stored in the array.
429
430
C h a p te r 7
A r r a y s a n d L is t s
• Line 31 closes the file.
• The for loop in lines 37–40 displays the array elements in the outputListBox control. Rather than stepping through all the elements in the array, however, the loop
steps through only the elements that contain values. N otice that the loop iterates as
long as index is less than count. Because count contains the number of items stored
in the array, the loop stops when the element containing the last valid value has
been displayed.
N ow that you’ve seen several algorithms for processing the contents of an array, you
should practice writing some of them yourself. Tutorial 7-2 takes you through the process
of writing an application that reads data from a file into an int array and then determines
the highest, lowest, and average values in the array.
T u t o r ia l 7 -2 :
P r o c e s s in g a n A r r a y
VideoNot e
T u to r ia l 7 -2 :
Processing
a n A r r a y
In this tutorial, you complete an application that reads five test scores from a file and
stores the test scores in an array. The application displays the test scores as well as the
highest score, the lowest score, and the average score. Figure 7-27 shows the application’s
form, which has already been created for you. A set of five test scores is stored in a file
named TestScores.txt, which has also been created for you.
F ig u r e 7 -2 7
T h e Test Average a p p l i c a t i o n ’ s f o r m
highScoreLabel
testScoresListBox
lowScoreLabel
averageScoreLabel
getScoresButton
exitButton
S t e p 1 :
S t a r t V i s u a l S t u d i o . O p e n t h e p r o j e c t n a m e d Test Average i n t h e Chap07 f o l d e r
o f th e S tu d e n t S a m p le P r o g r a m s .
S t e p 2 :
O p e n t h e F o r m 1 f o r m ’ s c o d e i n t h e c o d e e d i t o r . I n s e r t t h e using System.IO;
d ir e c tiv e s h o w n in lin e 1 0 o f P r o g r a m 7 -2 a t th e e n d o f th is tu to r ia l. T h is s ta te m e n t i s n e c e s s a r y b e c a u s e w e w i l l b e u s i n g t h e StreamReader c l a s s , a n d i t i s
p a r t o f t h e System.IO n a m e s p a c e i n t h e . N E T F r a m e w o r k .
S t e p 3 :
W i t h t h e c o d e e d i t o r s t i l l o p e n , t y p e t h e c o m m e n t s a n d c o d e f o r t h e Average
m e t h o d , s h o w n i n l i n e s 2 1 – 4 0 o f P r o g r a m 7 - 2 . T h e p u r p o s e o f t h e Average
m e t h o d i s t o a c c e p t a n int a r r a y a s a n a r g u m e n t a n d r e t u r n t h e a v e r a g e o f t h e
v a lu e s in th e a r r a y . T h is m e th o d u s e s a n a lg o r ith m s im ila r to th e a r r a y a v e r a g in g y o u s a w e a r lie r in th is c h a p te r .
S t e p 4 :
T y p e t h e c o m m e n t s a n d c o d e f o r t h e Highest m e t h o d , s h o w n i n l i n e s 4 2 – 6 3 o f
P r o g r a m 7 - 2 . T h e p u r p o s e o f t h e Highest m e t h o d i s t o a c c e p t a n int a r r a y a s
7 .5
S o m e U s e fu l A r r a y A lg o r it h m s
an argument and return the highest value in the array. This method uses an
algorithm similar to the algorithm that you saw earlier in this chapter for finding
the highest value in an array.
S t e p 5 :
Type the comments and code for the Lowest method, shown in lines 65–86 of
Program 7-2. The purpose of the Lowest method is to accept an int array as an
argument and return the lowest value in the array. This method uses an algorithm similar to the algorithm that you saw earlier in this chapter for finding the
lowest value in an array.
S t e p 6 :
N ow you create the Click event handlers for the Button controls. Switch back to
the D esigner and double-click the getScoresButton control. This opens the
code editor, and you will see an empty event handler named getScoresButton_
Click. Complete the getScoresButton_Click event handler by typing the
code shown in lines 90–134 in Program 7-2. Let’s review this code:
L i n e 9 0 : This is the beginning of a try-catch statement that handles any exceptions that are thrown while reading and processing data from the file. If an
exception occurs in the try block (lines 92–128), the program jumps to the catch
block, and line 133 displays an error message.
L i n e s 9 3 – 9 9 : The following declarations appear in these lines:
• SIZE—a constant, set to 5, for the number of test scores
• scores—an int array that holds the test scores
• index—an int variable, initialized to 0, that is used in a loop to step through
the elements of the scores array
• highestScore—an int that holds the highest score
• lowestScore—an int that holds the lowest score
• averageScore—a double that holds the average score
• inputFile—a variable that references the StreamReader object that is used
to read data from the file
L i n e 1 0 2 : After this statement executes, the TestScores.txt file will be opened
for reading, and the inputFile variable will reference a StreamReader object
that is associated with the file.
L i n e 1 0 5 : This is the beginning of a while loop that iterates as long as the end
of the TestScores.txt file has not been reached and as long as index is less than
scores.Length. (Recall that index starts with the value 0.)
L i n e 1 0 7 : This statement reads a line of text from the file and assigns it to the
array element scores[index].
L i n e 1 0 8 : This statement increments the index variable.
L i n e 1 1 2 : This statement closes the TestScores.txt file.
L i n e s 1 1 5 — 1 1 8 : This foreach loop displays the contents of the scores array
in the testScoresListBox control.
L i n e 1 2 1 : This statement calls the Highest method, passing the scores array as
an argument. The method returns the highest value in the array, which is
assigned to the highestScore variable.
L i n e 1 2 2 : This statement calls the Lowest method, passing the scores array as
an argument. The method returns the lowest value in the array, which is assigned
to the lowestScore variable.
L i n e 1 2 3 : This statement calls the Average method, passing the scores array as
an argument. The method returns the average of the values in the array, which
is assigned to the averageScore variable.
431
432
C h a p te r 7
A r r a y s a n d L is t s
L i n e s 1 2 6 – 1 2 8 : These statements display the highest score, lowest score, and
average score.
S t e p 7 :
Switch your view back to the D esigner and double-click the exitButton
control. In the code editor you will see an empty event handler named
exitButton_Click. Complete the exitButton_Click event handler by typing
the code shown in lines 139–140 in Program 7-2.
S t e p 8 :
Save the project. Then, press
on the keyboard or click the Start D ebugging
button ( ) on the toolbar to compile and run the application. When the
application runs, click the Get Scores button. This should display a set of test
scores in ListBox as well as the highest, lowest, and average of the test scores, as
shown in Figure 7-28. Click the Exit button to exit the application.
F ig u r e 7 -2 8
T h e Test Average a p p l i c a t i o n
P r o g r a m 7 -2
C o m p l e t e d c o d e f o r F o r m 1 i n t h e Test Avera ge a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10 using System.IO;
11
12 namespace Test_Average
13 {
14
public partial class Form1 : Form
15
{
16
public Form1()
17
{
18
InitializeComponent();
19
}
20
21
// The Average method accepts an int array argument
22
// and returns the Average of the values in the array.
23
private double Average(int[] iArray)
24
{
25
int total = 0;
// Accumulator, initialized to 0
26
double average; // To hold the average
7 .5
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
S o m e U s e fu l A r r a y A lg o r it h m s
// Step through the array, adding each element to
// the accumulator.
for (int index = 0; index < iArray.Length; index++)
{
total += iArray[index];
}
// Calculate the average.
average = (double) total / iArray.Length;
// Return the average.
return average;
}
// The Highest method accepts an int array argument
// and returns the highest value in that array.
private int Highest(int[] iArray)
{
// Declare a variable to hold the highest value, and
// initialize it with the first value in the array.
int highest = iArray[0];
// Step through the rest of the array, beginning at
// element 1. When a value greater than highest is found,
// assign that value to highest.
for (int index = 1; index < iArray.Length; index++)
{
if (iArray[index] > highest)
{
highest = iArray[index];
}
}
// Return the highest value.
return highest;
}
// The Lowest method accepts an int array argument
// and returns the lowest value in that array.
private int Lowest(int[] iArray)
{
// Declare a variable to hold the lowest value, and
// initialize it with the first value in the array.
int lowest = iArray[0];
// Step through the rest of the array, beginning at
// element 1. When a value less than lowest is found,
// assign that value to lowest.
for (int index = 1; index < iArray.Length; index++)
{
if (iArray[index] < lowest)
{
lowest = iArray[index];
}
}
// Return the lowest value.
return lowest;
433
434
C h a p te r 7
A r r a y s a n d L is t s
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
}
143 }
}
private void getScoresButton_Click(object sender, EventArgs e)
{
try
{
// Local variables
const int SIZE = 5;
// Number of tests
int[] scores = new int[SIZE]; // Array of test scores
int index = 0;
// Loop counter
int highestScore;
// To hold the highest score
int lowestScore;
// To hold the lowest score
double averageScore;
// To hold the average score
StreamReader inputFile;
// For file input
// Open the file and get a StreamReader object.
inputFile = File.OpenText("TestScores.txt");
// Read the test scores into the array.
while (!inputFile.EndOfStream && index < scores.Length)
{
scores[index] = int.Parse(inputFile.ReadLine());
index++;
}
// Close the file.
inputFile.Close();
// Display the test scores.
foreach (int value in scores)
{
testScoresListBox.Items.Add(value);
}
// Get the highest, lowest, and average scores.
highestScore = Highest(scores);
lowestScore = Lowest(scores);
averageScore = Average(scores);
// Display the values.
highScoreLabel.Text = highestScore.ToString();
lowScoreLabel.Text = lowestScore.ToString();
averageScoreLabel.Text = averageScore.ToString("n1");
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
7 .6
7 .6
A d v a n c e d A lg o r it h m s fo r S o r t in g a n d S e a r c h in g A r r a y s
A d v a n c e d A lg o r it h m s fo r S o r t in g
a n d S e a r c h in g A r r a y s
C O N C E P T :
A s o r tin g a lg o r ith m is u s e d to a r r a n g e d a ta in to s o m e o r d e r . A s e a r c h
a lg o r ith m is a m e th o d o f lo c a tin g a s p e c ific ite m in a la r g e r c o lle c tio n o f
d a ta . T h e s e le c tio n s o r t a n d th e b in a r y s e a r c h a r e p o p u la r s o r tin g a n d
s e a r c h in g a lg o r ith m s .
T h e S e le c t io n S o r t A lg o r it h m
Often the data in an array must be sorted in some order. Customer lists, for instance, are
commonly sorted in alphabetical order. Student grades might be sorted from highest to
lowest. Product codes could be sorted so all the products of the same color are stored
together. In this section, we explore how to write your own sorting algorithm. A sorting
algorithm is a technique for scanning through an array and rearranging its contents in
some specific order. The algorithm that we explore is called the selection sort.
The s e l e c t i o n s o r t works like this: The smallest value in the array is located and moved to
element 0. Then the next smallest value is located and moved to element 1. This process
continues until all the elements have been placed in their proper order. Let’s see how the
selection sort works when arranging the elements of the array in Figure 7-29.
F ig u r e 7 -2 9
V a lu e s in a n a r r a y
5
7
2
8
9
1
Element 0
Element 1
Element 2
Element 3
Element 4
Element 5
The selection sort scans the array, starting at element 0, and locates the element with the
smallest value. Then, the contents of this element are swapped with the contents of element 0. In this example, the 1 stored in element 5 is swapped with the 5 stored in element
0. After the swap, the array appears as shown in Figure 7-30.
F ig u r e 7 -3 0
V a lu e s in t h e a r r a y a ft e r t h e fir s t s w a p
These two elements were swapped.
1
7
2
8
9
5
Element 0
Element 1
Element 2
Element 3
Element 4
Element 5
Then, the algorithm repeats the process, but because element 0 already contains the smallest value in the array, it can be left out of the procedure. This time, the algorithm begins
the scan at element 1. In this example, the value in element 2 is swapped with the value in
element 1. Then, the array appears as shown in Figure 7-31.
435
436
C h a p te r 7
A r r a y s a n d L is t s
F ig u r e 7 -3 1
V a lu e s in t h e a r r a y a ft e r t h e s e c o n d s w a p
These two elements were swapped.
1
2
7
8
9
5
Element 0
Element 1
Element 2
Element 3
Element 4
Element 5
Once again, the process is repeated, but this time the scan begins at element 2. The
algorithm will find that element 5 contains the next smallest value. This element’s value is
swapped with that of element 2, causing the array to appear as shown in Figure 7-32.
F ig u r e 7 -3 2
V a lu e s in t h e a r r a y a ft e r t h e t h ir d s w a p
These two elements were swapped.
1
2
5
8
9
7
Element 0
Element 1
Element 2
Element 3
Element 4
Element 5
N ext, the scanning begins at element 3. Its value is swapped with that of element 5, causing the array to appear as shown in Figure 7-33.
F ig u r e 7 -3 3
V a lu e s in t h e a r r a y a ft e r t h e fo u r t h s w a p
These two elements were swapped.
1
2
5
7
9
8
Element 0
Element 1
Element 2
Element 3
Element 4
Element 5
At this point, there are only two elements left to sort. The algorithm finds that the value
in element 5 is smaller than that of element 4, so the two are swapped. This puts the array
in its final arrangement, as shown in Figure 7-34.
F ig u r e 7 -3 4
V a lu e s in t h e a r r a y a ft e r t h e fift h s w a p
These two elements were swapped.
1
2
5
7
8
9
Element 0
Element 1
Element 2
Element 3
Element 4
Element 5
7 .6
A d v a n c e d A lg o r it h m s fo r S o r t in g a n d S e a r c h in g A r r a y s
S w a p p in g A r r a y E le m e n t s
A s you saw i n t he descr i pt i on of t he sel ect i on sor t al gor i t hm, cer t ai n el ement s
ar e sw apped as t he al gor i thm st eps t hr ough t he ar r ay. L et ’ s br i ef l y di scuss t he
process of swapping two items in computer memory. Assume we have the following
variable declarations:
int a = 1;
int b = 9;
Suppose we want to swap the values in these variables so the variable a contains 9 and the
variable b contains 1. At first, you might think that we need only assign the variables to
each other, like this:
// ERROR! The following does NOT swap the variables.
a = b;
b = a;
To understand why this does not work, let’s step through the code. The first statement is
a = b. This causes the value 9 to be assigned to a. But, what happens to the value 1 that
was previously stored in a? Remember, when you assign a new value to a variable, the
new value replaces any value that was previously stored in the variable. So, the old value,
1, is thrown away. Then the next statement is b = a. Since the variable a contains 9, this
assigns 9 to b. After these statements execute, the variables a and b both contain the
value 9.
To successfully swap the contents of two variables, we need a third variable that can serve
as a temporary storage location:
int temp;
Then we can perform the following steps to swap the values in the variables a and b:
• Assign the value of a to temp.
• Assign the value of b to a.
• Assign the value of temp to b.
Figure 7-35 shows the contents of these variables as we perform each of these steps.
N otice that after the steps are finished, the values in a and b are swapped.
F ig u r e 7 -3 5
S w a p p in g t h e v a lu e s o f aa n d b
int a = 1;
int b = 9;
int temp;
1
2
temp = a;
a
1
a
1
b
9
b
9
temp
?
temp
1
a = b;
3
4
b = temp;
a
9
a
9
b
9
b
1
temp
1
temp
1
437
438
C h a p te r 7
A r r a y s a n d L is t s
H ere is the code for a Swap method that we can use to swap to int values:
1 private void Swap(ref int a, ref int b)
2 {
3
int temp = a;
4
a = b;
5
b = temp;
6 }
N O T E : It is critical that we use reference parameters in the Swap method because
the method must be able to change the values of the items that are passed to it
as arguments.
Let’s look at a complete program that demonstrates the Selection Sort algorithm. In the
Chap07 folder of the Student Sample Programs, you will find a project named Selection
Sort. Figure 7-36 shows the application’s form. On the left, you see the form in the
D esigner, with the names of various controls. On the right, you see the form at run time,
after the Go button has been clicked. When you click the Go button, the following actions
take place:
• An int array is created, initialized with unsorted values.
• The contents of the array are displayed in the originalListBox control.
• The array is passed as an argument to the SelectionSort method. The method
uses the Selection Sort algorithm to sort the array.
• The contents of the array are displayed in the sortedListBox control.
Program 7-3 shows the complete code for the Selection Sort application.
F ig u r e 7 -3 6
T h e Selection Sort a p p l i c a t i o n ’ s f o r m
sortedListBox
originalListBox
goButton
P r o g r a m 7 -3
exitButton
C o m p l e t e c o d e f o r Form1 i n t h e Selection Sort a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
7 .6
A d v a n c e d A lg o r it h m s fo r S o r t in g a n d S e a r c h in g A r r a y s
11 namespace Selection_Sort
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
// The SelectionSort method accepts an int array as an argument.
21
// It uses the Selection Sort algorithm to sort the array.
22
private void SelectionSort(int[] iArray)
23
{
24
int minIndex; // Subscript of smallest value in scanned area
25
int minValue; // Smallest value in the scanned area
26
27
// The outer loop steps through all the array elements,
28
// except the last one. The startScan variable marks the
29
// position where the scan should begin.
30
for (int startScan = 0; startScan < iArray.Length − 1; startScan++)
31
{
32
// Assume the first element in the scannable area
33
// is the smallest value.
34
minIndex = startScan;
35
minValue = iArray[startScan];
36
37
// Scan the array, starting at the 2nd element in the
38
// scannable area, looking for the smallest value.
39
for (int index = startScan + 1; index < iArray.Length; index++)
40
{
41
if (iArray[index] < minValue)
42
{
43
minValue = iArray[index];
44
minIndex = index;
45
}
46
}
47
48
// Swap the element with the smallest value with the
49
// first element in the scannable area.
50
Swap(ref iArray[minIndex], ref iArray[startScan]);
51
}
52
}
53
54
// The Swap method accepts two integer arguments, by reference,
55
// and swaps their contents.
56
private void Swap(ref int a, ref int b)
57
{
58
int temp = a;
59
a = b;
60
b = temp;
61
}
62
63
private void goButton_Click(object sender, EventArgs e)
64
{
65
// Create an array of integers.
66
int[] numbers = { 4, 6, 1, 3, 5, 2 };
67
// Display the array in original order.
68
69
foreach (int value in numbers)
70
{
71
originalListBox.Items.Add(value);
439
440
C h a p te r 7
A r r a y s a n d L is t s
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90 }
}
// Sort the array.
SelectionSort(numbers);
// Display the array in sorted order.
foreach (int value in numbers)
{
sortedListBox.Items.Add(value);
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
T h e B in a r y S e a r c h A lg o r it h m
Previously in this chapter, we discussed the sequential search algorithm, which uses a loop
to step sequentially through an array, starting with the first element. It compares each
element with the value being searched for and stops when the value is found or the end of
the array is encountered. If the value being searched for is not in the array, the algorithm
unsuccessfully searches to the end of the array.
The advantage of the sequential search is its simplicity: It is very easy to understand and
implement. Furthermore, it does not require the data in the array to be stored in any particular order. Its disadvantage, however, is its inefficiency. If the array being searched
contains 20,000 elements, the algorithm has to look at all 20,000 elements in order to
find a value stored in the last element.
In an average case, an item is just as likely to be found near the beginning of an array as
near the end. Typically, for an array of n items, the sequential search locates an item in
n/2 attempts. If an array has 50,000 elements, the sequential search makes a comparison
with 25,000 of them in a typical case. This is assuming, of course, that the search item is
consistently found in the array. (n/2 is the average number of comparisons. The maximum number of comparisons is always n.)
When the sequential search fails to locate an item, it must make a comparison with every
element in the array. As the number of failed search attempts increases, so does the average number of comparisons. Although the sequential search algorithm is adequate for
small arrays, it should not be used on large arrays if speed is important.
The b i n a r y s e a r c h is a clever algorithm that is much more efficient than the sequential
search. Its only requirement is that the values in the array must be sorted in ascending
order. Instead of testing the array’s first element, this algorithm starts with the element in
the middle. If that element happens to contain the desired value, then the search is over.
Otherwise, the value in the middle element is either greater than or less than the value
being searched for. If it is greater, then the desired value (if it is in the list) will be found
somewhere in the first half of the array. If it is less, then the desired value (again, if it is in
the list) will be found somewhere in the last half of the array. In either case, half of the
array’s elements have been eliminated from further searching.
If the desired value is not found in the middle element, the procedure is repeated for the
half of the array that potentially contains the value. For instance, if the last half of the
array is to be searched, the algorithm tests its middle element. If the desired value is not
7 .6
A d v a n c e d A lg o r it h m s fo r S o r t in g a n d S e a r c h in g A r r a y s
found there, the search is narrowed to the quarter of the array that resides before or after
that element. This process continues until the value being searched for is either found or
there are no more elements to test.
H ere is the pseudocode for a method that performs a binary search on an array:
M ethod BinarySearch(array, searchValue)
Set first to 0
Set last to the last subscript in the array
Set position to −1
Set found to false
While found is not true and first is less than or equal to last
Set middle to the subscript half way between array[first]and array[last]
I f array[middle] equals searchValue
Set found to true
Set position to middle
Else I f array[middle] is greater than searchValue
Set last to middle −1
Else
Set first to middle +1
End I f
End While
Return position
End M ethod
This algorithm uses three variables to mark positions within the array: first, last, and
middle. The first and last variables mark the boundaries of the portion of the array
currently being searched. They are initialized with the subscripts of the array’s first and
last elements. The subscript of the element halfway between first and last is calculated and
stored in the middle variable. If the element in the middle of the array does not contain
the search value, the first or last variable is adjusted so that only the top or bottom half of
the array is searched during the next iteration. This cuts the portion of the array being
searched in half each time the loop fails to locate the search value.
The following C# method performs a binary search on an integer array. The first parameter, iArray, is searched for an occurrence of the number stored in value. If the number
is found, its array subscript is returned. Otherwise, −1 is returned, indicating the value did
not appear in the array.
1 private int BinarySearch(int[] iArray, int value)
2 {
3
int first = 0;
// First array element
4
int last = iArray.Length − 1; // Last array element
5
int middle;
// Midpoint of search
6
int position = −1;
// Position of search value
7
bool found = false;
// Flag
8
9
// Search for the value.
10
while (!found && first <= last)
11
{
12
// Calculate the midpoint.
13
middle = (first + last) / 2;
14
15
// If value is found at midpoint . . .
16
if (iArray[middle] == value)
17
{
18
found = true;
19
position = middle;
441
442
C h a p te r 7
A r r a y s a n d L is t s
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 }
}
// else if value is in lower half . . .
else if (iArray[middle] > value)
{
last = middle − 1;
}
// else if value is in upper half . . .
else
{
first = middle + 1;
}
}
// Return the position of the item, or −1
// if it was not found.
return position;
If you want to see a complete application that uses the binary search algorithm, look at
the Binary Search project, located in the Chap07 folder of the Student Sample Programs.
It loads a list of names from a file into an array and then performs a binary search to find
a specific name in the array.
C h e c k p o in t
7.14 What is a search algorithm?
7.15 What is the purpose of a sorting algorithm?
7.16 What is the only requirement of the binary search algorithm?
7 .7
T w o -D im e n s io n a l A r r a y s
C O N C E P T :
A tw o -d im e n s io n a l a r r a y is lik e s e v e r a l id e n tic a l a r r a y s p u t to g e th e r . It is
u s e fu l fo r s to r in g m u ltip le s e ts o f d a ta .
The arrays that you have studied so far are known as one-dimensional arrays. They are
called o n e - d i m e n s i o n a l arrays because they can hold only one set of data. T w o - d i m e n s i o n a l
arrays, which are also called 2D arrays, can hold mu ltiple sets of data. Think of a twodimensional array as having rows and columns of elements, as shown in Figure 7-37. This
figure shows a two-dimensional array having three rows and four columns. N otice that
the rows are numbered 0, 1, and 2, and the columns are numbered 0, 1, 2, and 3. There is
a total of 12 elements in the array.
F ig u r e 7 -3 7
A t w o - d im e n s io n a l a r r a y
Column 0
Row 0
Row 1
Row 2
Column 1
Column 2
Column 3
7 .7
T w o - D im e n s io n a l A r r a y s
Two-dimensional arrays are useful for working with multiple sets of data. For example,
suppose you are designing a grade-averaging program for a teacher. The teacher has six
students, and each student takes five exams during the semester. One approach would be
to create six one-dimensional arrays, one for each student. Each of these arrays would
have five elements, one for each exam score. This approach would be cumbersome, however, because you would have to separately process each of the arrays. A better approach
would be to use a two-dimensional array with six rows (one for each student) and five
columns (one for each exam score), as shown in Figure 7-38.
F ig u r e 7 -3 8
T w o - d im e n s io n a l a r r a y w it h s ix r o w s a n d fiv e c o lu m n s
This row is for student 1.
Row 0
This row is for student 2.
Row 1
This row is for student 3.
Row 2
This row is for student 4.
Row 3
This row is for student 5.
Row 4
This row is for student 6.
Row 5
This column This column This column This column
contains
contains
contains
contains
scores for
scores for
scores for
scores for
exam 1.
exam 2.
exam 3.
exam 4.
This column
contains
scores for
exam 5.
Column 0
Column 4
Column 1
Column 2
Column 3
D e c la r in g a T w o -D im e n s io n a l A r r a y
To declare a two-dimensional array, two size declarators are required: The first one is for
the number of rows, and the second one is for the number of columns. H ere is an example
declaration of a two-dimensional array with three rows and four columns:
double[,] scores = new double[3, 4];
N oticethecomma that appearsinsidethefirst set of brackets. Thisindicatesthat the scores
variable references a two-dimensional array. The numbers 3 and 4 are size declarators. The
first size declarator specifies the number of rows, and the second size declarator specifies the
number of columns. N otice that the size declarators are separated by a comma.
As with one-dimensional arrays, it is best to use named constants as the size declarators.
H ere is an example:
const int ROWS = 3;
const int COLS = 4;
int[,] scores = new int[ROWS, COLS];
When processing the data in a two-dimensional array, each element has two subscripts:
one for its row and another for its column. In the scores array, the elements in row 0 are
referenced as follows:
scores[0,0]
scores[0,1]
scores[0,2]
scores[0,3]
443
444
C h a p te r 7
A r r a y s a n d L is t s
The elements in row 1 are referenced as follows:
scores[1,0]
scores[1,1]
scores[1,2]
scores[1,3]
And, the elements in row 2 are referenced as follows:
scores[2,0]
scores[2,1]
scores[2,2]
scores[2,3]
Figure 7-39 illustrates the array with the subscripts shown for each element.
F ig u r e 7 -3 9
S u b s c r i p t s f o r e a c h e l e m e n t o f t h e scores a r r a y
Column 0
Column 1
Column 2
Column 3
Row 0
scores[0,0]
scores[0,1]
scores[0,2]
scores[0,3]
Row 1
scores[1,0]
scores[1,1]
scores[1,2]
scores[1,3]
Row 2
scores[2,0]
scores[2,1]
scores[2,2]
scores[2,3]
A c c e s s in g t h e E le m e n t s in a T w o -D im e n s io n a l A r r a y
To access one of the elements in a two-dimensional array, you must use two subscripts.
For example, suppose we have the following declarations in a program:
const int ROWS = 5;
const int COLS = 10;
int[,] values = new int[ROWS, COLS];
The following statement assigns the number 95 to values[2,1]:
values[2,1] = 95;
Programs often use nested loops to process two-dimensional arrays. For example, the
following code assigns a random number to each element of the values array:
1 // Create a Random object.
2 Random rand = new Random();
3
4 // Create a two-dimensional int array.
5 const int ROWS = 5;
6 const int COLS = 10;
7 int[,] values = new int[ROWS, COLS];
8
9 // Fill the array with random numbers.
10 for (int row = 0; row < ROWS; row++)
11 {
12
for (int col = 0; col < COLS; col++)
13
{
14
values[row, col] = rand.Next(100);
15
}
16 }
7 .7
T w o - D im e n s io n a l A r r a y s
And the following set of nested loops displays all the elements of the values array in a
ListBox control named outputListBox:
1 // Display the array contents.
2 for (int row = 0; row < ROWS; row++)
3 {
4
for (int col = 0; col < COLS; col++)
5
{
6
outputListBox.Items.Add(values[row, col].ToString());
7
}
8 }
Im p lic it S iz in g a n d In it ia liz a t io n
o f T w o -D im e n s io n a l A r r a y s
As with a one-dimensional array, you may provide an initialization list for a twodimensional array. Recall that when you provide an initialization list for an array, you
cannot provide the upper subscript numbers. When initializing a two-dimensional array,
you must provide the comma to indicate the number of dimensions. The following is an
example of a two-dimensional array declaration with an initialization list:
int[,] values = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
Initialization values for each row are enclosed in their own set of braces. In this example,
the initialization values for row 0 are {1, 2, 3}, the initialization values for row 1 are
{4, 5, 6}, and the initialization values for row 2 are {7, 8, 9}. So, this statement
declares an array with three rows and three columns. The values are assigned to the
values array in the following manner:
values[0, 0] is set to 1.
values[0, 1] is set to 2.
values[0, 2] is set to 3.
values[1, 0] is set to 4.
values[1, 1] is set to 5.
values[1, 2] is set to 6.
values[2, 0] is set to 7.
values[2, 1] is set to 8.
values[2, 2] is set to 9.
Tutorial 7-3 gives you hands-on practice working with a two-dimensional array.
T u t o r ia l 7 -3 :
C o m p l e t i n g t h e Sea ting Cha rt A p p l i c a t i o n
VideoNot e
T u to r ia l 7 -3 :
Completing
the Seating
Chart
application
In this tutorial, you complete the Seating Chart application. The application’s form, which
is shown in Figure 7-40, uses a PictureBox control to display an airplane seating chart
that is arranged in rows and columns. When completed, the application allows the user to
enter valid row and column numbers in the rowTextBox and colTextBox text boxes and
then click the D isplay Price button. The price of the selected seat will be displayed in the
priceLabel control. The following table shows the seat prices:
445
446
C h a p te r 7
A r r a y s a n d L is t s
F ig u r e 7 -4 0
T h e Seating Chart a p p l i c a t i o n ’ s f o r m
rowTextBox
priceLabel
colTextBox
displayPriceButton
exitButton
C o lu m n s
0
1
2
3
Ro w 0
$450
$450
$450
$450
Ro w 1
$425
$425
$425
$425
Ro w 2
$400
$400
$400
$400
Ro w 3
$375
$375
$375
$375
Ro w 4
$375
$375
$375
$375
Ro w 5
$350
$350
$350
$350
When you write the code for the application, you will create a two-dimensional array to
hold these values.
S t e p 1 :
Start Visual Studio. Open the project named Seating Chart in the Chap07 folder
of this book’s Student Sample Programs.
S t e p 2 :
Open the Form1 form in the D esigner. Double-click the displayPriceButton
control. This opens the code editor, and you will see an empty event handler
named displayPriceButton_Click. Complete the event handler by typing the
code shown in lines 22–78 in Program 7-4. Let’s take a closer look at the code:
L i n e 2 3 : This statement declares two int variables, row and col, to hold the
row and column selected by the user.
L i n e s 2 6 – 2 7 : These statements declare int constants named MAX_ROW and MAX_
COL, set to the values 5 and 3, respectively. These are used as array size declarators.
7 .7
T w o - D im e n s io n a l A r r a y s
L i n e s 3 0 – 3 6 : This statement creates a two-dimensional decimal array named
prices, initialized with the seat prices previously shown.
L i n e 3 9 : This if statement converts the value entered into the rowTextBox
control to an int and stores the result in the row variable. If the conversion is
successful, the program continues. If the conversion fails, the program jumps to
the else clause in line 74, and then line 77 displays an error message.
L i n e 4 2 : This if statement converts the value entered into the colTextBox
control to an int and stores the result in the col variable. If the conversion is
successful, the program continues. If the conversion fails, the program jumps to
the else clause in line 68, and then line 71 displays an error message.
L i n e 4 5 : This if statement determines whether row is in the range of 0 through
MAX_ROW. If so, the program continues. Otherwise, the program jumps to the
else clause in line 61, and then lines 64–65 display an error message.
L i n e 4 8 : This if statement determines whether col is in the range of 0 through
MAX_COL. If so, the program continues. Otherwise, the program jumps to the
else clause in line 54, and then lines 57–58 display an error message.
L i n e s 5 1 – 5 2 : This statement uses row and col as subscripts to retrieve the
selected seat’s price from the prices array and then displays that value in the
priceLabel control.
S t e p 3 :
Switch your view back to the D esigner and double-click the exitButton
control. In the code editor you will see an empty event handler named
exitButton_Click. Complete the event handler by typing the code shown in
lines 83–84 in Program 7-4.
S t e p 4 :
Save the project. Then, press
on the keyboard or click the Start D ebugging
button ( ) on the toolbar to compile and run the application. When the application runs, experiment by entering row and column numbers for different seats
and comparing the displayed price with the table previously shown. When you
are finished, click the Exit button to end the application.
P r o g r a m 7 -4
C o m p l e t e d c o d e f o r F o r m 1 i n t h e Sea ting Cha rt a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10
11 namespace Seating_Chart
12 {
13
public partial class Form1 : Form
14
{
15
public Form1()
16
{
17
InitializeComponent();
18
}
19
20
private void displayPriceButton_Click(object sender, EventArgs e)
21
{
22
// Variables for the selected row and column
447
448
C h a p te r 7
A r r a y s a n d L is t s
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
int row, col;
// Constants for the maximum row and column subscripts
const int MAX_ROW = 5;
const int MAX_COL = 3;
// Create an array with the seat prices.
decimal[,] prices = { {450m, 450m, 450m, 450m},
{425m, 425m, 425m, 425m},
{400m, 400m, 400m, 400m},
{375m, 375m, 375m, 375m},
{375m, 375m, 375m, 375m},
{350m, 350m, 350m, 350m}
};
// Get the selected row number.
if (int.TryParse(rowTextBox.Text, out row))
{
// Get the selected column number.
if (int.TryParse(colTextBox.Text, out col))
{
// Make sure the row is within range.
if (row >= 0 && row <= MAX_ROW)
{
// Make sure the column is within range.
if (col >= 0 && col <= MAX_COL)
{
// Display the selected seat's price.
priceLabel.Text =
prices[row, col].ToString("c");
}
else
{
// Error message for invalid column.
MessageBox.Show("Column must be 0 through " +
MAX_COL);
}
}
else
{
// Error message for invalid row.
MessageBox.Show("Row must be 0 through " +
MAX_ROW);
}
}
else
{
// Display an error message for noninteger column.
MessageBox.Show("Enter an integer for the column.");
}
}
else
{
// Display an error message for noninteger row.
MessageBox.Show("Enter an integer for the row.");
}
}
private void exitButton_Click(object sender, EventArgs e)
7 .7
82
83
84
85
86
87 }
T w o - D im e n s io n a l A r r a y s
{
// Close the form.
this.Close();
}
}
S u m m in g A ll t h e E le m e n t s o f a T w o -D im e n s io n a l A r r a y
To sum all the elements of a two-dimensional array, you can use a pair of nested loops to
add the contents of each element to an accumulator. The following code shows an example:
1 const int ROWS = 3;
2 const int COLS = 3;
3 int[,] numbers = { {1, 2, 3, 4},
4
{5, 6, 7, 8},
5
{9, 10, 11, 12}
6
};
7
8 int total = 0; // Accumulator, set to 0
9
10 // Sum the array elements.
11 for (int row = 0; row < ROWS; row++)
12 {
13
for (int col = 0; col < COLS; col++)
14
{
15
total += numbers[row, col];
16
}
17 }
18 // Display the sum.
19 MessageBox.Show("The total is " + total);
S u m m in g t h e R o w s o f a T w o -D im e n s io n a l A r r a y
Sometimes you may need to calculate the sum of each row in a two-dimensional array.
For example, suppose a two-dimensional array is used to hold a set of test scores for a set
of students. Each row in the array is a set of test scores for one student. To get the sum of
a student’s test scores (perhaps so an average may be calculated), you use a loop to add all
the elements in one row. The following code shows an example:
1 const int ROWS = 3;
2 const int COLS = 3;
3 int[,] numbers = { {1, 2, 3, 4},
4
{5, 6, 7, 8},
5
{9, 10, 11, 12}
6
};
7
8 int total; // Accumulator
9
10 // Sum each row in the array.
11 for (int row = 0; row < ROWS; row++)
12 {
13
// Set the accumulator to 0.
14
total = 0;
15
16
// Total the row.
17
for (int col = 0; col < COLS; col++)
18
{
449
450
C h a p te r 7
A r r a y s a n d L is t s
19
20
21
22
23
24
25 }
total += numbers[row, col];
}
// Display the row's total.
MessageBox.Show("The total of row " + row +
" is " + total);
S u m m in g t h e C o lu m n s o f a T w o -D im e n s io n a l A r r a y
Sometimes you may need to calculate the sum of each column in a two-dimensional array.
For example, suppose a two-dimensional array is used to hold a set of test scores for a set
of students and you wish to calculate the class average for each of the test scores. To do
this, you calculate the average of each column in the array. This is accomplished with a set
of nested loops. The outer loop controls the column subscript, and the inner loop controls
the row subscript. The inner loop calculates the sum of a column, which is stored in an
accumulator. The following code demonstrates:
1 const int ROWS = 3;
2 const int COLS = 4;
3 int[,] numbers = { {1, 2, 3, 4},
4
{5, 6, 7, 8},
5
{9, 10, 11, 12}
6
};
7
8 int total;
// Accumulator
9
10 // Sum each column in the array.
11 for (int col = 0; col < COLS; col++)
12 {
13
// Set the accumulator to 0.
14
total = 0;
15
16
// Total the column.
17
for (int row = 0; row < ROWS; row++)
18
{
19
total += numbers[row, col];
20
}
21
22
// Display the column's total.
23
MessageBox.Show("The total of column " + col +
24
" is " + total);
25 }
C h e c k p o in t
7.17 H ow many rows and how many columns are in the following array?
int[,] values = new decimal[200, 100];
7.18 Write a statement that assigns the value 50 to the very last element in the values
array declared in Checkpoint 7.17.
7.19 Write a declaration for a two-dimensional int array initialized with the following
table of data:
12
24
32
21
42
99
8
68
32
92
95
34
21
11
7
7 .8
7 .8
Ja g g e d A r r a y s
Ja g g e d A r r a y s
C O N C E P T :
A ja g g e d a r r a y is s im ila r to a tw o -d im e n s io n a l a r r a y , b u t th e r o w s in a
ja g g e d a r r a y c a n h a v e d iffe r e n t le n g th s .
In a traditional two-dimensional array, each row has the same number of columns.
M entally, we visualize a two-dimensional array as a rectangular structure. Figure 7-37,
previously shown, is an example. For this reason, two-dimensional arrays are sometimes
referred to as r e c t a n g u l a r a r r a y s .
A j a g g e d a r r a y is similar to a two-dimensional array, but the rows in a jagged array
can have different numbers of columns. This is possible because a jagged array is actually an array of arrays. To be more specific, a jagged array is a one-dimensional array,
and each element of the array is also a one-dimensional array. Figure 7-41 shows an
example. In the figure, row 0 has four columns, row 1 has three columns, and row 2
has five columns.
F ig u r e 7 -4 1
A ja g g e d a r r a y
Row 0
1
2
3
Row 1
5
6
7
Row 2
8
9
10
4
11
12
Because a jagged array is an array of arrays, you set it up differently than a two-dimensional
array. First you create an array, and then you create each of the arrays that are the elem e n ts o f th e fir s t a r r a y . T h e fo llo w in g c o d e s h o w s a n e x a m p le o f h o w th e ja g g e d a r r a y in
F ig u r e 7 -4 1 m ig h t b e c r e a te d a n d in itia liz e d .
1
2
3
4
5
6
7
8
// Create an array of 3 int arrays.
int[][] jaggedArray = new int[3][];
// Create each array that is an element
// of the jagged array.
jaggedArray[0] = new int[4] { 1, 2, 3, 4 };
jaggedArray[1] = new int[3] { 5, 6, 7 };
jaggedArray[2] = new int[5] { 8, 9, 10, 11, 12 };
L e t’s ta k e a c lo s e r lo o k a t th e c o d e :
• L i n e 2 d e c l a r e s a n a r r a y n a m e d jaggedArray. N o t i c e t h a t t h e d a t a t y p e i s int[][],
w i t h t w o s e t s o f b r a c k e t s . T h i s i n d i c a t e s t h a t w e a r e d e c l a r i n g a n a r r a y o f int a r r a y s .
A l s o n o t i c e t h a t t h e e x p r e s s i o n new int[3][]u s e s o n l y o n e s i z e d e c l a r a t o r , s p e c i f y in g th e n u m b e r o f r o w s . T h e c o lu m n s iz e s m u s t b e s e t in d iv id u a lly .
• L i n e 6 c r e a t e s e l e m e n t 0 , w h i c h i s a n int a r r a y w i t h f o u r c o l u m n s . T h e c o l u m n s a r e
in itia liz e d w ith th e v a lu e s 1 , 2 , 3 , a n d 4 .
• L i n e 7 c r e a t e s e l e m e n t 1 , w h i c h i s a n int a r r a y w i t h t h r e e c o l u m n s . T h e c o l u m n s a r e
in itia liz e d w ith th e v a lu e s 5 , 6 , a n d 7 .
• L i n e 8 c r e a t e s e l e m e n t 2 , w h i c h i s a n int a r r a y w i t h f i v e c o l u m n s . T h e c o l u m n s a r e
in itia liz e d w ith th e v a lu e s 8 , 9 , 1 0 , 1 1 , a n d 1 2 .
T o a c c e s s a n ite m th a t is s to r e d a t a p a r tic u la r r o w a n d c o lu m n in a ja g g e d a r r a y , y o u
e n c lo s e th e r o w a n d c o lu m n s u b s c r ip ts in th e ir o w n s e ts o f b r a c k e ts . F o r e x a m p le , th e
451
452
C h a p te r 7
A r r a y s a n d L is t s
following statement displays the value stored at row 1, column 2, of the jaggedArray
that was previously declared:
MessageBox.Show(jaggedArray[1][2].ToString());
The following statement shows another example. It assigns the value 99 to row 0, column
3, of jaggedArray:
jaggedArray[0][3] = 99;
A jagged array has a Length property that holds the number of rows, and then each row
has its own Length property. You can use a row’s Length property to determine the number of columns in that row. For example, the following set of nested loops displays all the
values stored in the jaggedArray that was previously declared:
1 for (int row = 0; row < jaggedArray.Length; row++)
2 {
3
for (int col = 0; col < jaggedArray[row].Length; col++)
4
{
5
MessageBox.Show(jaggedArray[row][col].ToString());
6
}
7 }
C h e c k p o in t
7.20 Why are two-dimensional arrays sometimes referred to as rectangular arrays?
7.21 Write a statement that declares a jagged array of int values and initialize the
columns of each row with the values in the following table of data:
7 .9
2
4
6
3
5
7
9
5
9
11
17
21
T h e List C o l l e c t i o n
C O N C E P T :
List i s a c l a s s i n t h e . N E T F r a m e w o r k t h a t i s s i m i l a r t o a n a r r a y . U n l i k e
a n a r r a y , a List o b j e c t ’ s s i z e i s a u t o m a t i c a l l y a d j u s t e d t o a c c o m m o d a t e
th e n u m b e r o f ite m s b e in g s to r e d in it.
The .N ET Framework provides a class named List, which can be used for storing and
retrieving items. Once you create a List object, you can think of it as a container for
holding other objects. A List object is similar to an array but offers many advantages
over an array. H ere are a few:
• When you create a List object, you do not have to know the number of items that
you intend to store in it.
• A List object automatically expands as items are added to it.
• In addition to adding items to a List, you can remove items as well.
• A List object automatically shrinks as items are removed from it.
C r e a t i n g a List
H ere is an example of how you create a List object that can be used to hold strings:
List<string> nameList = new List<string>();
7 .9
T h e List C o l l e c t i o n
This statement creates a List object, referenced by the nameList variable. N otice that in
this example the word string is written inside angled brackets <> immediately after the
word List. This specifies that the List can hold objects of the string data type. If you
try to store any other type of object in this List, an error occurs.
H ere is an example of how you create a List object that can be used to hold integers:
List<int> numberList = new List<int>();
This statement creates a List object, referenced by the numberList variable. N otice that
in this example the word int is written inside angled brackets <> immediately after the
word List.
In it ia liz in g a
List
You can optionally initialize a List object when you declare it. H ere is an example:
List<int> numberList = new List<int>() { 1, 2, 3 };
This statement creates a List object that can hold integers and initializes it with the values
1, 2, and 3. H ere is an example that creates a List object to hold strings and initializes it
with three strings:
List<string> nameList = new List<string>() { "Chris",
"Kathryn", "Bill" };
A d d i n g I t e m s t o a List
To add items to an existing List object, you use the Add m e t h o d . For example, the
f ollowing statements create a List object and add a series of strings to it:
List<string> nameList = new List<string>();
nameList.Add("Chris");
nameList.Add("Kathryn");
nameList.Add("Bill");
After these statements execute, the nameList object will hold the three strings "Chris",
"Kathryn", and "Bill".
The items that are stored in a List have a corresponding index. The index specifies
the item’s location in the List, so it is much like an array subscript. The first item
that is added to a List is stored at index 0. The next item that is added to the List is
stored at index 1, and so forth. After the previously shown statements execute,
"Chris" is stored at index 0, "Kathryn" is stored at index 1, and "Bill" is stored at
index 2.
T h e C o u n t P r o p e r t y
A List object has a C o u n t p r o p e r t y that holds the number of items stored in the List.
For example, the following statement uses the Count property to display the number of
items stored in nameList:
MessageBox.Show("The List has " + nameList.Count +
" objects stored in it.");
Assuming that nameList holds the strings "Chris", "Kathryn", and "Bill", the following statement will be displayed in a message box:
The List has 3 objects stored in it.
453
454
C h a p te r 7
A r r a y s a n d L is t s
A c c e s s i n g I t e m s i n a List
You can use subscript notation to access the items in a List, just as you can with an
array. For example, the following for loop displays the items in the nameList object:
for (int index = 0; index < nameList.Count; index++)
{
MessageBox.Show(nameList[index]);
}
N otice that the loop uses the List object’s Count property in the test expression to control the number of iterations. H ere is an example that reads values from a text file and
adds them to a List:
1 // Open the Names.txt file.
2 StreamReader inputFile = File.OpenText("Names.txt");
3
4 // Create a List object to hold strings.
5 List<string> nameList = new List<string>();
6
7 // Read the file's contents.
8 while (!inputFile.EndOfStream)
9 {
10
// Read a line and add it to the List.
11
nameList.Add(inputFile.ReadLine());
12 }
Let’s take a closer look at this code:
• Line 2 opens a file named N ames.txt and associates it with a StreamReader object
that is referenced by the inputFile variable.
• Line 5 creates a List object, referenced by the nameList variable. The object can
hold strings.
• The while loop that starts in line 8 iterates until the end of the file is reached.
• The statement in line 11 reads a line from the file and adds it to the nameList
object.
After this code executes, the nameList object contains all the lines that were read from
the N ames.txt file.
You can also use the foreach loop to iterate over the items in a List, just as you can with
an array. H ere is an example:
foreach (string str in nameList)
{
MessageBox.Show(str);
}
P a s s i n g a List t o a M e t h o d
Sometimes you will want to write a method that accepts a List as an argument and performs an operation on the List. For example, the following code shows a method named
DisplayList. The method accepts a List of strings as an argument and displays each
item in List.
1 private void DisplayList(List<string> sList)
2 {
3
foreach (string str in sList)
4
{
5
MessageBox.Show(str);
6
}
7 }
7 .9
T h e List C o l l e c t i o n
N otice in line 1 that the method has a parameter variable named sList and that the
parameter’s data type is List<string>. The parameter variable is a reference to a
List<string> object. When you call this method, you must pass a List<string> object
as an argument.
When you call a method and pass a List<string> object as an argument, you simply
pass the variable that references the List. The following code shows an example of how
the DisplayList method (previously shown) might be called:
1 // Create a List of strings.
2 List<string> nameList = new List<string>() { "Chris",
3
"Kathryn", "Bill" };
4
5 // Pass the List to the DisplayList method.
6 DisplayList(nameList);
The statement in lines 2 and 3 creates a List containing the strings "Chris", "Kathryn",
and "Bill". Line 6 calls the DisplayList method, passing the nameList object as
an argument.
N O T E :
List objects, like arrays, are always passed by reference.
R e m o v in g It e m s fr o m a
List
You can use the RemoveAt m e t h o d to remove an item at a specific index in a List. The
following code shows an example:
1 // Create a List of strings.
2 List<string> nameList = new List<string>() { "Chris",
3
"Kathryn", "Bill" };
4
5 // Remove the item at index 0.
6 nameList.RemoveAt(0);
The statement in lines 2 and 3 creates a List containing the strings "Chris", "Kathryn",
and "Bill". Then, the statement in line 6 removes the string at index 0. After this statement executes, the List contains the strings "Kathryn" and "Bill".
If you know the value of the item that you want to remove from a List, but you do not
know the item’s index, you can use the Remove m e t h o d . You pass the item that you want
to remove as an argument, and the Remove method searches for that item in the List. If
the item is found, it is removed. H ere is an example:
1 // Create a List of strings.
2 List<string> nameList = new List<string>() { "Chris",
3
"Kathryn", "Bill" };
4
5 // Remove "Bill" from the List.
6 nameList.Remove("Bill");
The statement in lines 2 and 3 creates a List containing the strings "Chris", "Kathryn",
and "Bill". Then, the statement in line 6 removes "Bill" from the List. After this statement executes, the List contains the strings "Chris" and "Kathryn".
The Remove method returns a Boolean value indicating whether the item was actually
removed from the List. If the specified item was found in the List and removed, the
Remove method returns true. If the item was not found in the List, the Remove method
455
7 .9
T h e List C o l l e c t i o n
An easy way to search for item in a List, however, is to use the IndexOf method.
T h e IndexOf m e t h o d a c c e p t s a v a l u e a s a n a r g u m e n t , a n d i t s e a r c h e s f o r t h a t v a l u e i n t h e
List. I f t h e v a l u e i s f o u n d , t h e m e t h o d r e t u r n s i t s i n d e x . I f t h e v a l u e i s n o t f o u n d , t h e
method returns −1. The following code shows an example:
1 // Create a List of strings.
2 List<string> nameList = new List<string>() { "Chris",
3
"Kathryn", "Bill" };
4
5 // Search for "Kathryn".
6 int position = nameList.IndexOf("Kathryn");
7
8 // Was Kathryn found in the List?
9 if (position != −1)
10 {
11
MessageBox.Show("Kathryn was found at index " +
12
position);
13 }
14 else
15 {
16
MessageBox.Show("Kathryn was not found.");
17 }
The statement in lines 2 and 3 creates a List containing the strings "Chris", "Kathryn",
and "Bill". The statement in line 6 calls the IndexOf method to search for "Kathryn" in
the List. The value that is returned from the method is assigned to the position variable.
After this statement executes, the position variable contains the index of "Kathryn" or
−1 if "Kathryn" was not found in the List. The if statement in lines 9–17 displays one
of two possible messages, depending on whether "Kathryn" was found. (If this code were
executed, it would display the message “ Kathryn was found at index 1” .)
There are two additional versions of the IndexOf method that allow you to specify the
area of the List that should be searched. The following statement shows an example of
one of these:
position = nameList.IndexOf("Diane", 2);
N otice that two arguments are passed to the IndexOf method. The first argument,
"Diane", is the item to search for. The second argument, 2 is the starting index of the
search. This specifies that the search should begin at index 2 and end at the last item in the
List. (The beginning index is included in the search. If you pass an invalid index as an
argument, an exception occurs.)
H ere is an example of another version of the IndexOf method:
position = nameList.IndexOf("Diane", 2, 5);
In this example, three arguments are passed to the IndexOf method. The first argument,
"Diane", is the item to search for. The second argument, 2 is the starting index of the
search. The third argument, 5, is the ending index of the search. This specifies that the
search should begin at index 2, and end at index 5. (The beginning and ending indices
are included in the search. If either index is invalid, an exception occurs.)
N O T E : The IndexOf method performs a sequential search to locate the specified
item. If the List contains a large number of items, its performance will be slow.
In Tutorial 7-4, you will complete an application that reads the contents of a file into a
List, and then performs various operations on the List.
457
458
C h a p te r 7
A r r a y s a n d L is t s
T u t o r ia l 7 -4 :
C o m p l e t i n g t h e Test Score List A p p l i c a t i o n
VideoNot e
T u to r ia l 7 -4 :
Completing
the Test
Score L ist
Application
In this tutorial, you complete the Test Score L ist application. The application’s form,
which is shown in Figure 7-42, has already been created for you. When you complete the
application, it will read a set of test scores from a file into a List. (The file has also been
created for you.) The test scores are displayed in the ListBox control. The average test
score is calculated and displayed, as well as the number of above-average test scores and
below-average test scores.
F ig u r e 7 -4 2
T h e Test Score List a p p l i c a t i o n ’ s f o r m
averageLabel
aboveAverageLabel
testScoresListBox
belowAverageLabel
getScoresButton
exitButton
S t e p 1 :
Start Visual Studio. Open the project named Test Score L ist in the Chap07
folder of the Student Sample Programs.
S t e p 2 :
Open the Form1 form’s code in the code editor. Insert the using System.IO;
directive shown in line 10 of Program 7-5 at the end of this tutorial. This statement is necessary because we will be using the StreamReader class, and it is
part of the System.IO namespace in the .N ET Framework.
S t e p 3 :
With the code editor still open, type the comments and code for the ReadScores
method, shown in lines 21–44 of Program 7-5. The purpose of the ReadScores
method is to accept a List<int> object as an argument and read the contents
of the TestScores.txt file into the list.
S t e p 4 :
Type the comments and code for the DisplayScores method, shown in lines
46–54 of Program 7-5. The purpose of the DisplayScores method is to
a c c e p t a List<int> o b j e c t a s a n a r g u m e n t a n d d i s p l a y i t s c o n t e n t s i n t h e
testScoresListBox c o n t r o l .
S t e p 5 :
T y p e t h e c o m m e n t s a n d c o d e f o r t h e Average m e t h o d , s h o w n i n l i n e s 5 6 – 7 4 o f
P r o g r a m 7 - 5 . T h e p u r p o s e o f t h e Average m e t h o d i s t o a c c e p t a List<int>
o b j e c t a s a n a r g u m e n t a n d r e t u r n t h e a v e r a g e o f t h e v a l u e s i n t h e List.
S t e p 6 :
T y p e t h e c o m m e n t s a n d c o d e f o r t h e AboveAverage m e t h o d , s h o w n i n l i n e s
7 6 – 9 6 o f P r o g r a m 7 - 5 . T h e p u r p o s e o f t h e AboveAverage m e t h o d i s t o a c c e p t a
List<int> o b j e c t a s a n a r g u m e n t a n d r e t u r n t h e n u m b e r o f a b o v e a v e r a g e
s c o r e s it c o n ta in s .
S t e p 7 :
T y p e t h e c o m m e n t s a n d c o d e f o r t h e BelowAverage m e t h o d , s h o w n i n l i n e s
9 8 – 1 1 8 o f P r o g r a m 7 - 5 . T h e p u r p o s e o f t h e BelowAverage m e t h o d i s t o a c c e p t
a List<int> o b j e c t a s a n a r g u m e n t a n d r e t u r n t h e n u m b e r o f b e l o w a v e r a g e
s c o r e s it c o n ta in s .
7 .9
S t e p 8 :
T h e List C o l l e c t i o n
N ext, you create the Click event handlers for the Button controls. Switch
back t o t h e D esigner a n d d o u b l e - c l i c k t h e getScoresButton c o n t r o l . T h i s
o p e n s th e c o d e e d ito r , a n d y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
getScoresButton_Click . C o m p l e t e t h e getScoresButton_Click e v e n t
h a n d le r b y ty p in g th e c o d e s h o w n in lin e s 1 2 2 – 1 4 5 in P r o g r a m 7 -5 . L e t’s
r e v ie w th is c o d e :
L in e s 1 2 2 – 1 2 4 : T h e s e s ta te m e n ts d e c la r e th e fo llo w in g v a r ia b le s :
• averageScore— T h i s v a r i a b l e i s u s e d t o h o l d t h e a v e r a g e t e s t s c o r e .
• numAboveAverage— T h i s v a r i a b l e i s u s e d t o h o l d t h e n u m b e r o f a b o v e average test sco res.
• numBelowAverage— T h i s v a r i a b l e i s u s e d t o h o l d t h e n u m b e r o f b e l o w average test sco res.
L i n e 1 2 7 : T h i s s t a t e m e n t c r e a t e s a List<int> o b j e c t , r e f e r e n c e d
scoresList v a r i a b l e .
b y th e
L i n e 1 3 0 : T h i s s t a t e m e n t c a l l s t h e ReadScores m e t h o d , p a s s i n g t h e scoresList
o b j e c t a s a n a r g u m e n t . A f t e r t h i s s t a t e m e n t e x e c u t e s , t h e scoresList o b j e c t
c o n ta in s th e te s t s c o r e s th a t a r e in th e T e s tS c o r e s .tx t file .
L i n e 1 3 3 : T h i s s t a t e m e n t c a l l s t h e DisplayScores m e t h o d , p a s s i n g t h e
scoresList o b j e c t a s a n a r g u m e n t . A f t e r t h i s s t a t e m e n t e x e c u t e s , t h e i t e m s i n
t h e scoresList o b j e c t a r e d i s p l a y e d i n t h e testScoresListBox c o n t r o l .
L i n e 1 3 6 : T h i s s t a t e m e n t c a l l s t h e Average m e t h o d , p a s s i n g t h e scoresList
o b je c t a s a n a r g u m e n t. T h e m e th o d r e tu r n s th e a v e r a g e o f th e v a lu e s in th e
scoresList o b j e c t , w h i c h i s a s s i g n e d t o t h e averageScore v a r i a b l e .
L i n e 1 3 7 : T h i s s t a t e m e n t d i s p l a y s t h e a v e r a g e s c o r e i n t h e averageLabel
c o n tr o l.
L i n e 1 4 0 : T h i s s t a t e m e n t c a l l s t h e AboveAverage m e t h o d , p a s s i n g t h e
scoresList o b j e c t a s a n a r g u m e n t . T h e m e t h o d r e t u r n s t h e n u m b e r o f a b o v e a v e r a g e s c o r e s i n t h e scoresList o b j e c t , w h i c h i s a s s i g n e d t o t h e
numAboveAverage v a r i a b l e .
L in e 1 4 1 : T h is s ta te m e n t d is p la y s th e n u m b e r o f a b o v e -a v e r a g e s c o r e s in th e
aboveAverageLabel c o n t r o l .
L i n e 1 4 4 : T h i s s t a t e m e n t c a l l s t h e BelowAverage m e t h o d , p a s s i n g t h e
scoresList o b j e c t a s a n a r g u m e n t . T h e m e t h o d r e t u r n s t h e n u m b e r o f b e l o w a v e r a g e s c o r e s i n t h e scoresList o b j e c t , w h i c h i s a s s i g n e d t o t h e
numBelowAverage v a r i a b l e .
L in e 1 4 5 : T h is s ta te m e n t d is p la y s th e n u m b e r o f b e lo w -a v e r a g e s c o r e s in th e
belowAverageLabel c o n t r o l .
S t e p 9 :
S w i t c h y o u r v i e w b a c k t o t h e D esigner a n d d o u b l e - c l i c k t h e exitButton
c o n tr o l. In th e c o d e e d ito r y o u w ill s e e a n e m p ty e v e n t h a n d le r n a m e d
exitButton_Click. C o m p l e t e t h e e v e n t h a n d l e r b y t y p i n g t h e c o d e s h o w n i n
lin e s 1 5 0 – 1 5 1 in P r o g r a m 7 -5 .
S t e p 1 0 : S a v e th e p r o je c t. T h e n , p r e s s
o n t h e k e y b o a r d o r c l i c k t h e Start D ebugging
b u tto n ( ) o n th e to o lb a r to c o m p ile a n d r u n th e a p p lic a tio n . W h e n th e a p p lic a t i o n r u n s , c l i c k t h e Get Scores b u t t o n . T h i s s h o u l d d i s p l a y a s e t o f t e s t s c o r e s
in th e L is tB o x , a s w e ll a s th e a v e r a g e s c o r e , th e n u m b e r o f a b o v e -a v e r a g e s c o r e s ,
a n d th e n u m b e r o f b e lo w -a v e r a g e s c o r e s , a s s h o w n in F ig u r e 7 -4 3 . C lic k th e
Exit b u t t o n t o e x i t t h e a p p l i c a t i o n .
459
460
C h a p te r 7
A r r a y s a n d L is t s
F ig u r e 7 -4 3
T h e Test Score List a p p l i c a t i o n
P r o g r a m 7 -5
C o m p l e t e d c o d e f o r F o r m 1 i n t h e Test Scores List a p p l i c a t i o n
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Threading.Tasks;
9 using System.Windows.Forms;
10 using System.IO;
11
12 namespace Test_Score_List
13 {
14
public partial class Form1 : Form
15
{
16
public Form1()
17
{
18
InitializeComponent();
19
}
20
21
// The ReadScores method reads the scores from the
22
// TestScores.txt file into the scoresList parameter.
23
private void ReadScores(List<int> scoresList)
24
{
25
try
26
{
27
// Open the TestScores.txt file.
28
StreamReader inputFile = File.OpenText("TestScores.txt");
29
30
// Read the scores into the list.
31
while (!inputFile.EndOfStream)
32
{
33
scoresList.Add(int.Parse(inputFile.ReadLine()));
34
}
35
36
// Close the file.
37
inputFile.Close();
38
}
39
catch (Exception ex)
40
{
7 .9
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
T h e List C o l l e c t i o n
// Display an error message.
MessageBox.Show(ex.Message);
}
}
// The DisplayScores method displays the contents of the
// scoresList parameter in the ListBox control.
private void DisplayScores(List<int> scoresList)
{
foreach (int score in scoresList)
{
testScoresListBox.Items.Add(score);
}
}
// The Average method returns the average of the values
// in the scoresList parameter.
private double Average(List<int> scoresList)
{
int total = 0;
// Accumulator
double average;
// To hold the average
// Calculate the total of the scores.
foreach (int score in scoresList)
{
total += score;
}
// Calculate the average of the scores.
average = (double)total / scoresList.Count;
// Return the average.
return average;
}
// The AboveAverage method returns the number of
// above average scores in scoresList.
private int AboveAverage(List<int> scoresList)
{
int numAbove = 0;
// Accumulator
// Get the average score.
double avg = Average(scoresList);
// Count the number of above average scores.
foreach (int score in scoresList)
{
if (score > avg)
{
numAbove++;
}
}
// Return the number of above average scores.
return numAbove;
}
461
462
C h a p te r 7
A r r a y s a n d L is t s
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154 }
// The BelowAverage method returns the number of
// below average scores in scoresList.
private int BelowAverage(List<int> scoresList)
{
int numBelow = 0;
// Accumulator
// Get the average score.
double avg = Average(scoresList);
// Count the number of below average scores.
foreach (int score in scoresList)
{
if (score < avg)
{
numBelow++;
}
}
// Return the number of below average scores.
return numBelow;
}
private void getScoresButton_Click(object sender, EventArgs e)
{
double averageScore; // To hold the average score
int numAboveAverage;
// Number of above average scores
int numBelowAverage;
// Number of below average scores
// Create a List to hold the scores.
List<int> scoresList = new List<int>();
// Read the scores from the file into the List.
ReadScores(scoresList);
// Display the scores.
DisplayScores(scoresList);
// Display the average score.
averageScore = Average(scoresList);
averageLabel.Text = averageScore.ToString("n1");
// Display the number of above average scores.
numAboveAverage = AboveAverage(scoresList);
aboveAverageLabel.Text = numAboveAverage.ToString();
// Display the number of below average scores.
numBelowAverage = BelowAverage(scoresList);
belowAverageLabel.Text = numBelowAverage.ToString();
}
private void exitButton_Click(object sender, EventArgs e)
{
// Close the form.
this.Close();
}
}
7 .9
T h e List C o l l e c t i o n
C h e c k p o in t
7.22 Write a statement that initializes a List with 4 values of the double data type.
7.23 Write a statement that adds a new value to the List object created in Checkpoint 7.22.
7.24 Write a statement that clears the contents of the List object created in Checkpoint 7.22.
7.25 Is it possible to write code that performs a sequential search, binary search, selection
sort, and so forth, on a List? Why or why not?
463
464
C h a p te r 7
A r r a y s a n d L is t s
K e y T e r m s
Add method
array
binary search
Clear method
Count property
elements
foreach loop
garbage collection
IndexOf method
initialization list
Insert method
iteration variable
jagged array
Length property
List
new operator
off-by-one error
one-dimensional
rectangular arrays
reference
reference copy
reference types
reference var
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )