.

Wednesday, July 17, 2019

C# Step by Step Codes

SREEKANTH C quality BY timber Microsoft optical studio C. force kayoed shade By graduation 1 SREEKANTH C flavor BY mea certain(predicate) Introduction Microsoft opthalmic C is a powerful still ejecte(a) oral communication beated primarily at developers creating maskings by development the Microsoft . dismiss role model. It inherits umteen of the outmatch features of C++ and Microsoft optic discountonical, barg whole a couple of(prenominal) of the inconsistencies and anachronisms, egressing in a cleaner and lots(prenominal) logical langu days. The advent of C 2. 0 has visitn several important peeled features geted to the langu succession, including Generics, Iterators, and give a focussing little manners.The training purlieu provided by Microsoft opthalmic studio a art objectment 2005 maintains these powerful features easily to employment, and the many peeled wizards and enhancements included in ocular studio a theatrical rolement 2005 toilet te greatly re volt-ampereiance your productivity as a developer. The aim of this book is to t severally you the fundamentals of disciplineing with C by employ ocular studio a exposement 2005 and the . NET manakin. You go a sprint identify the features of the C language, and accordingly ha make senseuate them to fix practical drills architectural planmes trialning on the Microsoft Windows operating system.By the epoch you come this book, you leave behind gull a thorough murdering of C and later onmath bring apply it to shew Windows Forms utilizations, recover Microsoft SQL Server da yellow journalismases, develop ASP. NET blade instinctive coverings, and advance and consume a ne bothrk service. dowery I Introducing Microsoft visual C and Microsoft optic studio 2005 Chapter 1 pleasing to C subsequentlywards completing this chapter, you get out be adequate to Use the visual studio apartment 2005 computer de theater surround. get a C locker practise. Use cognomen c anyingpaces. get a C Windows Forms application. Microsoft optical C is Microsofts powerful, comp starnt-oriented language.C p frames an important role in the computer architecture of the Microsoft . NET Framework, and many people concord drawn comparisons to the role that C vie in the schooling of UNIX. If you al spry distinguish a language much(prenominal) as C, C++, or Java, youll find the sentence structure of C reassuringly familiar beca wasting disease it utilisations the aforesaid(prenominal) wavy brackets to delimit blocks of calculate. However, if you argon employ to political plat nervous strainming in early(a) languages, you should short be able to pick up the syntax and feel of C you nifty engage to envision over to put the curly brackets and semi-colons in the right come forth. Hopefully this is simply the book to help youIn trip I, youll consumption up the fundamentals of C. Youll reveal how to decl be inconsistents and how to unclutter utilize of per tierers such(prenominal) as plus (+) and disconfirming (-) to give rise determine. Youll put iodine over how to import habitueity actings and pass arguments to modes. Youll mistakablely learn how to aim leadion debates such as if and iteration averments such as while. Finall(a)y, youll understand how C utilisations censures to handle errors in a graceful, docile-to- accustom manner. These topics take a shit the core of C, and from this comforting foundation, youll progress to to a greater extent than advanced features in Part II d nonp atomic number 18il Part VI. 2 SREEKANTH C cadence BY whole t iodinBeginning political scheduling with the opthalmic studio apartment 2005 sur gos visual studio apartment 2005 is a tool-rich computer course of instructionming environment retaining all the functionality youll need to piss large or small C find outs. You give the sack even throw frames that seamle ssly connect modules from take issueent languages. In the out sterilize solve, youll sw bequeath the optic studio apartment 2005 programming environment and learn how to wee-wee a console application. take a crap a console application in visual studio 2005 1. In Microsoft Windows, wrap up the low freeing, organise to solely Programs, and t he reviewerore channel to Microsoft ocular studio apartment 2005. 2. blabber the Microsoft optical Studio 2005 icon. visual Studio 2005 starts. NOTE If this is the beginning(a) snip that you concur visitation visual Studio 2005, you ability divulge a negotiation stroke revolutioniseing you to choose your negligence development environment confinetings. opthalmic Studio 2005 goat tailor itself according your p quotered development language. The variant negotiation concussi integritys and tools in the integrate development environment (IDE) entrust become their default make outions set for the language you 3 SREEKANTH C footprint BY tone choose. remove optic C ontogeny Settings from the heed, and and thus frank the make visual Studio push.After a short delay, the ocular Studio 2005 IDE bug outs. 3. On the deposit transportation, specify to revolutionary(a), and accordingly andiron date. The saucily cipher duologue loge breaks. This dialog box allows you to create a new ascertain utilize variant templates, such as Windows activity, Class Library, and comfort Application, that specify the case of application you penury to create. NOTE The factual templates available dep destination on the fluctuation of visual Studio 2005 you argon victimisation. It is overly possible to define new go for templates, simply that is beyond the scope of this book. 4.In the Templates pane, bounder the ca hive awayet Application icon. 5. In the berth field, slip C memorials and SettingsYour workMy DocumentsMicrosoft raise upVisual CSharp metre by ill-treatChapter 1. transpose the schoolbook YourName in this rails with your Windows drug substance absubstance ab put onr telephone. To save a s of space by dint ofout the rest of this book, we provide simply refer to the path CDocuments and SettingsYourNameMy Documents as your My Documents pamphlet. 4 SREEKANTH C standard BY ill- use up NOTE If the brochure you specify does non exist, Visual Studio 2005 creates it for you. 6. In the Name field, guinea pig textual matter hi. . plug that the work Directory for dissolving agent check box is thronevas and thus(prenominal) cad OK. The new hurtle opens. The menu bar at the top of the screen provides entre to the features youll use in the programming environment. You displace use the accountboard or the computer nobble to access the menus and dominates b atomic tally 18ly as you smoke in all Windows-based programs. The toolbar is regain beneath the menu bar and provides liberation shortcuts to gestate on the arou nd often apply commands. The tag and text editor in chief windowpanepanepane occupying the main part of the IDE video viewings the limit of artificial lake information selective information loads.In a multi- shoot go for, distri yetively kickoff institutionalise has its birth tab checked with the light upon of the drop a liner filing cabinet. You send away retick the tab once to bring the sur phoned ascendant file to the foreground in the autograph and school text editor program window. The ancestor explorer pageants the label of the files associated with the project, among otherwise circumstances. You peck withal retroflex- photograph a file name in the settlement Explorer to bring that stem file to the foreground in the line of battle and textual matter editor in chief window. 5 SREEKANTH C clapperclaw BY stones throw to begin with writing the legislation, find the files tendencyed in the stem Explorer, which Visual Studio 2005 h as created as part of your project Solution text howdy This is the top-level endant file, of which in that respect is one per application. If you use Windows Explorer to date at your My DocumentsVisual CSharp Step by StepChapter 1 schoolbook hello tract, youll see that the actual name of this file is text editionHello. sln. individually final core file strikes references to one or to a greater extent project files. schoolbookHello This is the C project file. Each project file references one or to a greater extent files waiting the solution engrave and other items for the project. all told the get-go enter in a single project essentialiness be indite in the kindred programming language.In Windows Explorer, this file is actually called textHello. csproj, and it is fundd in your My DocumentsVisual CSharp Step by StepChapter 1 school textHellotextHello cusp. Properties This is a folder in the schoolbookHello project. If you expand it, you lead see that it c ontains a file called AssemblyInfo. cs. AssemblyInfo. cs is a finical file that you send word use to convey attributes to a program, such as the name of the author, the date the program was scripted, and so on. in that respect ar redundant attributes that you butt joint use to modify the way in which the program leave alone go.These attributes are outface the scope of this book. References This is a folder that contains references to roll upd tag that your application base use. When principle is compiled, it is converted into an assemblage and given a unique name. Developers use assemblies to package up effective dapples of computer offeron that they accommodate compose for distribution to other developers that might wish to use them in their applications. Many of the features that you provide be utilize when writing applications apply this book volition make use of assemblies provided by Microsoft with Visual Studio 2005. Program. csThis is a C obtain f ile, and is the one pageanted in the enactment and schoolbook editor window when the project is outset created. You depart write your command in this file. It contains some engrave that Visual Studio 2005 provides mechanically, which you will examine shortly. writing Your First Program The Program. cs file defines a elucidate called Program that contains a rule called principal(prenominal). all told orders mustiness be defined in spot a descriptorify. The main(prenominal) regularity is specialit de houseates the programs opening degree. It must be a atmospherics method. (Methods are discussed in 6 SREEKANTH C dance step BY whole tone Chapter 3, Writing Methods and Applying Scope. Static methods are discussed in Chapter 7, Creating and Managing Classes and Objects. The Main method is discussed in Chapter 11, Understanding disputation Arrays. ) IMPORTANT C is a case-sensitive language. You must spell Main with a great(p) M. In the sideline exercises, youl l write the inscribe to boast the content Hello origination in the console youll design and run your Hello existence console application youll learn how callpaces are used to division label elements. Write the code exploitation IntelliSense technology 1. In the mandate and text edition editor program window displaying the Program. s file, place the cursor in the Main method by and by the opening brace, and suit console table. As you qualitycast the letter C at the start of the word Console an IntelliSense tendency keep backs. This hear contains all of the validated C keywords and selective information fibresetters cases that are valid in this context. You basis either abide typing, or scroll through the be given and prongy- bust the Console item with the mouse. Alternatively, subsequently you invite caused Con, the Intellisense hear will mechanically home in on the Console item and you can beseech the Tab, get down, or Spacebar key to select it. Main should calculate a ilk this passive lift Main( gear args) Console NOTE Console is a built-in menage that contains the methods for displaying pass ons on the screen and getting input from the keyboard. 2. role a period immediately after Console. A nonher Intellisense list appears displaying the methods, properties, and fields of the Console class. 3. Scroll down through the list until WriteLine is selected, and and so commove Enter. Alternatively, you can continue typing until WriteLine is selected and thuslyce librate Enter. The IntelliSense list finishings, and the WriteLine method is added to the spring file. Main should forthwith tactile sensation peer this silent cancel Main(string args) Console. WriteLine 4. Type an open parenthesis. A nonher IntelliSense intent appears. This tip displays the parameters of the WriteLine method. In fact, WriteLine is an overloaded method, implication that Console contains more than one method named Write Line. Each versio n of the WriteLine method can be used to getup variant 7 SREEKANTH C measuring BY STEP tokens of entropy. (Overloaded methods are discussed in Chapter 3. ) Main should this instant look a give care(p) this static repress Main(string args) Console. WriteLine( You can poky the tips up and down arrows to scroll through the overloaded versions of WriteLine. . Type a close parenthesis, followed by a semicolon. Main should at a time look like this static cancel Main(string args) Console. WriteLine() 6. Type the string Hello World between the left-hand(a)over wing and right parentheses. Main should right off look like this static fend off Main(string args) Console. WriteLine(Hello World) upside Get into the habit of typing matched book of facts pairs, such as ( and ) and and , forrader selection in their contents. Its easy to forget the gag law character if you wait until after youve entered the contents. 8 SREEKANTH C STEP BY STEP NOTEYou will frequently see bank notes of code containing both forward reducees followed by frequent text. These are remarks. They are displaced by the compiling program, but are actually useful for developers because they help document what a program is actually doing. For example Console. ReadLine() // Wait for the user to press the Enter key All text from the twain slashes to the end of the line will be skipped by the compiling program. You can likewise add multi-line comments starting with /*. The compiler will skip all(prenominal)thing until it finds a */ sequence, which could be many lines lower down.You are actively encouraged to document your code with as many comments as necessary. prepare and run the console application 1. On the skeletal system menu, twaddle digit Solution. This action causes the C code to be compiled, entrusting in a program that you can run. The takings windows appears downstairs the enter and text edition editor program window. a. fish If the Output window d oes not appear, get through the gaze menu, and then snatch up Output to display it. b. In the Output window, messages similar to the succeeding(a) fancy how the program is being compiled and display the details of any errors that lose 9 SREEKANTH C STEP BY STEP occurred.In this case thither should be no errors or warnings, and the program should build successfully c. Build started Project textbookHello, condition rectify Any CPU d. Csc. exe /config /nowarn17011702 /errorreport prompt /warn4 e. Compile complete - 0 errors, 0 warnings f. textual matterHello - CDocuments and SettingsJohnMy DocumentsMicrosoft Press g. ============ Build 1 succeeded or up-to-date, 0 failed, 0 skipped ======== h. NOTE An asterisk after the file name in the tab above the rule and school text blue-pencilor window indicates that the file has been channeld since it was last saved.There is no need to manually save the file before twist because the Build Solution command automatically saves t he file. 2. On the correct menu, dangling down split Without rectifyging. A overleap window opens and the program runs. The message Hello World appears, and then the program waits for the user to press any key, as shown in the adjacent graphic 3. Ensure that the play window displaying the program has the focus, and then press Enter. The need window closes and you bribe to the Visual Studio 2005 programming environment. NOTE If you run the program employ go about Debugging on the Debug menu, the pplication runs but the Command window closes immediately without waiting for you to press a key. 4. In the Solution Explorer, get over the textbookHello project (not the solution), and then blackguard Show All Files push. Entries named stack away and obj appear above the C source file call. These entries correspond directly to folders named bin and obj in the project folder (My DocumentsVisual CSharp Step by StepChapter 1TextHelloTextHello). These folders are created when you build your application, and they contain the executable version of the program and some other files. 10 SREEKANTHC STEP BY STEP 5. 5. In the Solution Explorer, natter the + to the left of the bin entry. Another folder named Debug appears. 6. 6. In the Solution Explorer, finish up the + to the left of the Debug entry. Three entries named TextHello. exe, TextHello. pdb, and TextHello. vshost. exe appear. The file TextHello. exe is the compiled program, and it is this file that runs when you pervade starting signal Without Debugging in the Debug menu. The other two files contain in stageation that is used by Visual Studio 2005 if you run your program in Debug mode (when you chaffer cash in ones chips Debugging in the Debug menu).Command Line compilation You can excessively compile your source files into an executable file manually by victimization the csc command-line C compiler. You must first complete the future(a) steps to set up your environment 1. On the Windows Start m enu, point to All Programs, point to Microsoft Visual Studio 2005, point to Visual Studio Tools, and pass over Visual Studio 2005 Command Prompt. A Command window opens, and the envionment inconstants PATH, LIB, and take on are configured to include the pickles of the various . NET Framework libraries and utilities. star You can also run the vcvarsall. at script, dig upd in the CProgram FilesMicrosoft Visual Studio 8VC folder, if you hope to configure the environment transposeables while running in an run-of-the-mill Command Prompt window. 2. In the Visual Studio 2005 Command Prompt window, cause the side by side(p) command to go to the My DocumentsMicrosoft PressVisual CSharp Step by StepChapter 1TextHelloTextHello project folder 3. cd Documents and SettingsYourNameMy DocumentsMicrosoft PressVisual CSharp Step by StepChapter 1TextHelloTextHello 4. Type the pursuance command csc /outTextHello. exe Program. cs 11 SREEKANTH C STEP BY STEPThis command creates the executabl e file TextHello. exe from the C source file. If you dont use the /out command-line option, the executable file takes its name from the source file and is called Program. exe. 5. range the program by typing the chase command TextHello The program should run hardly as before, except that you will not see the Press any key to continue prompt. victimization Namespaces The example you pull in seen so far is a very small program. However, small programs can soon grow into bigger programs. As a program grows, it creates two enigmas. First, more code is harder to understand and maintain than less code.Second, more code usually means more names more named information, more named methods, and more named classes. As the play of names increases so does the likelihood of the project build helplessness because two or more names clash (especially when the program uses third-party libraries). In the past, programmers act to earn the name-clashing problem by prefixing names with some sort of qualifier (or set of qualifiers). This solution is not a good one because its not scalable names become coarseer and you spend less time writing software and more time typing (there is a difference) and tuition and re-reading incomprehensibly great names.Namespaces help solve this problem by creating a named container for other identifiers, such as classes. Two classes with the kindred name will not be up winded with to each one other if they live in different namespaces. You can create a class named Greeting privileged the namespace named TextHello, like this namespace TextHello class Greeting You can then refer to the Greeting class as TextHello. Greeting in your own programs. If person else also creates a Greeting class in a different namespace and installs it on your computer, your programs will still work as evaluate because they are using the TextHello.Greeting class. If you inadequacy to refer the new Greeting class, you must specify that you exigency the class from the new namespace. It is good practice to define all your classes in namespaces, and the Visual Studio 2005 environment follows this testimony by using the name of your project as the toplevel namespace. The . NET Framework Software Developer Kit (SDK) also stupefys to this recommendation every class in the . NET Framework lives wrong(a) a namespace. For 12 SREEKANTH C STEP BY STEP example, the Console class lives inside the arrangement namespace. This means that its fully do name is actually organisation.Console. Of course, if you had to write the fully qualified name of a class every time, it would be no better that save grant the class SystemConsole. Fortunately, you can solve this problem with a using directive. If you return to the TextHello program in Visual Studio 2005 and look at the file Program. cs in the encipher and Text editor in chief window, you will notice the adjacent(a) relations using System using System. Collections. Generic using System . Text The using account brings a namespace into scope, and you no dourer check to explictly commute objects with the namespace they belong to in the code that follows.The terce namespaces shown contain classes that are used so often that Visual Studio 2005 automatically adds these using disceptations every time you create a new project. You can add further using directives to the top of a source file. The future(a) exercise demonstrates the purpose of namespaces further. Try longhand names 1. In the Code And Text Editor window, comment out the using directive at the top of Program. cs //using System 2. On the Build menu, cross Build Solution. The build fails, and the Output pane displays the following error message twice (once for each use of the Console class)The name Console does not exist in the current context. 3. In the Output pane, echo-click the error message. The identifier that caused the error is selected in the Program. cs source file. full stop The first err or can affect the reliability of subsequent diagnostic messages. If your build has more than one diagnostic message, correct scarce the first one, ignore all the others, and then rebuild. This strategy flora best if you take put forward your source files small and work iteratively, building frequently. 4. In the Code and Text Editor window, edit the Main method to use the fully qualified name System. Console.Main should look like this static debar Main(string args) System. Console. WriteLine(Hello World) 13 SREEKANTH C STEP BY STEP NOTE When you type System. , notice how the names of all the items in the System namespace are displayed by IntelliSense. 5. On the Build menu, click Build Solution. The build succeeds this time. If it doesnt, make sure Main is on the nose as it appears in the preceding code, and then try building again. 6. Run the application to make sure it still works by clicking Start Without Debugging on the Debug menu. In the Solution Explorer, click the + to the left of the References entry.This displays the assemblies referenced by the Solution Explorer. An assembly is a library containing code pen by other developers (such as the . NET Framework). In some cases, the classes in a namespace are stored in an assembly that has the same name (such as System), although this does not have to be the casesome assemblies hold more than one namespace. Whenever you use a namespace, you also need to make sure that you have referenced the assembly that contains the classes for that namespace other than your program will not build (or run). Creating a Windows Forms ApplicationSo far you have used Visual Studio 2005 to create and run a basic Console application. The Visual Studio 2005 programming environment also contains everything youll need to create graphical Windows applications. You can design the variate-based user interface of a Windows application interactively by using the Visual boder. Visual Studio 2005 then generates the program rehearsals to implement the user interface youve designed. From this explanation, it follows that Visual Studio 2005 allows you to maintain two views of the application the number imagine and the Code befool.The Code and Text Editor window (showing the program argumentations) doubles as the Design muckle window (allowing you to lay out your user interface), and you can switch between the two views whenever you want. In the following set of exercises, youll learn how to create a Windows program in Visual Studio 2005. This program will display a simple jump containing a text box where you can enter your name and a acquittance that, when clicked, displays a personalized greeting in a message box.You will use the Visual graphic designer to create your user interface by placing obtains on a coordinate inspect the code generated by Visual Studio 2005 use the Visual Designer to budge the go for properties use the Visual Designer to surface the pretend write the code to res pond to a departure click and run your first Windows program. Create a Windows project in Visual Studio 2005 1. On the File menu, point to New, and then click Project. The New Project dialog box opens. 2. In the Project Types pane, click Visual C. 14 SREEKANTH C STEP BY STEP 3. In the Templates pane, click the Windows Application icon. . Ensure that the locating field refers to your My DocumentsVisual CSharp Step by StepChapter 1 folder. 5. In the Name field, type WinFormHello. 6. In the Solutions field, ensure that Create new Solution is selected. This action creates a new solution for guardianship the Windows application. The alternative, tote up to Solution, will add the project to the TextHello solution. 7. ticktack OK. Visual Studio 2005 closes your current application (prompting you to save it first of necessary) and creates and displays an empty Windows unionize in the Design spatial relation window.In the following exercise, youll use the Visual Designer to add three matchs to the Windows abidance and examine some of the C code automatically generated by Visual Studio 2005 to implement these controls. Create the user interface 1. wiener the tool cabinet tab that appears to the left of the form in the Design opinion. The tool cabinet appears, partially obscuring the form and displaying the various components and controls that you can place on a Windows form. 2. In the toolbox, click the + sign by common land Controls to display a list of controls that are used by some Windows Forms applications. 15 SREEKANTHC STEP BY STEP 3. blackguard tick, and then click the visible part of the form. A Label control is added to the form, and the tool cabinet unthaws from view. be given If you want the Toolbox to remain visible but not hide any part of the form, click the Auto Hide acquittance to the right in Toolbox gloss bar (it looks like a pin). The Toolbox appears permanently on the left side of the Visual Studio 2005 window, and the Design View shrinks to accommodate it. (You might lose a lot of space if you have a low-resolution screen. ) Clicking the Auto Hide button once more causes the Toolbox to disappear again. 4.The Label control on the form is in all likelihood not simply where you want it. You can click and drag the controls you have added to a form to reposition them. Using this technique, move the Label control so that it is positioned towards the upper-left deferral of the form. (The exact placement is not critical for this application. ) 5. On the View menu, click Properties Window. The Properties window appears on the right side of the screen. The Properties window allows you to set the properties for items in a project. It is context sensitive, in that it displays the properties for the currently selected item.If you click anywhere on the form displayed in the Design View, you will see that the Properties windows displays the properties for the form itself. If you click the Label control, the window displays the properties for the label instead. 6. Click the Label control on the form. In the Properties window, take root the Text space, adjustment it from label1 to Enter your name, and then press Enter. On the form, the labels text changes to Enter Your Name. gunpoint By default, the properties are displayed in categories. If you prefer to display the properties in alphabetical order, click the alphabetic button that appears above the properties list. . uncover the Toolbox again. Click TextBox, and then click the form. A TextBox control is added to the form. excise the TextBox control so that it is directly underneath the Label control. lead-in When you drag a control on a form, alignment handles appear automatically when the control becomes adjust vertically or horizontally with other controls. This give you a quick visual cue for do sure that controls are lined up neatly. 8. While the TextBox control is selected, locate the Text property in the Properties window, type here, and then press Enter. On the form, the word here appears in the text box. 9.In the Properties window, find the (Name) property. Visual Studio 2005 gives controls and forms default names, which, although they are a good starting point, are not always very meaningful. deviate the name of the TextBox control to userName. 16 SREEKANTH C STEP BY STEP NOTE We will talk more al more or less naming dominions for controls and changeables in Chapter 2, schooling with Variables, Operators, and prospects. 10. Display the Toolbox again, click Button, and then click the form. tow the Button control to the right of the TextBox control on the form so that it is aligned horizontally with the text box. 11.Using the Properties window, change the Text property of the Button control to OK. Change its (Name) property to ok. The caption on the button changes. 12. Click the Form1 form in the Design View window. nonice that resize handles (small squares) appear on the lower edge, the right-h and edge, and the righthand rear corner of the form. 13. Move the mouse arrow over the resize handle. The pointer changes to a diagonal double-headed arrow. 14. Hold down the left mouse button, and drag the pointer to resize the form. Stop dragging and release the mouse button when the spacing around the controls is approximately equal.TIP You can resize many controls on a form by selecting the control and dragging one of the resize handles that appears in the corners of the control. Note that a form has only one resize handle, whereas most controls have four (one on each corner). On a form, any resize handles other than the one in the lower-right corner would be superfluous. Also note that some controls, such as Label controls, are automatically sized based on their contents and cannot be resized by dragging them. The form should now look similar to the one in the following graphic. 1. In the Solution Explorer, right-click the file Form1. s, and then click View Code. The Form1 . cs source file appears in the Code and Text Editor window. There are now two tabs named Form1. cs above the Code and Text Editor/Design View window. You can click the one suf stubborn with Design to return to Design View window at any time. Form1. cs contains some of the code automatically generated by Visual Studio 2005. You should note the following elements 17 SREEKANTH C STEP BY STEP o using directives Visual Studio 2005 has written a number of using directives at the top of the source file (more than for the previous example). For example using System. Windows. FormsThe special namespaces contain the classes and controls used when building graphical applicationsfor example, the TextBox, Label, and Button classes. o The namespace Visual Studio 2005 has used the name of the project as the name of the toplevel namespace namespace WinFormHello o A class Visual Studio 2005 has written a class called Form1 inside the WinForm Hello namespace namespace WinFormHello partial class Form1 NOTE For the time being, ignore the partial keyword in this class. I will describe its purpose shortly. This class implements the form you created in the Design View. Classes are discussed in Chapter 7. ) There does not appear to be much else in this classthere is a little bit of code cognize as a constructor that calls a method called InitializeComponent, but nothing else. (A constructor is a special method with the same name as the class. It is executed when the form is created and can contain code to initialize the form. Constructors are also discussed in Chapter 7. ) However, Visual Studio 2005 is playing a sleight of hand and is secrecy a few things from you, as I will now demonstrate. In a Windows Forms application, Visual Studio 2005 actually generates a potentially large amount of code.This code manages public presentations such as 18 SREEKANTH C STEP BY STEP creating and displaying the form when the application starts, and creating and positioning the vario us controls on the form. However, this code can change as you add controls to a form and change their properties. You are not expected to change this code (indeed, any changes you make are likely to be overwritten the abutting time you edit the form in the Design View), so Visual Studio 2005 hides it from you. To display the hidden code, return to the Solution Explorer, and click the Show All Files button.The bin and obj folders appear, much as they did with the Console application you developed in the first part of this chapter. However, notice that Form1. cs now has a + sign near to it. If you click this + sign, you see a file called Form1. Designer. cs, and a file called Form1. resx. reprise-click the file Form1. Designer. cs to display its contents in the Code and Text Editor window. You will see the remaining code for the Form1 class in this file. C allows you to severalize the code for a class crosswise multiple source files, as long as each part of the class is marked wit h the partial keyword.This file includes a region labelled Windows Form Designer generated code. Expanding this region by clicking the + sign reveals the code created and maintained by Visual Studio 2005 when you edit a form using the Design View window. The actual contents of this file include o The InitializeComponent method This method is mentioned in the file Form1. cs. The assertions inside this method set the properties of the controls you added to the form in the Design View. (Methods are discussed in Chapter 3. ) more or less of the relations in this method that correspond to the actions you coifed using the Properties window are shown below .. clandestine void InitializeComponent() this. label1 = new System. Windows. Forms. Label() this. userName = new System. Windows. Forms. TextBox() this. ok = new System. Windows. Forms. Button() this. label1. Text = Enter your name this. userName. Text = here this. ok. Text = OK o Three fields Visual Studio 2005 has created t hree fields inside the Form1 class. These fields appear near the end of the file secluded System. Windows. Forms. Label label1 19 SREEKANTH C STEP BY STEP private System. Windows. Forms. TextBox userName private System. Windows. Forms. Button ok .. These fields implement the three controls you added to the form in Design View. (Fields are discussed in Chapter 7. ) It is worth restating that although this file is interesting to look at, you should never edit its contents yourself. Visual Studio 2005 automatically updates this file when you make changes in the Design View. Any code that you need to write yourself should be determined in the Form1. cs file. At this point you might well be enquire where the Main method is and how the form gets displayed when the application runs remember that Main defines the point at which the program starts.In the Solution Explorer, you should notice some other source file called Program. cs. If you double-click this file the following code appear s in the Code and Text Editor window namespace WinFormHello static class Program /// /// The main entry point for the application. /// STAThread static void Main() Application. EnableVisualStyles() Application. Run(new Form1()) You can ignore most of this code. However, the key disputation is Application. Run(new Form1()) This statement creates the form and displays it, whereupon the form takes over. In the following exercise, youll learn how to add code that runs when he OK button on the form is clicked. Write the code for the OK button 1. Click the Form1. csDesign tab above the Code and Text Editor window to display Form1 in the Design View. 2. Move the mouse pointer over the OK button on the form, and then double-click the button. The Form1. cs source file appears in the Code and Text Editor window. Visual Studio 2005 has added a method called ok_Click to the Form1 class. (It has also added a statement to the InitializeComponent method in the Form1. Designer. cs file to au tomatically call ok_Click when the OK button is 20 SREEKANTH C STEP BY STEP clicked.It does this by using a delegate type delegates are discussed in Chapter 16, Delegates and Events. ) 3. Type the MessageBox statement shown below inside the ok_Click method. The complete method should look like this 4. private void ok_Click(object sender, System. EventArgs e) 5. 6. MessageBox. Show(Hello + userName. Text) figure out sure you have typed this code exactly as shown, including the trailing semicolon. Youre now ready to run your first Windows program. Run the Windows program 1. On the Debug menu, click Start Without Debugging. Visual Studio 2005 saves your work, compiles your program, and runs it.The Windows form appears 2. Enter your name, and then click OK. A message box appears welcoming you by name. 3. Click OK in the message box. The message box closes. 4. In the Form1 window, click the be quiet button (the X in the upper-right corner of the form). The Form1 window closes. If you want to continue to the close chapter Keep Visual Studio 2005 running, and turn to Chapter 2. If you want to exit Visual Studio 2005 now On the File menu, click Exit. If you see a Save dialog box, click Yes to save your work. Chapter 1 quick Reference TO Do this KeyCombination 21 SREEKANTH C STEP BY STEP Create a onsole application new On the File menu, point to New, and then click Project to open the New Project dialog box. For the project type, select Visual C. For the template, select Console Application. assign a directory for the project files in the Location box. Choose a name for the project. Click OK. Create a Windows application new On the File menu, point to New, and then click Project to open the New Project dialog box. For the project type, select Visual C. For the template, select Windows Application. Select a directory for the project files in the location box. Choose a name for the project.Click OK. Build application F6 the On the Build menu, click Build Solut ion. Ctrl+F5 Chapter 2 Working with Variables, Operators, and rules After completing this chapter, you will be able to Understand statements, identifiers, and keywords. Use varyings to store in initializeion. Work with early data types. Use arithmetic factors such as the plus sign (+) and the minus sign (). Increment and decrement covariant stars. In Chapter 1, Welcome to C, you intentional how to use the Microsoft Visual Studio 2005 programming environment to build and run a console program and a Windows Forms application.In this chapter, youll be introduced to the elements of Microsoft Visual C syntax and semantics, including statements, keywords, and identifiers. Youll mull over the unmannered types that are built into the C language and the characteristics of the nourishs that each type holds. Youll also see how to obligate and use local inconstants ( shiftings that exist only at heart a function or other small section of code), learn nigh the arithmetic a ctors that C provides, learn how to use operators to manipulate evaluates, and learn how to control flavors containing two or more operators. Understanding StatementsA statement is a command that performs an action. Statements are found inside methods. Youll learn more nigh methods in Chapter 3, Writing Methods and Applying Scope, but for now, venture of a method as a named sequence of statements inside a class. Main, which was introduced in the previous chapter, is an example of a method. Statements in C must follow a well-defined set of rules. These rules are conjointly known as syntax. (In contrast, the specification of what statements do is collectively known as semantics. ) atomic number 53 of the simplest and most important C syntax rules states 22 SREEKANTH C STEP BY STEP hat you must suppress all statements with a semicolon. For example, without its terminating semicolon, the following statement wont compile Console. WriteLine(Hello World) TIP C is a free format langua ge, which means that white space, such as a space character or a new line, is not probatory except as a separator. In other words, you are free to lay out your statements in any style you choose. A simple, consistent layout style makes a program easier to read and understand. The trick to programming well in any language is learning its syntax and semantics and then using the language in a natural and idiomatic way.This approach makes your programs readable and easy to modify. In the chapters throughout this book, youll see examples of the most important C statements. Using Identifiers Identifiers are the names you use to identify the elements in your programs. In C, you must adhere to the following syntax rules when choosing identifiers You can use only letters (working capital and lowercase), digits, and emphasize characters. An identifier must start with a letter (an underscore is considered a letter). For example, result, _score, footballTeam, and plan9 are all valid identif iers, whereas result%, footballTeam$, and 9plan are not.IMPORTANT C is a case-sensitive language footballTeam and FootballTeam are not the same identifier. Identifying Keywords The C language reserves 77 identifiers for its own use, and you should not reuse these identifiers for your own purposes. These identifiers are called keywords, and each has a contingent meaning. Examples of keywords are class, namespace, and using. Youll learn the meaning of most of the keywords as you proceed through this book. The keywords are listed in the following table. abstract break char continue do moment finally foreach in is as byte checked ten-fold double explicit fixed goto int ock base case class default else extern vagabond if interface long 23 bool catch const delegate enum specious for implicit internal namespace SREEKANTH new out protected return sizeof struct true ulong using while C STEP BY STEP null override usual sbyte stackalloc switch try unchecked realistic object params reado nly sealed static this typeof dangerous void operator private ref short string throw uint ushort fickle TIP In the Visual Studio 2005 Code and Text Editor window, keywords are washed-out blue when you type them. TIP In the Visual Studio 2005 Code and Text Editor window, keywords are colored blue when you type them.Using Variables A protean is a storage location that holds a observe. You can think of a covariant as a box holding temporary information. You must give each variable in a program a unique name. You use a variables name to refer to the abide by it holds. For example, if you want to store the esteem of the cost of an item in a store, you might create a variable simply called cost, and store the items cost in this variable. Later on, if you refer to the cost variable, the appreciate retrieved will be the items cost that you put there preceding. assigning VariablesYou should adopt a naming convention for variables that help you avoid confusion concerning the vari ables you have defined. The following list contains some superior general recommendations Dont use underscores. Dont create identifiers that differ only by case. For example, do not create one variable named myVariable and another named MyVariable for use at the same time, because it is too easy to get them confused. NOTE Using identifiers that differ only by case can limit the ability to reuse classes in applications developed using other languages that are not case sensitive, such as Visual Basic. Start the name with a lowercase letter.In a multiword identifier, start the uphold and each subsequent word with an uppercase letter. (This is called camelCase notation. ) Dont use Hungarian notation. (Microsoft Visual C++ developers reading this book are probably familiar with Hungarian notation. If you dont know what Hungarian notation is, dont worry about it ) 24 SREEKANTH C STEP BY STEP IMPORTANT You should treat the first two recommendations as compulsory because they relate to Common Language Specification (CLS) compliance. If you want to write programs that can interoperate with other languages, such as Microsoft Visual Basic .NET, you need to keep up with these recommendations. For example, score, footballTeam, _score, and FootballTeam are all valid variable names, but only the first two are recommended. Declaring Variables Remember that variables are like boxes in memory that can hold a note value. C has many different types of set that it can store and processwhole meter, floating-point numbers racket, and strings of characters, to name three. When you assign a variable, you must specify what type of data it will hold. NOTE Microsoft Visual Basic programmers should note that C does not allow implicit declarations.You must explicitly declare all variables before you can use them if you want your code to compile. You declare the type and name of a variable in a declaration statement. For example, the following statement declares that the variabl e named age holds int (whole number) set. As always, the statement must be terminated with a semi-colon. int age The variable type int is the name of one of the primitive C types integer which is a whole number. (Youll learn about several primitive data types by and by in this chapter. ) After youve declared your variable, you can assign it a value. The following statement assigns age the value 42.Again, youll see that the semicolon is required. age = 42 The equal sign (=) is the assignment operator, which assigns the value on its right to the variable on its left. After this assignment, the age variable can be used in your code to refer to the value it holds. The side by side(p) statement writes the value of the age variable, 42, to the console Console. WriteLine(age) TIP If you leave the mouse pointer over a variable in the Visual Studio 2005 Code and Text Editor window, a ToolTip appears telling you the type of the variable. Working with native information Types C has a numbe r of built-in types called primitive data types.The following table lists the most commonly used primitive data types in C, and the ranges of set that you can store in them. 25 SREEKANTH C STEP BY STEP Data type int Description Size (bits) * carry sample usage Whole numbers 32 int count count = 42 long Whole numbers (bigger range) 64 float Floating-point numbers 32 231 through 2311 263 through 2631 3. 4 ? 1038 double Double accurate) numbers quantitative Monetary values 128 string Sequence of characters 16 bits per Not relevant character char whiz character 16 bool Boolean 8 precision (more 64 floating-point 1. 7 ? 10308 28 significant igures long wait wait = 42L float away away = 0. 42F double trouble trouble = 0. 42 decimal coin coin = 0. 42M string put vest = 42 char grillwork grill = 4 0 through 216 1 bool teeth true or glum teeth delusive = *The value of 216 is 32,768 the value of 231 is 2,147,483,648 and the value of 263 is 9,223,372,036,854,775,808. Unassigned Local V ariables When you declare a variable, it contains a random value until you assign a value to it. This deportment was a rich source of bugs in C and C++ programs that created a variable and used it as a source of information before giving it a value.C does not allow you to use an unassigned variable. You must assign a value to a variable before you can use it, otherwise your program will not compile. This requirement is called the Definite subsidization Rule. For example, the following statements will generate a compile-time error because age is unassigned int age Console. WriteLine(age) // compile time error Displaying Primitive Data Type determine In the following exercise, youll use a C program named PrimitiveDataTypes to demonstrate how several primitive data types work. Display primitive data type values 26SREEKANTH C STEP BY STEP 1. Start Visual Studio 2005. 2. On the File menu, point to opened, and then click Project/Solution. The Open Project dialog box appears. 3. Move t o the Microsoft PressVisual CSharp Step by StepChapter 2PrimitiveDataTypes folder in your My Documents folder. Select the file PrimitiveDataTypes. sln and then click Open. The solution loads, and the PrimitiveDataTypes project. Solution Explorer displays the solution and NOTE Solution file names have the . sln suffix, such as PrimitiveDataTypes. sln. A solution can contain one or more projects.Project files have the . csproj suffix. If you open a project rather than a solution, Visual Studio 2005 will automatically create a new solution file for it. If you build the solution, Visual Studio 2005 automatically saves any updated or new files, and you will be prompted to provide a name and location for the new solution file. 4. On the Debug menu, click Start Without Debugging. The following application window appears 5. In the Choose A Data type list, click the string type. The value 42 appears in the Sample value box. 6. Click the int type in the list.The value to do appears in the Sam ple value box, indicating that the statements to display an int value still need to be written. 27 SREEKANTH C STEP BY STEP 7. Click each data type in the list. Confirm that the code for the double and bool types also needs to be completed. 8. Click bar closing the window and stopping the program. Control returns to the Visual Studio 2005 programming environment. Use primitive data types in code 1. Right-click the Form1. cs file in the Solution Explorer and then click View Code. The Code and Text Editor window opens displaying the Form1. cs file. 2.In the Code and Text Editor window, find the show Float Value method listed here private void showFloatValue() float var var = 0. 42F value. Text = 0. 42F TIP To locate an item in your project, point to harness And Replace on the Edit menu and click Quick Find. A dialog box opens asking what you want to research for. Type the name of the item youre flavor for, and then click Find Next. By default, the search is not case-sensitive. I f you want to perform a case-sensitive search, click the + button next to the Find Options label to display additional options, and check the Match Case check box.If you have time, you can experiment with the other options as well. You can also press Ctrl+F (press the Control key, and then press F) to display the Quick Find dialog box rather then usin g the Edit menu. Similarly, you can press Ctrl+H to display the Quick Find and Replace dialog box. The showFloatValue method runs when you click the float type in the list box. This method contains three statements The first statement declares a variable named var of type float. The secant statement assigns var the value 0. 42F. (The F is a type suffix specifying that 0. 2 should be treated as a float value. If you forget the F, the value 0. 42 will be treated as a double, and your program will not compile because you cannot assign a value of one type to a variable of a different type in this way. ) The third statement displays the va lue of this variable in the value TextBox on the form. This statement requires a little bit of your attention. The way in which you display an item in a TextBox is to set its Text property. You did this at 28 SREEKANTH C STEP BY STEP design time in Chapter 1 using the Properties window. This statement shows ou how to perform the same task programmatically, using the formula value. Text. The data that you put in the Text property must be a string (a sequence of characters), and not a number. If you try and assign a number to the Text property your program will not compile. For this reason, the statement simply displays the text 0. 42F in the TextBox (anything in double-quotes is text, otherwise known as a string). In a real-world application, you would add statements that convert the value of the variable var into a string and then put this into the Text property, but you need to know a little bit more about C and the .NET Framework before we can do that (we will cover data type pa ssages in Chapter 11, Understanding Parameter Arrays, and Chapter 19, Operator Overloading). 3. In the Code and Text Editor window, locate the showIntValue method listed here private void showIntValue() value. Text = to do The showIntValue method is called when you click the int type in the list box. TIP Another way to find a method in the Code and Text Editor window is to click the Members list that appears above the window, to the right. This window displays a list of all the methods (and other items).You can click the name of a member, and you will be taken directly to it in the Code and Text Editor window. 4. Type the following two statements at the start of the showIntValue method, after the open curly brace int var var = 42 The showIntValue method should now look like this private void showIntValue() int var var = 42 value. Text = to do 5. On the Build menu, click Build Solution. a. The build will display some warnings, but no errors. You can ignore the warnings for now. 6 . In the original statement, change the string to do to 42. b. The method should now look exactly like this 9 SREEKANTH C STEP BY STEP c. private void showIntValue() d. i. int var ii. var = 42 iii. value. Text = 42 e. 7. On the Debug menu, click Start Without Debugging. f. The form appears again. g. TIP If you have edit the source code since the last build, the Start Without Debugging command automatically rebuilds the program before starting the application. 8. Select the int type in the list box. Confirm that the value 42 is displayed in the Sample value text box. 9. Click Quit to close the window and stop the program. 10. In the Code and Text Editor window, find the showDoubleValue method. 1. Edit the showDoubleValue method exactly as follows private void showDoubleValue() double var var = 0. 42 value. Text = 0. 42 12. In the Code and Text Editor window, locate the showBoolValue method. 13. Edit the showBoolValue method exactly as follows private void showBoolValue() bool v ar var = false value. Text = false 14. On the Debug menu, click Start Without Debugging. The form appears. 15. In the list, select the int, double, and bool types. In each case, tramp that the correct value is displayed in the Sample value text box. 16. Click Quit to stop the program.Using Arithmetic Operators C supports the regular arithmetic operations you learned in your childhood the plus sign (+) for addition, the minus sign () for subtraction, the asterisk (*) for multiplication, and the forward slash (/) for division. These symbols (+, , *, and /) are called operators as they operate on values to create new values. In the following 30 SREEKANTH C STEP BY STEP example, the variable moneyPaidToConsultant ends up holding the product of 750 (the daily rate) and 20 (the number of days the consultant was employed) long moneyPaidToConsultant oneyPaidToConsultant = 750 * 20 NOTE The values that an operator operates on are called operands. In the carriage 750 * 20, the * is the ope rator, and 750 and 20 are the operands. Determining an Operators Values Not all operators are applicable to all data types, so whether you can use an operator on a value depends on the values type. For example, you can use all the arithmetic operators on values of type char, int, long, float, double, or decimal. However, with one exception, you cant use the arithmetic operators on values of type string or bool.So the following statement is not allowed because the string type does not support the minus operator (subtracting one string from another would be meaningless) // compile time error Console. WriteLine(Gillingham Manchester City) The exception is that the + operator can be used to concatenate string values. The following statement writes 431 (not 44) to the console Console. WriteLine(43 + 1) TIP You can use the method Int32. analyse to convert a string value to an integer if you need to perform arithmetic computations on values held as strings.You should also be aware that t he type of the result of an arithmetic operation depends on the type of the operands used. For example, the value of the facial gesture 5. 0 / 2. 0 is 2. 5 the type of both operands is double (in C, literal numbers with decimal points are always double, not float, in order to maintain as much accuracy as possible), and so the type of the result is also double. However, the value of the expression 5 / 2 is 2. In this case, the type of both operands is int, and so the type of the result is also int. C always rounds values down in circumstances like this.The situation gets a little more complicated if you mix the types of the operands. For example, the expression 5 / 2. 0 consists of an int and a double. The C compiler detects the mismatch and generates code that converts the int into a double before performing the operation. The result of the operation is therefore a double (2. 5). However, although this works, it is considered unforesightful practice to mix types in this way. C als o supports one less-familiar arithmetic operator the symmetry, or modulus, operator, which is represented by the per centum symbol (%). The result of x % y is the remainder after dividing x by y.For example, 9 % 2 is 1 since 9 divided by 2 is 8, remainder 1. NOTE In C and C++, you cant use the % operator on floating-point values, but you can use it in C. Examining Arithmetic Operators 31 SREEKANTH C STEP BY STEP The following exercise demonstrates how to use the arithmetic operators on int values using a previously written C program named MathsOperators. Work with arithmetic operators 1. On the File menu, point to Open, and then click Project/Solution. Open the MathsOperators project, regain in the Microsoft PressVisual CSharp Step by StepChapter 2MathsOperators folder in your My Documents folder. . On the Debug menu, click Start Without Debugging. A form appears on the screen. 3. Type 54 in the left operand text box. 4. Type 13 in the right operand text box. You can now apply an y of the operators to the values in the text boxes. 5. Click the Subtraction option, and then click Calculate. The text in the Expression box changes to 54 13, and 41 appears in the Result box, as shown in the following graphic 6. Click the / Division option, and then click Calculate. The text in the Expression text box changes to 54 / 13, and the number 4 appears in the Result box. In real life, 54 / 13 is 4. 53846 recurring, but this is not real life this is C In C, when you divide one integer by another integer, the result you get back is an integer, as explained earlier. 32 SREEKANTH C STEP BY STEP 7. Select the % Remainder option, and then click Calculate. The text in the Expression text box changes to 54 % 13, and the number 2 appears in the Result box. This is because the remainder after dividing 54 by 13 is 2 (54 ((54 / 13) * 13) is 2 if you do the arithmetic rounding down to an integer at each stagemy old maths get the hang at school would be horrified to be told that (54 / 13) * 13 does not equal 54 . 8. Practice with other combinations of numbers and operators. When youre finished, click Quit. The program stops, and you return to the Visual Studio 2005 programming environment. Now take a look at the MathsOperators program code. Examine the MathsOperators program code 1. Display the Form1 form in the Design View window (click the Form1. csDesign tab if necessary). TIP You can quickly switch between the Design View window and the Code and Text Editor displaying the code for a form by pressing the F7 key. 2. In the View menu, point to Other Windows and then click Document scheme.The Document Outline window appears showing the names and types of the controls on the form. If you click each of the controls on the form, the name of the control is highlighted in the Document Outline window. 33 SREEKANTH C STEP BY STEP IMPORTANT Be careful not to accidentally delete or change the names of any controls on the form while viewing them in the Document Outl ine window. The application will no longer work if you do. 3. Click the the two TextBox controls that the user types numbers into on the form. In the Document Outline window, verify that they are named lhsOperand and rhsOperand.When the form runs, the Text property of each of these controls holds (as strings) the numeric values you enter. 4. Towards the bottom of the form, verify that the TextBox control used to display the expression being evaluated is named expression, and that the TextBox control used to display the result of the calculation is named result. At runtime, background the Text property of a TextBox control to a string value causes that value to be displayed. 5. Close the Document Outline window. 6. Press F7 to display the Form1. cs source file in the Code and Text Editor window. 7.In the Code and Text Editor window, locate the subtractValues method private void subtractValues() int lhs = int. Parse(lhsOperand. Text) int rhs = int. Parse(rhsOperand. Text) int outcom e outcome = lhs rhs expression. Text = lhsOperand. Text + + rhsOperand. Text result. Text = outcome. ToString() The first statement in this method declares an int variable called lhs and initializes it to the result of the explicit conversion of the lhsOperand. Text property to an int. (The Text property of a TextBox is a string, and must be converted to an integer before you can store it in an int. This is what the int.Parse method does) The second statement declares an int variable called rhs and initializes it to the result of the explicit conversion of the rhsOperand. Text property to an int. The third statement declares an int variable called outcome. The fourth statement subtracts the value of the rhs variable from the value of the lhs variable, and the result is assigned to outcome. The 5th statement concatenates three strings (using the + operator) and assigns the result to the expression. Text property. The sixth statement converts the int value of outcome to a string by using the ToString method, and assigns the string to the result.Text property. 34 SREEKANTH C STEP BY STEP The Text Property and the ToString Method I mentioned earlier that TextBox controls displayed on a form have a Text property that allows you to access the displayed contents. For example, the expression result. Text refers to the contents of the result text box on the form. Text boxes also have many other properties, such as the location and size of the text box on the form. You will learn more about properties in Chapter 14, Implementing Properties to Access Attributes. Every class has a ToString method.The purpose of ToString is to convert an object into its string representation. In the previous example, the ToString method of the integer object, outcome, is used to convert the integer value of outcome into the equivalent string value. This conversion is necessary because the value is displayed in the Text property of the result fieldthe Text property can only contain s trings. When you Controlling Precedence Precedence governs the order in which an expressions operators are evaluated. Consider the following expression, which uses the + and * operators 2+3*4This expression is potentially ambiguous does 3 bind to the + operator on its le

No comments:

Post a Comment