Tải bản đầy đủ - 0 (trang)
Chapter 2. Getting Started with C#

Chapter 2. Getting Started with C#

Tải bản đầy đủ - 0trang

whatweusedtocallaDOSbox),youmightconsidercreatingaconsole

application.Thisbookmakesextensiveuseofconsoleapplicationsto

illustratethebasicsoftheC#language.

Web,Windows,andconsoleapplicationsaredescribedandillustratedin

thefollowingpages.

Consoleapplications

Aconsoleapplicationrunsinaconsolewindow,asshowninFigure

2-1.Aconsolewindow(orDOSbox)providessimpletext-based

output.

Figure2-1.Aconsoleapplication



Consoleapplicationsareveryhelpfulwhenlearningalanguagebecause

theystripawaythedistractionoftheGraphicalUserInterface.Rather

thanspendingyourtimecreatingcomplexwindowingapplications,you

canfocusonthedetailsofthelanguageconstructs,suchashowyou

createclassesandmethods,howyoubranchbasedonruntime

conditions,andhowyouloop.Allthesetopicswillbecoveredindetailin

comingchapters.

Windowsapplications

AWindowsapplicationrunsonaPC'sdesktop.Youarealready

familiarwithWindowsapplicationssuchasMicrosoftWordorExcel.

Windowsapplicationsaremuchmorecomplexthanconsole

applicationsandcantakeadvantageofthefullsuiteofmenus,

controls,andotherwidgetsyou'vecometoexpectinamodern

desktopapplication.Figure2-2showstheoutputofasimple

windowsapplication.



Figure2-2.AWindowsapplication



ASP.NETapplications

AnASP.NETapplicationrunsonawebserveranddeliversits

functionalitythroughabrowser,typicallyovertheWeb.ASP.NET

technologyfacilitatesdevelopingwebapplicationsquicklyandeasily.

Figure2-3showsamessagefromasimpleASP.NETapplication.

Figure2-3.AnASP.NETapplication



AlthoughmostcommercialapplicationswillbeeitherWindowsor

ASP.NETprograms,consoleapplicationshaveatremendous

advantageinaC#primer.WindowsandASP.NETapplicationsbring

alotmoreoverhead;thereisgreatcomplexityinmanagingthe

windowandalltheeventsassociatedwiththewindow.(Eventsare



coveredinChapter19.)Consoleapplicationskeepthingssimple

allowingyoutofocusonthefeaturesofthelanguage.

Thisbookdoesnotgointoallthemyriaddetailsofbuilding

robustWindowsandASP.NETapplications.Forcomplete

coverageofthesetopics,pleaseseeProgrammingASP.NET

andProgramming.NETWindowsApplications,bothbyJesse

LibertyandDanHurwitz(O'Reilly).



2.1What'sinaProgram?

AprogramconsistsofEnglish-languageinstructionscalledsourcecode.

Thesyntaxfortheseinstructionsisstrictlydefinedbythelanguage.

Sourcecodeconsistsofaseriesofstatements.Astatementisan

instructiontothecomplier.Eachinstructionmustbeformedcorrectly,and

onetaskyou'llfacewhenlearningC#willbetolearnthecorrectsyntaxof

thelanguage.Forexample,inC#everystatementendswithasemicolon.

Eachinstructionhasasemanticmeaningthatexpresseswhatyouare

tryingtoaccomplish.Althoughyoumustfollowthesyntax,thesemantics

ofthelanguagearefarmoreimportantindevelopingeffectiveobjectorientedprograms.Thisbookwillprovideinsightintoboththesyntaxand

thesemanticsofgoodC#programs.

Savethesourcecodeyouwriteinatextfile.Youcanwritethissource

codefileusinganysimpletexteditor(suchasNotepad),oryoucanuse

theVisualStudio.NETIntegratedDevelopmentEnvironment(IDE).

VisualStudio.NETisdescribedinChapter4.

Onceyouwriteyourprogram,youcompileitusingtheC#compiler.The

endresultofcompilingtheprogramisanapplication.



2.2YourFirstProgram:HelloWorld

Inthischapter,youwillcreateaverysimpleapplicationthatdoesnothing

morethandisplaythewords"HelloWorld"toyourmonitor.Thisconsole

applicationisthetraditionalfirstprogramforlearninganynewlanguage;

itdemonstratessomeofthebasicelementsofaC#program.

Onceyouwriteyour"HelloWorld"programandcompileit,thischapter

willprovidealine-by-lineanalysisofthesourcecode.Thisanalysisgives

somethingofapreviewofthelanguage;Chapter5describesthe

fundamentalsmuchmorefully.

Asexplainedearlier,youcancreateC#programswithanytexteditor.

Youcan,forexample,createeachofthethreeprogramsshown

previously(inFigures2-1,2-2,and2-3)withNotepad.Todemonstrate

thatthisispossible,you'llwriteyourveryfirstC#programusingNotepad.

BeginbyopeningNotepadandtypingintheprogramexactlyasshownin

Example2-1.

Example2-1.HelloWorldinNotepad

namespaceNotePad

{

classHelloWorld

{

//everyconsoleappstartswithMain

staticvoidMain()

{



System.Console.WriteLine("Helloworld!");

}

}

}

Thatistheentireprogram.Saveittoyourdiskasafilecalled

helloworld.cs.

We'llexaminethisprograminsomedetailinjustamoment.First,

however,itmustbecompiled.



2.2.1TheCompiler

Onceyousaveyourprogramtodisk,youmustcompilethecodeto

createyourapplication.Compilingyoursourcecodemeansrunninga

compilerandpassinginthesourcecodefile.Yourunthecompilerby

openingacommandprompt(DOSbox)andenteringtheprogramname

csc.Thenyoupassinyoursourcecodefilebyenteringthefilenameon

thecommandline,asinthefollowing:

cscHelloWorld.cs

Thejobofthecompileristoturnyoursourcecodeintoaworking

program.Itturnsouttobejustslightlymorecomplicatedthanthat

because.NETusesanintermediatelanguagecalledMicrosoft

IntermediateLanguage(MSIL,sometimesabbreviatedtoIL).The

compilerreadsyoursourcecodeandproducesIL.The.NETJustInTime

(JIT)compilerthenreadsyourILcodeandproducesanexecutable

applicationinmemory.

Microsoftprovidesacommandwindowwiththecorrectenvironment

variablesset.Openthecommandwindowbyselectingthefollowing

menuitemsinthisorder:



Start->Programs->MicrosoftVisualStudio.NET



->VisualStudio.NETTools->VisualStudio.NETCommandPrompt

Thennavigatetothedirectoryinwhichyoucreatedyourcodefileand

enterthefollowingcommand:

cschelloworld.cs

TheMicrosoftC#compilercompilesyourcode;whenyoudisplaythe

directoryyou'llfindthecompilerhasproducedanexecutablefilecalled

helloworld.exe.Typehelloworldatthecommandprompt,andyour

programexecutes,asshowninFigure2-4.

Figure2-4.CompilingandrunningHelloWorld



Presto!YouareaC#programmer.That'sit,closethebook,you'vedone

it.Okay,don'tclosethebooktherearedetailstoexamine,buttakea

momenttocongratulateyourself.Haveacookie.

Granted,theprogramyoucreatedisoneofthesimplestC#programs

imaginable,butitisacompleteC#program,anditcanbeusedto

examinemanyoftheelementscommontoC#programs.



2.3ExaminingYourFirstProgram

Thesinglegreatestchallengewhenlearningtoprogramisthatyoumust

learneverythingbeforeyoucanlearnanything.Eventhissimple"Hello

World"programusesmanyfeaturesofthelanguagethatwillbe

discussedincomingchapters,includingclasses,namespaces,

statements,staticmethods,objects,strings,inheritance,blocks,libraries,

andevensomethingcalledpolymorphism!

Itisasifyouwerelearningtodriveacar.Youmustlearntosteer,

accelerate,brake,andunderstandtheflowoftraffic.Rightnowwe're

goingtogetyououtonthehighwayandjustletyousteerforawhile.

Overtimeyou'lllearnhowtospeedupandslowdown.Alongtheway

you'lllearntosettheradioandadjusttheheatsothatyou'llbemore

comfortable.Innotimeyou'llbedriving,andthenwon'tyourparents

begintoworry.



2.3.1Line-by-LineAnalysis

Hangontight,we'regoingtozipthroughthisquicklyandcomebackto

thedetailsinsubsequentchapters.

Thefirstlineintheprogramdefinesanamespace:

namespaceNotePad

YouwillcreatemanynameswhenprogramminginC#.Everyobjectand

everytypeofobjectmustbenamed.Itispossibleforthenamesyou

assigntoconflictwiththenamesassignedbyMicrosoftorothervendors.

Anamespaceisawaytosay"thesenamesaremine."

Inthisprogram,you'vecreatedanamespacecalledNotePad.Each

namespacemustbeenclosedinbraces({}).Thus,thesecondlineof

theHelloWorldprogramisanopenbracetomarkthebeginningofthe

NotePadnamespace.Theopenbraceismatchedbyaclosingbraceat



theendoftheprogram.

Withinthebracesofthenamespace,youwriteotherprogramming

constructs.Forinstance,youmightdefinewhatiscalledanobject.Every

objectnamedwithinthesebracesisimplicitlyprefixedwiththename

NotePad.Thedotoperator(.)separatesthenamespacefromthename

oftheobjectwithinthenamespace.Thus,ifyouweretocreateanobject

MyObjectwithinthenamespaceNotePad,therealnameofthatobject

wouldbeNotePad.MyObject.Youcanreadthisaseither"NotePaddot

MyObject"or"NotePadMyObject".Actually,youusethedotoperator

quitealot;you'llseevariousotherusesasweproceed.

Classesdefineacategory,ortype,ofobject.InC#therearethousands

ofclasses.Aclassisanew,user-definedtype.Classesareusedto

defineWindowscontrols(buttons,listboxes,etc.),aswellastypesof

things(employees,students,telephones,etc.)intheprogramyouare

writing.Someclassesyoucreateyourself,andsomeyouobtainfromthe

.NETFramework.Eachclassmustbenamed.

ClassesarethecoreofC#andobject-orientedprogramming.You'lllearn

aboutclassesindetailinChapter3,aswellasinChapter5.

ThethirdlineinourHelloWorldprogramcreatesaclassnamed,aptly,

HelloWorld.Likeanamespace,aclassisdefinedwithinbraces.The

followingcoderepresentstheopeningoftheHelloWorldclassdefinition:

classHelloWorld

{

Amethodisasmallblockofcodethatperformsanaction.TheMain()

methodisthe"entrypoint"foreveryC#consoleapplication;itiswhere

yourprogrambegins.ThenextfewlinesinHelloWorldmarkthe

beginningoftheMain()method:

staticvoidMain()

{



MethodsarecoveredindetailinChapter9butarementionedinvirtually

everychapterinthisbook.

Acomment(hereinbold)appearsjustbeforethestartoftheMain()

method:

//everyconsoleappstartswithMain

staticvoidMain()

{

Acommentisjustanotetoyourself.Youinsertcommentstomakethe

codemorereadabletoprogrammers.Youcanplacecomments

anywhereinyourprogramthatyouthinktheexplanationwillbehelpful;

theyhavenoeffectontherunningprogram.

C#recognizesthreestylesofcomments.ThecommentinHelloWorld

beginswithtwoslashes(//).Theslashesindicatethateverythingtothe

rightonthesamelineisacomment.

Thesecondstyleistobeginyourcommentwithaforwardslashfollowed

byanasterisk(/*)andtoendyourcommentwiththeoppositepattern

(*/).ThesepairsofcharactersarecalledtheopeningC-stylecomment

andtheclosingC-stylecomment,respectively.

ThesecommentsymbolswereinheritedfromtheClanguage

thusthenamesusedtoidentifythem.Theyarealsousedin

C++andJava.



Everythingbetweenthesecommentsymbolsisacomment.C-style

commentscanspanmorethanoneline,asinthefollowing:

/*Thisbeginsacomment

Thislineisstillwithinthecomment



Herecomestheendofthecomment*/

Thethirdandfinalstyleofcommentsusesthreeforwardslashes///.This

isanXML-stylecommentandisusedforadvanceddocumentation

techniques.XMLcommentsarebeyondthescopeofthisbook.

NoticethattheMain()methodisdefinedwiththekeywordsstaticand

void.

staticvoidMain()

Thestatickeywordindicatesthatyoucanaccessthismethodwithout

havinganobjectofyourclassavailable.Whileaclassdefinesatype,

eachinstanceofthattypeisanobject(muchasCardefinesatypeof

vehicleandyouragingrust-bucketisanindividualinstanceofCar).Thus,

whileButtondefinesatypeofcontrolforaWindowsprogram,any

individualprogramwillhavemanyButtonobjects,eachwithitsownlabel

(e.g.,OK,Cancel,Retry).

Normally,methodscanbecalledonlyifyouhaveanobject,butstatic

methodsarespecialandcanbecalledwithoutanobject.(Theuseof

staticmethods,otherthanMain(),isfairlyadvancedandwon'tbe

covereduntilChapter8.)

ThesecondkeywordinthestatementdefiningtheMain()methodis

void:

staticvoidMain()

Typically,onemethodcallsanother.Thecalledmethodwilldowork,and

itcanreturnavaluetothecallingmethod.(You'llseehowmethodscall

oneanotherandreturnvaluesinChapter9.)Ifamethoddoesnotreturn

avalue,itisdeclaredvoid.Thekeywordvoidisasignaltothecompiler

thatyourmethodwillnotreturnavaluetothecallingmethod.

TheoperatingsystemcallsMain()(whentheprogramisinvoked).Itis

possibleforMain()toreturnavalue(typicallyanerrorcode)thatmightbe



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 2. Getting Started with C#

Tải bản đầy đủ ngay(0 tr)

×