Tải bản đầy đủ (.pdf) (1,293 trang)

Computing with c sharp and the net framework 2003

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.29 MB, 1,293 trang )

ComputingwithC#and
the.NETFramework
ISBN:0763723398
byArt
Gittleman
JonesandBartlettPublishers
©2003(753pages)

Bothnoviceandexperienced
programmerswillfindthat
thistextservesasan
accessibleandthorough
guidetoobject-orientedand
event-drivenprogramming
conceptsthroughthe
author'sspiralteaching
approach.
CDContent
TableofContents
ComputingwithC#andthe.NET
Framework
Preface
AnIntroductionto
Chapter1 ComputingwithC#
Chapter2 - C#ProgrammingBasics
SoftwareEngineering
Chapter3 withControlStructures
MoreControlStructures
Chapter4 andTypes
GettingStartedwith
Chapter5 - Object-Oriented




Programming
Chapter6 - WorkingwithObjects
Chapter7 - Arrays
Event-Driven
Chapter8 Programming
Chapter9 - UserInterfaces
Chapter10 - Inheritance
ExceptionHandlingand
Chapter11 Input/Output
Chapter12 - DataStructures
Chapter13 - ThreadsandAnimation
Chapter14 - Networking
Chapter15 - UsingaDatabase
Chapter16 - ASP.NET
Chapter17 - XMLandWebServices
BinaryandHexadecimal
AppendixA Numbers
BitwiseandShift
AppendixB Operators
OperatorPrecedence
AppendixC Table
AppendixD - TheASCIICharacterSet
AppendixE - SimpleTypes
AnswerstoSelectedExercises
Index
ListofFigures
ListofCodeExamples
CDContent



BackCover
ComputingwithC#demystifiestheartof
programmingwithC#throughclearexplanationsand
intuitiveexamples.Bothnoviceandexperienced
programmerswillfindthatthistextservesasan
accessibleandthoroughguidetoobject-orientedand
event-drivenprogrammingconcepts.Readersdevelop
amasteryofobjectsthroughtheauthor’sspiral
teachingapproach:firststraightforwardexamplesare
presented,thensimpleclassdesign,andfinallythe
moredifficultaspectsofinheritanceand
polymorphism.Theauthorapplieshisspiralteaching
approachthroughoutthetext,andreadersacquirea
meaningfulunderstandingofprogrammingconcepts
andtechniques.Thistextsetsthestandardfortoday’s
C#programmingbooks;readersofalllevelswill
benefitfromtherichlearningexperiencethatthistext
provides.
DistinctiveFeatures:
200complete,fullyannotatedprogramsare
includedtoprovideconceptswithaconcrete
embodimentthatfacilitateslearning.
Inadditiontobasicprogrammingconcepts,this
textintroducesdatastructures,threads,
networking,databaseaccess,XML,Web
programming,andWebservices.
Readerscanpracticetheirskillsthroughthe
followingexercises:TestYourUnderstanding,Skill

Builder,CriticalThinking,Debugging,Program


Modification,ProgramDesign,andmore!


ComputingwithC#andthe.NETFramework
ArtGittleman
WorldHeadquarters
JonesandBartlett
Publishers
40TallPineDrive
Sudbury,MA01776
978-443-5000

www.jbpub.com

JonesandBartlett
PublishersCanada
2406NikannaRoad
Mississauga,
ONL5C2W6

JonesandBartlett
PublishersInternational
BarbHouse,Barb
Mews
LondonW67PA
UK


Copyright©2003byArtGittleman
Coverimage©RyanMcVay/GettyImages
Allrightsreserved.Nopartofthematerialprotectedbythiscopyright
maybereproducedorutilizedinanyform,electronicormechanical,
includingphotocopying,recording,orbyanyinformationstorageand
retrievalsystem,withoutwrittenpermissionfromthecopyrightowner.
LibraryofCongressCataloging-in-PublicationData
Gittleman,Art.
ComputingwithC#andthe.NETframework/ArthurGittleman.
p.cm.
ISBN0-7637-2339-8
1.C#(Computerprogramlanguage)2.Microsoft.NETFramework.I.
Title.
QA76.73.C154G582003
005.13'3-dc212002040703
Editor-in-Chief,College:J.MichaelStranz
ProductionManager:AmyRose
AssociateEditor:TheresaDiDonato
AssociateProductionEditor:KarenC.Ferreira


SeniorMarketingManager:NathanJ.Schultz
ProductionAssistant:JennyL.McIsaac
CoverDesign:KristinE.Ohlin
Composition:NortheastCompositors
Design:Anne'sBooks
PrintingandBinding:CourierWestford
CoverPrinting:JaguarAdvancedGraphics
ThisbookwastypesetinQuarkXpress4.1onaMacintoshG4.Thefont
familiesusedwereTimes,Frutiger,andImpress.Thefirstprintingwas

printedon45#HighlandPlus.
070605040310987654321
ToCharlottewithlove


Preface
C#andthe.NETFrameworksupportanew,integrated,powerfulInternet
programmingmodel.WenolongerneedtouseVisualBasicforrapid
applicationdevelopmentandforms,C++forobject-orientedapplications,
andASPfortheWeb.WecanuseC#forall,andwiththe.NET
Frameworkwehaveaplatformwithahugelibrarythatcanintegrate
applicationsacrosstheInternet.
ThistextteachesC#fromthebeginning,butincludesenoughmaterialfor
atwo-termcoursecoveringmoreadvancedtopics.Itteachesthe
conceptsofcomputingnecessaryforaCS-1course,butallowsthose
withpriorexperienceprogramminginanotherlanguagetoproceed
quicklyovertheearlierchapterstolearntheexcitingC#languageand
.NETFrameworkindepth.
CoretopicsincludeC#basics,controlstructures,types,object-oriented
programming,andarrays.Nextcomeevent-drivenprogramming,user
interfaces,andinheritance.Additionaltopicsincludeexceptionhandling,
files,datastructures,threads,animation,networking,databases,web
programmingwithASP.NET,andXMLandwebservices.Thelater
chapterscan,forthemostpart,bestudiedindependently,soan
instructorhasflexibilityinthechoiceoftopicsforamoreadvanced
course.
Ibelieveonelearnsbestfromexample,and,therefore,eachchapterhas
manycompleteprograms.Asprogrammerswelearntoaddcommentsto
ourcode,butforpedagogicalpurposeswherecommentswouldbeso
detailedastoclutterthecode,Iprefertousenotes.Eachnotecontainsa

longerexplanationofakeylineofcode,andappearsjustafterthecode,
allowingeasierreadingofthecodeitself.Byusingnotesinthisway,I
alsoavoidclutteringthetextwithdetailedcodeexplanationsandcan
focusonexplainingconcepts.
Onealsolearnsbydoing.TofacilitatelearningIincludemanyvaried
exercises.TestYourUnderstandingExercisesattheendofeachsection
givereadersachancetoassimilatethematerialimmediately.Answersto
theodd-numberedexercisesappearattheendofthetext,andanswers


totheeven-numberedexercisesareavailablewithcodeforallprogram
examplesonaStudentResourceCDincludedwiththetext.ThisCDalso
includesthe.NETframeworkSDK.
IincludeSkillBuilderandCriticalThinkingexercisesattheendofmost
chapterstoallowreaderstomasternewconcepts.Answerstothese
appearattheendofthebook.Adebuggingexerciseattheendofmost
chaptershelpsdevelopthisnecessaryskill.
ProgramModificationexercisesallowreaderstotacklethiscommontask.
ProgramDesignexercisesprovidepracticeincludingtheentire
developmentprocess.
Onecandebateendlesslythebestwaytointroduceobjects.Iliketo
presentobjectsearly,butusingaspiralapproachsostudentsbuilda
soundfoundationbeforedelvingintothedetails.ThusIstartwithan
intuitiveexampleinChapter5andcontinuetoshow,usingUML,howto
designaclassandcodeitinC#.IdefersomeconceptstoChapter6,and
themoredifficultinheritanceconceptstoChapter9.
Ithankreviewers
GeraldBaumgartner,TheOhioStateUniversity
DavidBinkley,LoyolaCollege
CorinneHoisington,CentralVirginiaCommunityCollege

KenrickMock,UniversityofAlaskaAnchorage
fortheirmanyperceptivecommentsandsuggestionsthatdidmuchto
improvethemanuscript.Ithasbeeagreatpleasureworkingwiththevery
helpfulandamiableCSteamatJonesandBartlett,includingMichael
Stranz,TheresaDiDonato,AmyRose,JennyMcIsaac,andKaren
Ferreira.
Thewebsiteforthisbookis
/>

IwillposterrataassoonasIbecomeawareofthem.Pleaseemailany
correctionstomeat



Chapter1:AnIntroductiontoComputingwith
C#
DownloadCDContent


Overview
Onceuponatime,giantdigitalcomputersfilledlargeroomswiththeir
thousandsofvacuumtubes.Theywereslowbeasts,butlooked
awesome.Intheyearssinceelectronicdigitalcomputerswerefirst
developedinthe1940s,computershavedramaticallydecreasedinsize
andincreasedincomputingpower.Startingasatoolforscienceand
engineering,computershavebecomeanessentialpartofoursociety.
Studyingcomputingchallengesustokeepupwithrapidtechnological
change.WithC#(pronouncedCsharp)wecanlearnthebasic
techniquesofprogrammingthathavebroughtustothispoint,andgo
forwardwithobject-oriented,interactive,graphical,event-driven

programming,networking,andwebservicesthattakeustothefuture.

Objectives
Introducebasiccomputingconcepts
SurveyC#history,itsfeatures,andhowitworks
IntroducetheelementsofaC#program
Introducetheprogramdevelopmentprocess


1.1IntroductiontoComputing
Hardware
Acomputerhasseveralbasiccomponents(seeFigure1.1).The
processorexecutesprogramsstoredinmemory,usingthememoryto
storedataneededincomputations.Externalstorage,includingdisk
drives,holdsprogramsanddata.Inputdevicessuchasakeyboardanda
mouseallowuserinteraction.Outputdevicesdisplayresults.Changing
technologyimprovestheperformanceofthesecomponentsandprovides
newtypes,butcurrentcommercialcomputershavethisorganization.


Figure1.1:Acomputersystem

Software
Softwareconsistsoftheprogramsthecomputerexecutes.Theoperating
systemsoftwaremakesitmucheasierforustousethecomputer.It
providesaninterfacetothehardwareforus,sothateachofusdoesnot
havetowriteprogramstoreadinputfromthekeyboard,writeoutputto
thescreen,orcreatefilesontheharddisk.Anoperatingsystemcanbe
relativelysimple,providingfewservices,oritcanbeahugeprogramwith
manybellsandwhistlesforustouse.

Programmersappreciateutilityprogramssuchaseditorsthatallowusto
createormodifyprogramsandcompilersthattranslateprogramsfrom
onelanguagetoanothertofacilitatetheirexecution.Endusersrunword
processors,spreadsheets,games,browsers,andmanyother
applications.Businessesrelyoncomputersoftwaretoservecustomers
andforthebusinesses'accounting,payroll,andothermanagement
needs.


Theprocessorexecutessoftwareusingitsspeciallydesignedinstruction
set.Eachinstructionissimplesothatitmaytakehundreds,thousands,
ormillionsofinstructionstoimplementthetaskswewantoursoftwareto
perform.Eachinstructionhasseveralparts.Thesepartsspecifythe
operation(addition,forexample)thattheinstructionperforms,andany
operandsthatituses,suchasthenumberstoadd.Eachmemory
locationhasanumericaladdress.High-levellanguagessuchasC#
provideinstructionstoperformtheequivalentofmanylow-levelmachine
instructions.

High-LevelLanguages
Eachprocessorhasitsowninstructionsetthatusesnumericalcodesfor
theoperatorsandnumericaladdressesfortheoperations.Each
instructionperformsonebasicstepsuchasanaddition,aload,ora
store.Programmingusingaprocessor'sinstructionsetwouldmakeit
difficulttoaccomplishanybutthesimplesttasks.Moreover,wewould
havetowritesuchaprogramalloveragainfortheinstructionsetofa
differentprocessor.AprogramusingprocessorABC'sinstructionsetwill
notrunonprocessorXYZ,andviceversa.
Ahigh-levellanguageallowsustoexpressthecomputationinamore
understandableform,combiningseveralstepsintooneexpression,and

towriteaprogramthatwecanimplementonmanytypesofprocessors.
Forexample,wecanexpressanadditionas
totalSalary=baseSalary+bonus;


Figure1.2:Translatingahigh-levelprogram
andwritemorecomplicatedstatementssuchas
totalScore=
(judge1Score+judge2Score+judge3Score)*difficulty;
whichrepresentsthetotalscoreobtainedbyfirstaddingthescoresof


threejudges,andthenmultiplyingthatsumbyadifficultyfactor.Weuse
theasterisk,*,todenotemultiplication.

Compilers
Acompilertranslatesaprogramfromonelanguagetoanother.Ifwewant
towriteaprograminahigh-levellanguageandrunitonprocessorABC,
wecanuseacompilertotranslateourhigh-levelprogramtoan
equivalentprogramusingtheinstructionsetofprocessorABC.Each
high-levelstatementwillusuallytranslatetoseveralprocessorABC
instructions.Figure1.2showsthisprocess.
TorunthesameprogramonprocessorXYZwewouldneedanother
compilerthattranslatesfromthehigh-levellanguagetotheinstructionset
ofprocessorXYZ.Thehigh-levelprogramiscalledthesourcecode,and
thetranslatedprogramiscalledtheexecutablecodeorthebinarycode
(reflectingitsuseofthebinarynumbersystemtorepresentoperatorsand
operands.)ImplementationsoftheCandC++languagesusuallyuse
compilerstoproduceexecutablecodeforspecificprocessors.
Compilersareindispensabletoolsforprogramdevelopers,butendusers

havenodesiretousethem.Aplayerofagamewantsaprogramthatwill
run—anexecutableprogram.Thevendorofthatgamemustprovide
executableversionsofthegameforeachprocessor.

Interpreters
Aninterpreterisaprogramthatexecutesthecoderatherthantranslating
ittoanotherlanguage.Forexample,aninterpreterwouldexecutethe
statement
totalSalary=baseSalary+bonus;
byfindingthevaluesofbaseSalaryandbonus,addingthem,and
storingtheresultintotalSalary.Inthisexample,theinterpreter
executesahigh-levellanguagestatement.TheBASIClanguage,usedon
earlypersonalcomputersthathadinsufficientmemorytosupportthe
compilationprocess,wastypicallyimplementedbyaninterpreter.


Wecouldalsouseaninterpretertoallowonemachinetosimulatethe
instructionsofanother,asshowninFigure1.3.Forexample,wecould
writeaprogramthatexecutes,onprocessorXYZ,programswrittenusing
processorABC'sinstructionset.ManyJavaimplementationsusea
combinationofcompilationandinterpretation,asdidthefirst
implementationsofthePascallanguage.


Figure1.3:Aninterpreterexecutingeachhigh-level
statement

Networks
Thusfarwehavefocusedonthesoftwareandhardwareforasingle
computer.WiththeadventoftheInternet,computerseasilycommunicate

withothercomputersinthesameoffice,thesamecompany,oratremote
sitesallovertheworld.Manyofususeemailmorethanweuseregular
mailorthetelephone.Acomputermaybeconnectedbycabletoother
computersinanetwork,oruseamodemtoconnectovertelephonelines.
TheInternetisavastnetworkofnetworksoverwhichweusefamiliar
servicessuchasemailandfiletransfer.TheWorldWideWeb,arapidly
growingpartoftheInternet,useshypertexttocreateaweboflinksfrom
onecomputertoanother.Hypertext,whichwediscusslaterinthetext,
allowsustoincludeimages,sounds,formattedtext,andlinkstoother
computersinwebpageswhichwedisplayusingabrowser.Manyuse
browsersoftwareastheirprimaryaccesstocomputers.Webservices
allowcomputerstocommunicatewithoneanother.
TheBIGPicture
Operatingsystemsoftwarehandlesthedetailsofinput,output,andfiles.
Eachhardwareprocessorusesitsownlow-levelinstructionset.Higher-


levellanguagesallowprogrammerstowritestatementsthataremore
meaningful.Acompilertranslatesaprograminahigh-levellanguageto
theinstructionsetforaspecificprocessor.Aninterpreterexecutesthe
high-levelcodedirectly.

TestYourUnderstanding
1. Describeeachcomponentofthecomputerthatyouwillbeusing
toprograminC#.Whatisthefunctionofeach?
2. Listseveralsoftwareapplicationsyouhaveusedorwouldliketo
use.Identifyeachasanoperatingsystem,wordprocessor,
game,etc.
3. Whatdowecallthetypeofprogramthattranslatesaprogram
inahigh-levellanguagetoanequivalentprograminanother

language?
4. Whatdowecallthetypeofprogramthatexecutesanother
program?
Answers
3. Acompiler.


1.2The.NETFramework
MicrosoftdevelopedtheC#languagealongwiththe.NETFramework,a
newcomputingplatformthatsimplifiesapplicationdevelopmentinthe
distributionenvironmentoftheInternet.Theydesignedthe.NET
Frameworktofulfillthefollowingobjectives[1]:
Toprovideaconsistentobject-orientedprogrammingenvironment
whetherobjectcodeisstoredandexecutedlocally,executed
locallybutInternet-distributed,orexecutedremotely.
Toprovideacode-executionenvironmentthatminimizessoftware
deploymentandversioningconflicts
Toprovideacode-executionenvironmentthatguaranteessafe
executionofcode,includingcodecreatedbyanunknownor
semitrustedthirdparty
Toprovideacode-executionenvironmentthateliminatesthe
performanceproblemsofscriptedorinterpretedenvironments
Tomakethedeveloperexperienceconsistentacrosswidely
varyingtypesofapplications,suchasWindows-based
applicationsandWeb-basedapplications
Tobuildallcommunicationonindustrystandardstoensurethat
codebasedonthe.NETFrameworkcanintegratewithanyother
code
The.NETFrameworkobjectivemeetstheneedsofprofessional
developers.Thistextpresentsonlyasmallpartofthe.NETFramework,

butwecannotclimbthemountainuntilwetakethefirststeps.
Thetwomainpartsofthe.NETFrameworkaretheCommonLanguage
Runtimeandthe.NETFrameworkclasslibrary.

TheCommonLanguageRuntime
TheCommonLanguageRuntime(CLR)managestheexecutionofcode


andprovidesservicesthatmaketheexecutionofcodeeasier."Runtime"
meansthatcodeisrunning,whichisanotherwayofsayingitisbeing
executed."CommonLanguage"meansthatthisruntimemanagesthe
executionofcodewritteninseverallanguagesthatsharetheservices
provided.
MicrosoftdevelopedC#totakeadvantageoftheCLR.Itsfeatureswork
especiallywellwiththeCLR.ThepopularVisualBasiclanguageevolved
toVisualBasic.NET,whichisanobject-orientedlanguagethattakes
advantageoftheCLR.VisualBasicprogrammershavetolearnmany
newfeaturestotakeadvantageoftheCLRusingVisualBasic.Net.C++,
likeitsCpredecessor,hasmanycapabilitiesthatdonotfitintothenew
approach.AversionofC++,calledmanagedC++,adaptsC++towork
withtheCLR,soC++programmerscanintegratecodewithotherCLR
users.
WecallcodethatusestheCLRmanagedcode.TheCommonType
Systemdefinesthetypesofdatathatmanagedcodecanuse.A
CommonLanguageSpecification(CLS)definesfeaturesthatevery
languagefordevelopingmanagedcodemustprovide.Programmerswho
useonlyfeaturesintheCommonLanguageSpecificationcanbuildan
applicationcombiningprogramsindifferentlanguages.Theywillknow
thatiftheyuseafeatureinonelanguage,aprograminanotherlanguage
willalsobeabletousethatsameconstruct.

Togiveasimplifiedexample,considernumbers.Supposewehavespace
foronly10numbers.Ifweuseonlynonnegativenumbers,wecanuse0,
1,2,3,4,5,6,7,8,and9.Ifweneedtoincludebothpositiveand
negativevalues,wewouldchoose–5,–4,–3,–2,–1,0,1,2,3,and4.
Theunsignedtypeallowsustouselargervalues,butthesignedtype
allowsustousenegativevalues.Inananalogoussituation,theCommon
TypeSystemprovidesbothunsignedandsignedtypes,butonlyrequires
thatlanguagesprovidesignedtypestosatisfytheCommonLanguage
Specification.
Adeveloperwhousesonlysignedtypescanexpecteverylanguagethat
followstheCLStointeroperatewiththecodeproduced.Adeveloperwho
usesunsignedtypesmayproducecodethatanotherlanguagethat


followstheCLSisnotrequiredtosupport.
Abigproblemfacingdevelopersisthemanydifferenttypesofprocessors
thatruncode.Windows,Macintosh,andUnixmachinesuseawide
varietyofhardware,asdopersonaldigitalassistants,cellphones,large
computers,andotherplatforms.Onewaytomakeaprogramworkon
eachofthesedevicesistotranslatetheprogramtothenativeinstruction
setforthatdevice.Saywehave10programminglanguagesand10
devices.Usingthisapproach,intheworstcase[2]wewouldneed100
compilerstotranslateprogramsineachofthe10languagestonative
codeforeachofthe10devices.Figure1.4diagramsthisjumbleof
compilers.


Figure1.4:Compilingthreelanguagestonativecodeforthree
machines
Anotherapproach,usedbytheCLR,istoprovideanintermediate

languagethatismuchlikethenativelanguagesofdevices.This
languageiscalledMSIL,MicrosoftIntermediateLanguage.Wecompile
eachlanguagetoMSIL.DuringruntimetheCLRusesaJIT(JustIn
Time)compilertocompiletheMSILcodetothenativecodeforthe
deviceused.[3]ThisrequiresoneJITcompilerforeachdeviceto
translateMSILcodetothenativecodeforthatdevice.Thistranslation
processisnotasdifficultastranslatingahigh-levellanguagetonative
code,becausetheMSILcodeissimilartonativecode.



Figure1.5:Compilingusinganintermediate
language
Moreover,usingMSILgreatlyreducesthenumberofcompilersweneed.
For10languagesand10devices,weneedonecompilerforeach
languagetotranslateittoMSIL,andoneJITcompilerforeachdeviceto
translateMSILcodetonativecodeforthatdevice.Thusweneed20
compilersinsteadof100.Figure1.5illustratesthisapproach.

The.NETFrameworkClassLibrary
The.NETFrameworkClassLibraryprovidesalargeandveryusefulset
oftypesthatexpeditethedevelopmentprocess.Thelibrarygroupsthe
typesinnamespacesthatcombinerelatedtypes.Itcontainsabout100
namespacesofwhichweuseonlyasmallnumberinthistext.Someof
thenamespacesfromthelibrarythatweuseare:
System
Containsfundamentaltypes
System.Collections
Definesvariouscollectionsofobjects
System.Data

Managesdatafrommultiplesourcesincludingdatabases
System.Drawing
Providesgraphics
System.IO
Allowsreadingandwriting
System.Net
Providesaninterfacecomputersusetocommunicateover


networks
System.Runtime.Remoting
Supportsdistributedapplications
System.Text
Handlescharacterencoding
System.Threading
Enablesmultithreadedprogramming
System.Web
Enablesbrowser–servercommunication
System.Web.Services
Enablesthebuildinganduseofwebservices
System.Windows.Forms
ForuserinterfacesinWindows-basedapplications
System.Xml
ProvidessupportforprocessingXML
TheBIGPicture
The.NETFrameworkhelpsdevelopersbuildapplicationsforthediverse
Internetenvironment.TheCommonLanguageRuntimeand.NET
FrameworkClassLibraryprovideservicesandtypestomake
programmersmoreproductive.


TestYourUnderstanding
5. WhatdowecallcodethattargetstheCommonLanguage
Runtime?
6. Whatarethetwomainpartsofthe.NETFramework?
Answers


5. managedcode
[1]"Overviewofthe.NETFramework,"fromthe.NETFramework
Developer'sGuide.See />[2]Moderncompilersusesimilartechniquestoreducethenumber
neededtosupportmultipleplatforms.
[3]JavaalsousesaJITcompiler.


1.3OverviewofC#
History
FORTRANandCOBOLwereamongthefirsthigh-levellanguages,
introducedinthelate1950s.Botharestillusedtoday,FORTRANfor
scientificapplicationsandCOBOLforbusiness.Smalltalk,released
around1980,isafullyobject-orientedlanguagethatinfluencedits
successors,includingJavaandC#.
Systemsprogrammerswhoneededaccesstothemachinehardware
usedassemblylanguages,whichareverylow-levelandspecifictothe
hardware.TheClanguage,developedinthemid1970s,issometimes
describedasaportableassemblylanguage.Itisahigh-levellanguage,
likeFORTRANandCOBOL,butprovidesaccesstomachinehardware.
TheUNIXoperatingsystem,developedforthethen-newminicomputers,
wasmostlywritteninC,andbothCandUNIXrapidlygrewinpopularity.
Althoughitisgoodforsystemsprogramming,Cisasmalllanguagethat
doesnotfacilitatethedevelopmentoflargesoftwaresystems.Introduced

inthelater1960s,object-orientedprogrammingstartedtobecome
popularinthemid1980s.Languagesthatsupportobject-oriented
programmingdofacilitatethedevelopmentoflargesoftwaresystems.
C++extendsCtoincludeconstructsthatsupportobject-oriented
programming,whilestillincludingthosethataccessmachinehardware.
Consequently,C++grewinpopularity.
BASICwasdevelopedinthe1960sasaneasierwayforstudentsto
learntoprogram.Itusedaninterpretersostudentscouldimmediately
seetheresultsofexecution.Originally,personalcomputershadvery
limitedmemorychipsinwhichtoholdprograms,soBASIC,whichdidnot
requirecompilationtoalargerlow-levelrepresentation,becamethemain
languageusedonearlyPCs.Asmemorybecamecheaperandgraphics
capabilitiesgrew,BASICmorphedtoVisualBasic,anextremelypopular
languagefortherapiddevelopmentofuserapplications.
Withtheintroductionofthe.NETFramework,VisualBasicevolvedto
VisualBasic.NET,acousinofC#.OnewaywemightdescribeC#isasa


languagethattriestocombinetherapidapplicationdevelopmentof
VisualBasicwithmuchofthepowerofC++.
WiththeriseofdesktopcomputersandtherapidgrowthoftheInternetin
themid1990scametheneedforalanguagetosupportprogrammingto
enableusersonvastlydifferentsystemstointeractinasecureway.
Java,introducedin1995,usesaJavaVirtualMachinetoprovidesecurity
andenableprogramsdevelopedondifferentsystemstointeract.Alarge
libraryextendsitscapabilitiesforInternetprogramming.Becauseitsuited
thenewdemandsondevelopers,Javahasbecomeverypopular.
ThegoalsofC#aresimilartothoseofJava.Thoseversedinoneof
theselanguagescanrapidlyconverttousingtheother.C#hadthe
advantageofseeingtheJavaapproachandhowitmightenhanceit.C#

addsfeaturesfortheeasydevelopmentofcomponentstomakeiteasier
fordeveloperstocombineprogramswrittenondifferentsystems.One
canannotateaC#programwithattributesthatbecomepartofthe
runtimeusedbytheCLR.Thismetadatadescribestheprogramsothat
otherprogramscanuseit.C#,newlydevelopedinthetwenty-first
century,promisestobecomeverypopularastheprimary.NET
programminglanguage.

C#Features
Microsoft[4]identifiesC#asamodernobject-orientedlanguagethat
allowsprogrammerstoquicklybuild.NETcomponentsfromhigh-level
businessobjectstosystem-levelapplications.Thesecomponentscan
easilybeconvertedtowebservicestobeusedovertheInternet.
Importantcharacteristicsare:
Productivityandsafety:C#usesthe.NETplatformsupporting
webtechnologies.C#workswellwithXML,theemerging
standardtopassstructureddataovertheInternet.
TheC#designeliminatesmanycostlyprogrammingerrors.It
includesautomaticmemorymanagementandinitializationof
variables.Itcheckstypestoavoidruntimeerrors.


C#reducesupdatingcostsbysupportingversioninginthe
language,makingiteasierandlesscostlytointroducenew
versionsofaproduct.
Power,expressiveness,andflexibility:C#allowsaclose
connectionbetweentheabstractbusinessprocessandits
softwareimplementation.Thedevelopercanassociatemetadata
withaprogramthatwillallowtoolstodeterminethatacomponent
iscorrectlyidentifiedaspartofabusinessobjectortocreate

reports.
ToavoidtheneedtouseC++toaccessbasicmachinefunctions,
C#permitscarefullyidentifiedlow-levelaccesstomachine
resources.

HowC#Works
C#usesacompiler,butdoesnotimmediatelytranslateahigh-level
programtothemachineinstructionsofeachspecificprocessor.TheC#
compilertakesasinputthehigh-levelC#programandoutputsan
equivalentprogramwrittenusingtheMicrosoftIntermediateLanguage.
DuringruntimetheCLRusesaJITcompilertotranslatetheMSILcodeto
theinstructionsetoftheprocessor.Figure1.6showsthecompilationofa
C#programtoMSILfollowedbytheJITcompilationtonativecodeon
twodifferentprocessors.


Figure1.6:CompilingaC#program
TheadvantageofproducingMSILcodeinsteadofcodeforeachdifferent
processoristhatthesameintermediatecodewillrunonanyprocessor
thathasaCLR.WecandownloadaC#programwhichhasbeen
compiledtointermediatecodeononetypeofmachineandrunitona


×