Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Beginning Object-Oriented Programming with C#
Beginning Object-Oriented Programming with C#
Beginning Object-Oriented Programming with C#
Ebook1,076 pages10 hours

Beginning Object-Oriented Programming with C#

Rating: 0 out of 5 stars

()

Read preview

About this ebook

The ideal beginner's guide to C# and object-oriented programming

Wrox beginners' guides have the perfect formula for getting programming newcomers up and running. This one introduces beginners to object-oriented programming using C# to demonstrate all of the core constructs of this programming framework. Using real-world situations, you'll discover how to create, test, and deliver your programs and how to work with classes, arrays, collections, and all the elements of object-oriented programming.

  • Covers exactly what beginners, even those with no prior programming experience, need to know to understand object-oriented programming and start writing programs in C#
  • Explains the advantages and disadvantages of C#, and tips for understanding C# syntax
  • Explores properties, encapsulation, and classes; value data types; operands and operators; errors and debugging; variables; and reference types
  • Shows how to use statement repetition and program loops, understand arrays and collections, and write your own classes
  • Also covers inheritance and polymorphism

Beginning Object-Oriented Programming with C# uses the tried-and-true Wrox formula for making this popular programming method easy to learn.

LanguageEnglish
PublisherWiley
Release dateNov 5, 2012
ISBN9781118416471
Beginning Object-Oriented Programming with C#

Read more from Jack Purdum

Related to Beginning Object-Oriented Programming with C#

Related ebooks

Programming For You

View More

Related articles

Reviews for Beginning Object-Oriented Programming with C#

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Beginning Object-Oriented Programming with C# - Jack Purdum

    Part I

    Getting Started

    Chapter 1: Introducing C#

    Chapter 2: Understanding Objects

    Chapter 1

    Introducing C#

    What you will learn in this chapter:

    How to download Visual Studio

    How to install Visual Studio Professional

    How to create a simple project

    How to develop a small program in Visual Studio

    Some features found in the Visual Studio IDE

    Running a Visual Studio program

    Welcome to the world of object-oriented programming and C#! The primary goal of this book is to use the C# programming language from Microsoft to teach you object-oriented programming, or OOP. This book assumes that you have no prior programming experience in any language and that you know nothing about OOP. As such, this book must be viewed as a beginning text.

    If you do have programming experience and some familiarity with OOP, that's fine. Having that experience makes things easier for you. However, I still encourage you to read the book from start to finish for a number of reasons. First, this book represents the distillation of 25 years of programming and teaching experience. I have a good idea of what works and what doesn't work to explaining complex topics so that they're easy to understand. Reading each chapter gives you the tools to understand the next chapter. Second, I may introduce topics in one chapter and then rely heavily on those topics in a much later chapter. In other words, the process used to learn OOP and C# is one that introduces new topics based upon ones that were introduced earlier. Obviously, you must master the earlier content before tackling the later content. Finally, the programming examples I use also build on concepts presented in earlier program examples. It will be easier for you to understand the later program examples if you've experimented with those programs introduced earlier in the book.

    One more thing: You cannot learn programming by just reading about it. You have to dig in and start programming. For that reason, there are exercises at the end of each chapter designed to help you hone your programming skills. The learning process is even more interesting if you try to create your own programs based upon some real problems you'd like to solve. Don't worry if things don't fall together instantly on the first try. You should plan to make a ton of flat-forehead mistakes…you know, the kind of mistake in which, upon discovering it, you pound the heel of your hand into your forehead and say, How could I make such a stupid mistake! Not to worry…we've all been there. Such mistakes are just part of the process to become a programmer, and you should expect to make your fair share. However, stick with it, read the book, and you'll be surprised at how fast things can come together. Indeed, I think you'll find programming to be a truly enjoyable pastime.

    A Short History of Object-Oriented Programming (OOP)

    Many people believe that OOP is a product of the 1980s and the work done by Bjarne Stroustrup in moving the C language into the object-oriented world by creating the C++ language. Actually, SIMULA 1 (1962) and Simula 67 (1967) are the two earliest object-oriented languages. The work on the Simula languages was done by Ole-John Dahl and Kristen Nygaard at the Norwegian Computing Center in Oslo, Norway. Although most of the advantages of OOP were available in the earlier Simula languages, it wasn't until C++ became entrenched in the 1990s that OOP began to flourish.

    C was the parent language of C++ and it was often said that C was powerful enough to shoot yourself in the foot multiple times. C++, on the other hand, not only was powerful enough to shoot yourself in the foot, but also you could blow your entire leg off without too much difficulty. Most programmers admit that C++ is a powerful language and it is still in widespread use today. However, with that power comes a lot of complexity. Language developers wanted a simpler and perhaps less complex language for OOP development.

    The next step in the development of OOP started in January 1991 when James Gosling, Bill Joy, Patrick Naughton, Mike Sheradin, and several others met in Aspen, Colorado, to discuss ideas for the Stealth Project. The group wanted to develop intelligent electronic devices capable of being centrally controlled and programmed from a handheld device. They decided that OOP was the right direction to go with the development language but felt that C++ was not up to the job. The result was the Oak programming language (named after an oak tree outside Gosling's window), which eventually morphed into the Java programming language. (Oak had to be renamed because the team discovered that a language by that name already existed.)

    Java quickly grew in popularity, spurred by the growth of the World Wide Web. In both cases this rapid growth was in part because the guts necessary to run Java programs on the web quickly became an integral part of various web browsers. With the improved web functionality augmented by Java, the web hit light speed.

    To many programmers, C# is Microsoft's answer to Java. Some would even say that C# is the result of Microsoft's stubbornness to refuse to promote a language it did not develop. That sentiment is a bit too harsh. Microsoft had good reasons for developing C#, not the least of which was that it wanted type-safe programs that run in a managed environment. You may not appreciate exactly what that means right now, but it will become clear as you learn C#.

    C# provides you with a robust object-oriented programming language and an impressive set of tools to tackle almost any programming task. Whether you want to develop desktop, distributed, web, or mobile applications, C# can handle the task.

    As you become familiar with C#, you can appreciate its relatively few keywords, its crisp syntax, and its easy-to-use development environment. You'll discover that pieces of programs you write in C# can be reused in other programs. Finally, you might appreciate that there are many job opportunities for programmers who know C#.

    Installing C#

    If you have already purchased and installed Visual Studio 2012 and C#, you can skip this section. If you haven't installed C#, this section tells you how to download and install the Visual Studio version of Visual Studio. Visual Studio is a modified version of C# that is available from Microsoft at no charge. Although the Express version of C# is missing some features found in the commercial version of Visual Studio, you should compile and run all the sample programs in this book using Visual Studio.

    At the present time, the Express version of Visual Studio requires the use of Windows 8. If you do not have Windows 8, you can download a trial version of Visual Studio Professional. By registering the trial version, you can use Visual Studio Professional for a period of 90 days. After you are convinced that you should do all your development work in C# (and you will be), you can purchase the full version of Visual Studio. Of course, if you later purchase Windows 8, you can always download the Express version of Visual Studio.

    Due to the newness of Windows 8, you probably are not using Windows 8 and, hence, must use the trial version of Visual Studio Professional. The next section discusses how to download the trial version of Visual Studio Professional.

    Downloading Visual Studio Professional

    At the time that this book is written, you can go to professionalhttp://http://www.microsoft.com/visualstudio/11/en-us/downloads#professional to download the Professional version of Visual Studio. The download page should look similar to what is shown in Figure 1.1. As you can see if you look closely at the figure, the download is for the 90-day trial version of Visual Studio Professional. Click the Install Now button to begin the installation process.

    Figure 1.1 Download page for Visual Studio Professional

    1.1

    Depending upon the speed of your system and Internet connection, it can take more than 1 hour to download and install the 6+ gigabytes of files used during the installation process. You must first agree to the licensing terms, as shown in Figure 1.2.

    Figure 1.2 License terms dialog

    1.2

    After you agree to the licensing terms, the program displays a dialog box that tells you the items that are about to be installed. Unless you are constrained by disk space, you should leave all the options checked so that they are all installed. Otherwise, you can uncheck those options that you do not want installed. See Figure 1.3.

    Figure 1.3 Installation items checklist

    1.3

    Having made your selections, click the Install button to initiate the installation process. Your display will look similar to Figure 1.4…for a long time.

    Figure 1.4 Installation process

    1.4

    Note

    While I was working through the installation process, the install software sensed that some of the Windows software on my system was outdated. I was asked if I wanted to install the updates and patches that had come out since I last updated my system. Because the list also included several patches to Visual Studio, I said yes. It took almost 2 hours to download and update my software. However, when the updates were finished, the Visual Studio installer picked up right where it had left off and the installation continued without a hitch. Although it does take some time, you should update your software if the installer offers you that option.

    Eventually, the installation process ends…honest! If you updated your system software as part of the installation process, the installer asks you at some point if you want to restart your computer. Answer yes if you are asked. After the system restarts and the software has been installed, you should see a new icon on your desktop labeled Visual Studio. You should double-click the new icon and launch Visual Studio.

    A Test Program Using C#

    Although things may appear to have been installed properly, you can't be certain until you actually write a program and try to run it. That's the purpose of this section of the chapter. The program is about as simple as you can make a program while remaining confident that the installation was successful.

    After you double-click the Visual Studio icon on your desktop, you should see a Visual Studio startup screen similar to the one shown in Figure 1.5.

    Figure 1.5 The Visual Studio IDE

    1.5

    Creating a Project

    Move the cursor to the upper-left side of the screen, and select the File → New → Project menu option from the main program menu bar, as shown in Figure 1.6.

    Figure 1.6 Creating a new project

    1.6

    Select New Project from the menu. Your program screen changes, as shown in Figure 1.7.

    Figure 1.7 New Project dialog

    1.7

    Figure 1.7 shows a number of predefined project templates from which to choose. Make sure you have selected the Templates Visual C# Windows menu option that appears on the left side of the screen. These templates define the types of programs that you can develop with C#. For your purposes, you want to select the Windows Forms Application template.

    When you select one of the templates, Visual Studio creates that type of project for you as well as writing some stub code for you. Stub codes are predefined pieces of code that Visual Studio writes for you as a background process. From the templates shown in Figure 1.7, select the Windows Forms Application template. You should also type in the name you want the program to have. I have typed in TemplateProgram for the example and designated the project to be placed in the C:\Temp\ directory. You can use the Browse button to select some other directory, or you can check the Create Directory for solution and let Visual Studio create a directory for you. Click OK after you enter the program name you want to use.

    The C# Integrated Development Environment

    You should now see something like Figure 1.8 on your screen, which shows you where you'll be spending a lot of your programming time as you read this book. It's called the Integrated Development Environment, or IDE, because virtually every programming tool you need to write C# programs is available to you there.

    Figure 1.8 The Visual Studio IDE

    1.8

    Back in the Dark Ages of programming, you had to load and run a programming editor to write the program's source code. Next, you had to close the editor and load the language compiler program to check the program's statements for errors. Then you had to load an assembler program to convert the source code to assembly language. Finally, you had to load and run a linker program to combine all the elements of your program into an executable program. The Visual Studio IDE provides all these functions within a single program. This makes it much easier to write and test the programs you create.

    The Major IDE Windows

    The IDE shown in Figure 1.8 divides the screen into three windows. The left window shows the Visual Studio Toolbox, which, by default, shows some of the objects Visual Studio makes available to you. If you look closely you can see that the Toolbox presents a smorgasbord of objects you can use in your programs, including textboxes, labels, buttons, and other controls you will find useful as you develop your programs.

    The middle window is referred to as the Source window and currently shows an unadorned Visual Studio form object. (Microsoft refers to the window as the Forms Designer window.) As presented in Figure 1.8, the form has no other objects placed on it…yet. That is, you haven't added any other objects (such as textboxes or buttons) from the Toolbox onto the form. You change this in the section Adding a Toolbox Object to a Windows Form later in this chapter.

    The right side of the IDE currently shows two subwindows. The subwindow on top shows the Solution Explorer. Simply stated, the Solution Explorer shows the current development state of your project. It shows the forms the program has and its references, plus other information that is discussed in later chapters.

    Below the Solution Explorer window is the Properties window. The purpose of the Properties window is to show you the properties associated with the object currently in focus in the Source window. If you look closely at the form in the Source window in Figure 1.8, you'll notice that it has a couple of small white boxes along its edge. These are called sizing boxes and their purpose is to enable you to alter the size of the objects to which they are attached. However, the sizing boxes also show which object in the Source window currently has the attention, or focus, of Visual Studio. Whatever object has the focus in the Source window is also the object that the Properties window displays. In Figure 1.8 the properties shown in the Properties window apply to the form shown in the Source window. Visual Studio always maintains this relationship between the object in focus in the Source window and the information displayed in the Properties window.

    Using the Source Code Window

    If you right-click Form1.cs in the Solution Explorer window, a small menu opens up from which you can select to view the source code for the file you just right-clicked. You can move to the Solution Explorer menu bar and click the source code icon to view the code that Visual Studio has written for you thus far. As you can see in Figure 1.9, you can also use the F7 key to view the source code for the file.

    Figure 1.9 Right-clicking the form filename

    1.9

    The code associated with right-clicking the filename shown in Figure 1.9 is presented in Figure 1.10. Notice that another tab has been added at the top of the Source window. One tab has Form1.cs [Design] on it, whereas the other tab has Form1.cs. The first tab is the source code mode and shows you the code for the program under development. Even though you haven't written any code, Visual Studio has already written some program code for you behind your back! You can see the TemplateProgram C# source code in Figure 1.10. The second tab is for the view of the form in the design mode. (The design mode was shown earlier in Figure 1.8.)

    Figure 1.10 Source code for file

    1.10

    It's not necessary that you understand the code shown in Figure 1.10 at this time. All you're trying to do at this point is to write a short program to see if the installation was done correctly. However, you will be spending a lot of time in the source code window as you write your own programs.

    Adding a Toolbox Object to a Windows Form

    A form with nothing on it isn't interesting. Now change the form so that, when the program runs, it displays the message, My First Program. You need to add a label to the form object shown in the Source window in Figure 1.8 to hold your program message. There are two ways to add a label object to a form. First, as shown in Figure 1.11, you can click the label object in the Toolbox, and while holding the left mouse button down, drag the label over to the form and release the mouse button. Second, you can simply double-click the label object in the Toolbox. The mouse double-click causes Visual Studio to place a label object near the upper-left corner of the form shown in the Source window.

    Figure 1.11 Adding a label object to a form

    1.11

    You should try both methods to place a label on the form. After you see that both actions do place a label on the form, click one of the labels to move Visual Studio's focus to the label you just clicked. You know this is true because you see the sizing boxes on the label you just clicked. Because you need only one label in this test program, press the Delete key on your keyboard. The label is then removed from the form.

    You can click the label in the Source window while holding the left mouse button down and drag the label to wherever you want it to appear on the form object. When you have positioned the label object where you want it on the form, simply release the mouse button.

    Changing the Text of a Label Object

    After you position the label object on the form, you can set the text for the label. One of the things that Visual Studio does automatically is size the label to be just big enough to accommodate the label's text. Given the default font size used by Visual Studio, the default height for a label is 13 pixels. (A pixel is one dot, or point of light, on the screen of your display device.) If you change the font size of the label object, the height of the label is automatically adjusted for you.

    Actually, I am not a big fan of automatic sizing of labels. For that reason, I turn off the auto-sizing feature. To turn off auto-sizing, go to the Properties Window on the lower-right side of the display and change the AutoSize property from True, as shown in Figure 1.12, to False. You may need to scroll the Property window to see the AutoSize property displayed in the Properties window. Click the down arrow at the right end of the AutoSize textbox to display the choices you have for the property. In this case you can choose only True or False. Select False. The auto-sizing of the label object is now turned off.

    Figure 1.12 Changing the AutoSize property

    1.12

    After you set AutoSize to False, you can resize the label object in the Source window by clicking the white sizing boxes that appear on the ends and corners of the label object. You can increase the width of the label by clicking the middle sizing box on the right edge of the label object and dragging the edge to the right until you get the wanted size. Then released the left mouse button to end up with the label object, as shown in Figure 1.13.

    Figure 1.13 Resizing the label object

    1.13

    After you have set the size of the label object, you can change the text property of the label object to whatever you want to appear in the label. In your example, you want the text My first program. At the present time, the text property of the label object is label1, which is not what you want. Scroll the contents of the Property window down to the Text property for the label object, change it to My first program, and press the Enter key. (If the property window should ever disappear for some reason, press the F4 key to recall it.) Changing the Text property for the label object is shown in Figure 1.14. Notice how the first line below the Property window's title bar shows the name of the object currently in focus in the Source window (label1 in Figure 1.13).

    Figure 1.14 Changing the Text property of the label object

    1.14

    By default, the text of a label object is positioned so that it appears in the upper-left corner of the label. If AutoSize is set to True, you can't position the text with the label object; it's set for you automatically. However, because you turned off auto-sizing, you can position the text within the label wherever you want. Figure 1.15 shows how to do this using the TextAlign property in the Properties window. If you look closely at Figure 1.15, you can see that TextAlign is currently set to TopLeft. There are nine positions where you can place the text in a label that you can resize. You want to right-justify your text in the center of the label object. If you look where the cursor is positioned in Figure 1.15, clicking that box right-justifies the text in the label object.

    Figure 1.15 Changing the TextAlign property for the label object

    1.15

    Running the Program

    This is all that you want to do at the present time to test your C# installation. If you can run the program at this point, you have probably installed C# correctly. There are two simple ways to run a program. The easiest is to press the F5 key. If you do that, the program should appear on the screen in a few moments with your message centered in the label object.

    The second way is to click the Run Program icon. If you look carefully at Figure 1.11, below the DEBUG menu option near the top of the form you can see a small triangle followed by the word Start. (On your screen, the triangle appears green.) Click that green triangle and the program begins execution.

    If your program does not run correctly and you're not getting an error message from within Visual Studio, go back to the start of the installation process and check to make sure you followed each step correctly. Before you start the reinstall, make sure that you have enough free disk space to hold Visual Studio. If you get an error message from Visual Studio, you performed some step in the coding process incorrectly. Just go back to the beginning of the A Test Program Using Visual Studio section of this chapter to check each step to ensure you followed the correct sequence.

    Summary

    In this chapter you learned how object-oriented programming started more than four decades ago. This chapter also showed you how to download and install Visual Studio's Professional edition. Finally, you wrote a simple program to test the installation to make sure it was done correctly. So, now what?

    You could immediately proceed to the next chapter and start reading. Not a good idea. Now that you have a simple program up and running, this is the perfect time to experiment a little. For example, your program doesn't have any text in the program's title bar. Surely C# provides a property that enables you to change the title bar. (Hint: It does provide such a property!) Play around with some of the other properties to see what they do. For example, change the foreground property and see what happens.

    Looking forward, at the end of each chapter in this book are set of exercises that you should do before reading the subsequent chapter. You will probably be eager to move to the next chapter, but resist the temptation to skip the exercises—be sure to do them. They can help crystallize what you've learned in the current chapter and better prepare you for the content of the next chapter. You can find the solutions to all the exercises in Appendix A.

    Programming should be fun, and some of that fun comes from discovering what happens if you change this to that. If you see smoke coming out of your computer, don't make that change again. (Just kidding…you can't hurt your computer if you make an incorrect change to a property.) Experiment and have fun!

    What You Learned in This Chapter

    Chapter 2

    Understanding Objects

    What you will learn in this chapter:

    What an object is

    What the term state means to objects

    What a class is

    What it means to instantiate an object

    What properties are

    What methods are

    How to use objects provided by Visual Studio .NET

    wrox.com code downloads for this chapter

    You can find the wrox.com code downloads for this chapter at www.wrox.com/remtitle.cgi?isbn=9781118336922 on the Download Code tab. The code in the Chapter02 folder is individually named as shown in this chapter.

    The concepts introduced in this chapter lay the ground work for understanding object-oriented programming (OOP). Before you move on to Chapter 3 you should feel comfortable with the concepts introduced here. You should end this chapter feeling that you understand what objects, properties, and methods are and how they are used in an OOP program. If any of these concepts seem fuzzy after your first reading of this material, read the chapter again.

    If any topic presented in this book still seems unclear after two or more passes through the chapter, you should log on to the Wrox website for this book and ask a question about the subject that is giving you trouble. If it's unclear to you, chances are it may be unclear to others. Wrox expends a lot of effort to make that web resource available to you, so use it whenever you feel unclear on some issue or topic.

    Understanding Objects

    As you learned in Chapter 1, programming with objects has been around for more than four decades. However, it's only in the last 20 years that object-oriented programming has become the norm rather than the exception. This chapter presents a simple example of how you can use objects in an everyday situation. You then expand on the concepts presented in that example to an actual program you build using Visual Studio .NET and the objects it provides.

    Suppose you are the personnel manager for a company and you need to hire someone to fill an important position. After sifting through dozens of résumés, you select one candidate to call to arrange for a face-to-face interview at your company offices. You call her (let's say her name is Jane) on the phone and chat for a few minutes to confirm that she appears to be the right person for the job. You (pretend your name is Jack) make arrangements for Jane to fly to your location, stating that you will meet her at the airport, as shown in Figure 2.1.

    Figure 2.1: Arranging a job interview

    2.1

    However, because the two of you have never met before, you start asking a few questions so that you can recognize each other at the airport. Jane says she's medium height with blonde hair and that she will be wearing a black business suit and carrying a tan leather briefcase. You then describe yourself as 6 feet tall with sandy hair and say that you'll be wearing a gray suit. You then set a date and time for the flight, and everything's ready for the interview.

    Everyday Use of Objects

    Perhaps without realizing it, both of you used objects in the course of your conversation. First, without thinking about it, you implicitly created a person class during the phone call. A class is a template used to describe an object. As such, a class is an abstraction, or simplification, of some object you observe in the real world. You can break a class down into two basic components:

    Properties that describe the object

    Methods, or actions, that you want to associate with the object

    Class Properties

    The class properties are the data that you want to associate and record with an object. If you want to create a class person object (referred to as clsPerson), a list of properties might include those shown in Table 2.1.

    Table 2.1 clsPerson Properties

    Although not a rule, many programmers use variable names for properties that start with a lowercase letter but use uppercase letters at the start of any words contained within the property name. Because you may want to follow this convention, too, the property names in Table 2.1 follow this convention.

    Prior to the phone conversation, the list of properties for the clsPerson named Jane is virtually empty. All you could fill in from her résumé were her name and gender. However, after the phone conversation you filled in almost all the properties for the clsPerson object named Jane. (You might scare her away if you tried to fill in the Build and eyeColor properties over the phone or face a lawsuit.)

    While you were filling in a clsPerson object named Jane, she was doing the same thing for a clsPerson object named Jack. Prior to the phone call, the clsPerson object Jane created to be associated with the name Jack may have been totally empty because Jane had no idea who might be calling her about a job interview. However, the dialog on the phone enabled each party to fill in at least some of the property values for the other person. From Jane's point of view, her clsPerson object went from a totally nondescript object to (at least) a partially identifiable object after the phone call was completed.

    By changing the values of the class properties, you can change the state of the object. The state of an object is determined by the values of the properties used to describe the object. In the example, the properties used to describe the state of a clsPerson object are those shown in Table 2.1. Prior to the phone call, there are no meaningful values for the properties shown in Table 2.1.

    Although people don't change their names often, it happens occasionally. Likewise, people do gain and lose weight, dye their hair, wear tinted contacts, change clothes, and alter their accessories. If any of these property values change, the state of the object also changes. Just keep in mind that anytime the value of a property changes, the state of the objectby definitionalso changes.

    It should also be obvious that it is the value of the properties that enable someone to distinguish a Jane clsPerson object from a Jack clsPerson object. That is, different objects usually have different values for their properties. It also follows, therefore, that different objects have different states.

    Class Methods

    Just as there are property values that define the state of an object, there are usually class methods that act on the properties. For a clsPerson object, you would want that object to talk, wave her arms, walk, change clothes, and so forth. In short, the class methods determine the behaviors or actions the object can perform. Methods are used to describe whatever actions you want to associate with the object. Class methods often are used to manipulate the data contained within the object.

    You can depict the phone conversation between Jane and Jack as objects of the person class, as shown in Figure 2.2.

    Figure 2.2: Filling in property values during the phone conversation

    2.2

    Often, class methods are used to take one or more property values, process the data those properties contain, and create a new piece of data as a by-product of the method's process. For example, you might develop a business application and need to create an invoice object that has priceEach and quantityOrdered (among others) as properties of an clsInvoice class. You might then create a method named salesTaxDue() as a class method that computes the sales tax due for the invoice. You might have another clsInvoice property named salesTax that is filled in automatically as part of the code contained in the method named salesTaxDue().

    If you think about it, a class property may be viewed as a noun: a person, place, or thing used to describe an object. Class methods, on the other hand, often behave like verbs, denoting some kind of action to be taken on the class properties (that is, the data in the class) or an action the object can perform.

    How Many Properties, How Many Methods?

    One question that you must grapple with as a programmer is how many properties and methods you should have in a class. For example, in the clsPerson object, you could also include a photograph of the person, fingerprints, a retinal scan, blood type, a DNA sample, dental records, shoe size, plus hundreds of other things that may be part and parcel of a person object. Likewise, you can create methods to simulate talking, running, writing, walking, digestion, elimination, sleeping, dreaming, and a bunch of other actions humans can do. So where do you stop? What is the proper number of properties and methods?

    Classes Are Simplifications of Objects

    Keep in mind that for every property and method you add to a class, you must write program code to implement that property or method. As a general rule, the less code a program has, the fewer things there are to go wrong. From a programmer's perspective, writing less code is a good thing, provided the code accomplishes the task at hand. In other words, when you design a class, you need to strike a balance between minimizing the code you write and fulfilling the design goals for the class.

    Note

    The proper number of properties and methods in a class is the minimal number of properties and methods that gets the job done.

    The number of properties and methods in a person class the FBI needs to find criminals is going to be vastly different from the number of properties and methods in a person class you might create to write an address book to keep track of your friends.

    You'll also find that if you omit unnecessary details in a class, there's a greater likelihood that you can reuse that same class code in some other project. The concept of code reuse is one of the main advantages of object-oriented programming. The more generic the class is, the easier it is to reuse the class. In a sense, therefore, you might want to define your classes as the minimal abstraction necessary to describe an object in a way that fulfills your needs.

    Always keep in mind that if there is a simple way and a complex way to accomplish the same goal, simple is almost always the best choice. Some programmers get a kick out of writing clever code that no one else can understand. That's probably okay, as long as no one else has to work with their code. In a commercial setting, however, clever, obfuscated code is rarely a good thing. Given alternatives, stick with the code that is easily understood.

    What Do I Do After I've Defined a Class?

    As mentioned earlier, a class is a template for an object. In that sense, a class is like a cookie cutter that enables you to shape specific cookie objects. By this release of Visual Studio, Microsoft has buried within the .NET Framework approximately 4,000 available classes. This means you have approximately 4,000 cookie cutters already hanging on the wall ready for you to use. (You'll use some of these cookie cutters later in this chapter.) Part of your job as a fledgling programmer is to learn about those classes that already exist. After all, there's no reason for you to reinvent the wheel.

    There will be times when you will use one of these 4,000 objects but will say to yourself: If only this object had such-and-such property or had a method that could do such-and-such. OOP provides a mechanism called inheritance to do just that. However, that topic is deferred to Chapter 16. For the moment, you should concentrate on using those objects built into Visual Studio.

    Visual Studio as an IDE

    As pointed out in Chapter 1, Visual Studio is an IDE that incorporates numerous programming tools. Prior to the advent of IDEs, programmers had separate programs for writing the course code (an editor), compiling the program (a compiler), assembling the program (an assembler), and combining the program into an executable program (a linker). With an IDE, all these disparate functions are combined into a single package.

    A huge part of the functionality of Visual Studio comes from the .NET Framework, including all those cookie cutters. As you write your code, components within the IDE combine your code with elements from the .NET Framework and produce Microsoft Intermediate Language (MSIL) code. It is this MSIL code, passed through the Common Language Runtime (CLR) component of Visual Studio that actually gets your program to run.

    Rather than make the distinction between each of the pieces that comprise Visual Studio when some specific function is performed, you simply say something like: Visual Studio takes your code and does whatever is necessary to produce an executable program. If a situation arises in which the distinction is important, we will use the proper nomenclature. For now, just remember that, as an IDE, Visual Studio is composed of a lot of different components acting in concert to make your life easier.

    Most of the time you must write some of your own classes in addition to those provided for you by Visual Studio. This means that, after you finish writing your class, you now have 4,001 cookie cutters hanging on the wall, each one of which can create an object of that class's type. But note: Just because you have defined a class (or a cookie cutter) does not necessarily mean you have an object (or a cookie). Just because the cookie cutter your Mom gave you is sitting in the kitchen drawer, in and of itself, doesn't put any cookies on the table.

    As stated before, a class is just a template for the object. Just as a cookie cutter works to cut specific shapes out of cookie dough, a class is used to carve out chunks of memory used to hold objects of that class. Until you've used the class template to actually carve out an object, that object does not yet exist.

    Figure 2.3 shows the relationship between a class and the objects you can instantiate from that class. The class is shown as a diamond-shaped cookie cutter. The class is named clsDiamond. You can think of the properties of clsDiamond as holding the values that determine the exact shape of the cookie cutter. In other words, the state of the properties makes the class look like a diamond rather than some other shape (for example, a heart). To get an object of the class, you must press the cookie cutter (class template) into the cookie dough (computer memory) to get an actual cookie (object).

    Figure 2.3: Class template versus an object of the class

    2.3

    An object is also called an instance of a class. The act to use a class to define an object is called instantiation.

    An object, therefore, is something that you can actually use in a program. Just as you can't eat a cookie cutter, you can't directly use a class. You must use the class to instantiate an object of the class in memory before you can use it in your program.

    Naming Objects

    Throughout this text, I have adopted a convention under which you prefix the name of certain objects with a specific combination of letters. For example, I use cls before class names, txt before the names of text box objects, btn before button objects, and so on. You can discover other examples as you read this text. This convention is a modified form of what is called Hungarian notation but not its pure form. At the extreme, Hungarian notation prefixed every data item with its data type, such as iHatSize for an integer variable, cLetter for a character variable, fWage for a floating-point variable, objMyData for a data object, plus many other similar variations. At the extreme, some programmers also include a scope identifier, as in igHatSize, which means: an integer variable with global scope named HatSize. This notation has lost followers simply because what it brought to the table in terms of code clarity wasn't worth the effort. So why do I continue to use a modified version of Hungarian notation?

    One reason is that I feel our version is definitely worth the effort. The major reason is that the prefixes reinforce the object type used in the program. That is, at a glance you can see that txtName is a textbox object and that it's different from lblName, which is a label object.

    A second reason is the way Visual Studio looks at your program data as you type in program code. For example, if you have three textboxes in your program, all prefixed with txt, Visual Studio knows about these objects and can open up a small look-ahead window the instant it sees you type in the prefix txt. You can then select the appropriate textbox object in the window, press the Tab key, and Visual Studio fills in the rest of the object's name for you. If you didn't prefix the textbox names with txt and you couldn't recall anything about the object (even its name) other than it's a textbox object, the names would be scattered throughout the look-ahead window, thus making the look-ahead feature less useful.

    Because this look-ahead feature is a real time-saver, prefixes are used for objects in the program examples. If you don't feel it's worth the effort, you can use your own style.

    Instantiating an Object of a Class

    Consider the following statement:

    clsPerson myFriend;

    To help explain what is taking place with this statement, consider the simplified memory map of your computer system, as shown in Figure 2.4.

    Figure 2.4: Simplified Windows memory map

    2.4

    Simply stated, the program statement statement says: Go to the cookie cutter wall and look for a cookie cutter named clsPerson. When you find it, take it down from the wall, carve out a chunk of memory for it and label that chunk myFriend. The end result is that .NET asks the Windows operating system for 4 bytes of memory where it can store a reference, or memory address, for the variable named myFriend.

    Assume that the Windows Memory Manager finds 4 bytes of free storage at memory address 800,000. For the moment, you haven't done anything with the memory at this address, so its current value is null. (The word null means the variable has nothing useful currently stored in it.)

    What you have at this point is a cookie cutter named myFriend just waiting around at memory address 800,000 for something useful to happen. Things start to happen with the next program statement:

    myFriend = new clsPerson();

    Words that have special meaning in a programming language are called keywords. The new keyword in C# means that you want to set aside enough memory to hold a new clsPerson object. Further assume that it takes 2,000 bytes of memory to hold all the data associated with a clsPerson object. (.NET figures out how many bytes it needs for an object by examining the program code of the class.) If you verbalize what is happening on the right side of this programming statement, you might say, Hey, Windows! It's me…Visual Studio. My programmer wants to create a new clsPerson object. Do you have 2,000 bytes of free memory available for such an object? The Windows Memory Manager then looks through its table of available memory and probably finds 2,000 bytes of free memory somewhere in the system. Assume the 2,000-byte memory block starts at address 900,000. The Windows Memory Manager then sends a message back to Visual Studio and says, Hey, VS! It's me…the Windows Memory Manager. I found 2,000 bytes of free memory starting at address 900,000. Visual Studio says, Thanks, and proceeds to set up things to use the clsPerson object named myFriend, which now exists at memory location 900,000.

    When Visual studio finishes with the statement, the memory map now looks like the one shown in Figure 2.5.

    Figure 2.5: Memory map after object instantiation

    2.5

    Notice what happened. The value associated with the variable myFriend at memory address 800,000 has changed from null to the memory address where the data associated with the newly created myFriend object is stored. You have now carved out a clsPerson object that you can access via the variable named myFriend. The purpose of the myFriend variable is to tell you where to find the data associated with the myFriend object.

    Again, the correct programming term is that you have instantiated a clsPerson object referenced by the variable myFriend. An instantiated object is an object that you can use in your program. It should also be clear that myFriend is a reference that enables you to find the object's data (that is, the values of its properties).

    Repeating the two programming statements (Chapter 4 explains the purpose of the slashes in the following statements):

    clsPerson myFriend;        // Grab a specific cookie cutter from the wall

                              // and name it myFriend

    myFriend = new clsPerson();// Use the cookie cutter to make a clsPerson

                              // cookie and refer to it as myFriend

    The first statement means that you intend to create an object of clsPerson and refer to that object using the variable named myFriend. The second statement says you carried through with your intent and instantiated a new object of a clsPerson type and associated it with the object variable named myFriend. You reference the object's data for the remainder of the program using the variable named myFriend. Using the cookie cutter analogy, the cookie cutter (that is, the reference) is found at memory address 800,000, but the cookie itself (that is, the object's data) is found at memory address 900,000.

    You can combine the two statements into a single statement if you want:

    clsPerson myFriend = new clsPerson();

    The interpretation is exactly as before. You have simply collapsed the two statements into one. Because programmers prefer less code to more code, you will see the abbreviated form used more often.

    You must understand the difference between a class and an object of the class. When you write the code for a class, you are actually acting like an architect designing a house. The plans you craft might be used to build one house or hundreds of houses. The point is that the class code is the design to be used at some later date. Later, carpenters, plumbers, and other craftsmen actually construct the house. The craftsmen grab the blueprints (that is, the class) from the wall, read them, and then instantiate the house. The usefulness of a class (that is, a house) actually comes into being after an object of the class is instantiated (that is, the house is actually built). Although Santa indirectly appreciates what a cookie cutter does, he'd much rather see a pile of (instantiated) cookies on a plate than a stack of rusting cookie cutters.

    I Have an Object…Now What?

    You now have instantiated an object of the clsPerson type. The obvious question is, So what? At the present time, the object named myFriend is fairly nondescript. Indeed, every property in the object is instantiated with the value of zero, false, or null by default, depending upon the data type of the property. None of the information previously presented in Table 2.1 has been filled in for the myFriend object. You need to change the faceless myFriend object into one that has some meaningful information in it.

    You can change the object by changing the information contained in the properties defined within it. From Table 2.1, you might do the following:

    myFriend.name = Jane;

    myFriend.gender = F;

    myFriend.height = 66;

    myFriend.build = Petite;

    myFriend.hairColor = Blonde;

    myFriend.eyeColor = Blue;

    myFriend.clothing = Business casual;

    myFriend.accessories = Tan leather briefcase;

    Notice what these statements do. They change the faceless myFriend object into one that gives you some impression of what this particular clsPerson object looks like. In these statements, the equals sign (=) is called the assignment operator. The assignment operator takes the information in the expression on the right side of the assignment operator and copies that information into the expression on the left side of the assignment operator. This means that somewhere near memory address 900,000, the name property has been changed from null to Jane. Similar changes have occurred for the other myFriend properties. In programming terms, the assignment statements change the state of the object from a faceless, nondescript person to an attractive female named Jane.

    Object Syntax

    It is important to note the syntax associated with changing the state of an object. The syntax of a programming language refers to the rules governing the use of the language. The general syntax for using the property of an object is as follows:

    objectName.Property

    Note the period, or dot, between objectName and Property. The period that appears between the object name and the property (or method) name is called the dot operator in C#. If you think of an object as a steel box surrounding the properties and methods of the object, the dot operator is the key that unlocks the object's door and lets you inside the object to gain access to the object's properties and methods.

    In the statement

    myFriend.Name = Jane;

    the computer processes the statement from right to left. You might verbalize the process implied by the statement as the following sequence of steps:

    1. Place the word Jane in a wheelbarrow.

    2. Go to the object named myFriend.

    3. Insert your key (the dot operator) into the door of the box.

    4. Open the door of the box.

    5. Guide your wheelbarrow over to the name property.

    6. Dump the letters Jane into the name property.

    You can visualize these steps, as shown in Figure 2.6.

    Figure 2.6: Changing the value of the Name property

    2.6

    Now that you've followed these steps, the object associated with the myFriend variable has a name assigned to it. This also means that the state of the myFriend object has changed from an object with no name to one with the name Jane.

    The object may be used in the opposite direction, too. For example, suppose you have assigned Jane's name to the myFriend object. Later in the program you want to display her name in a textbox object on a form. If the textbox object is named txtName, you could write

    txtName.Text = myFriend.Name;

    Again, because an assignment statement is processed from right to left, the code causes the program to do the following:

    1. Go to the myFriend object.

    2. Insert the key (the dot operator) into the steel box's lock.

    3. Open the door of the myFriend object.

    4. Push an empty wheelbarrow over to the name property of myFriend.

    5. Make a copy of the bytes stored in the name property (that is, Jane).

    6. Place the copy into the wheelbarrow.

    7. Come out of the object's box. (The door closes automatically!)

    8. Push the wheelbarrow over to the textbox object named txtName.

    9. Insert the key (the dot operator) into the lock for the txtName's box.

    10. Open txtName's door in its box.

    11. Push the wheelbarrow over to the Text property of the txtName object.

    12. Dump Jane into the Text property.

    You can visualize these steps, as shown in Figure 2.7.

    Figure 2.7: Copying a property value into another variable

    2.7

    This sequence of steps illustrates two important concepts to remember:

    You did not change the state of the object associated with myFriend in this last sequence. You simply went inside the object, copied its contents, and left. Because the code didn't alter the contents of any of the properties (data) of myFriend, its state remains unchanged.

    You did change the state of the txtName object. This is true because you went into the txtName object and assigned the copy of Jane's name to the Text property of the txtName object. Because the Text property's data changed, the state of the txtName object was changed.

    You can make two important generalizations from these observations:

    If an object's property appears on the right side of the assignment operator (equals sign, =), you are simply reading the property of the object, not changing its state.

    If an object's property appears on the left side of the assignment operator, you are changing the data of one of its properties and, therefore, changing that object's state.

    Although there are a few exceptions, these generalizations can serve you well most of the time.

    Why Hide the Data Inside an Object?

    In an oversimplified way, the discussion in this section describes how objects work and how properties, or the object's data, should be hidden inside an object. Why hide the properties inside an object? You hide them for the same reason that kings used to hide their daughters in the castle tower…to keep other people from messing around with them.

    By encasing the properties (data) of the object inside a steel box, you can restrict access to those properties by forcing everyone to have a proper key (the object's dot operator) to gain access to the properties. Stated differently, you bury the data inside an object in an attempt to protect the data from accidental changes by other parts of the program. The process to hide data within an object is called encapsulation. Encapsulation is one of the cornerstones of OOP. You learn more about encapsulation and the other elements of OOP in later chapters. For the moment, however, just keep in mind that you want to encapsulate (hide) your objects' data as much as possible, yet still make that data available to those parts of your program that need it.

    Getting Started with Objects

    In the following Try It Out you write a simple program that uses a few of the many objects that Visual Studio provides for you. Follow the same general directions you used to create the program to test your installation of Visual Studio in Chapter 1.

    Note

    Virtually every program in this book starts with the C# template described here, using the same sequence of steps described next. Therefore, you should make note of this page number (perhaps writing the page number on the back cover) and refer to it whenever you are asked to start a new project. After a while, you will know the sequence by heart.

    If the following sequence does not apply to a particular project, you will be told so and a different set of instructions will be presented. With the exception of the project name, the steps are the same for all future projects.

    Try It Out: Create New Project

    Create a new program project using the following steps:

    1. From the File menu, select New → Project.

    2. Select C# Windows Empty Project.

    3. Name the program Chapter02Program01.

    4. Uncheck the Create Directory for Solution if you don't want to add a separate folder. (I usually uncheck it but you don't have to. See Figure 2.8.)

    Figure 2.8: Creating a new project

    2.8

    5. Add a form to the project using the Project → Add Windows Form → Windows Form; give it the name frmMain.cs and click Add.

    Type your program name into the Name textbox (near the bottom of the dialog box in Figure 2.8) for the project name, and click the OK button. Visual Studio creates the project for you, using the default file location for the project (such as C:\Documents and Settings\yourUserName\Local Settings\Application Data\Temporary Projects\ProgramName).

    You should now see the project listed in the Solution Explorer window. If you don't see the Solution Explorer window, use the View → Solution Explorer menu sequence. (You can also use the keyboard shortcut to display the Solution Explorer window by pressing the Control (Ctrl) and W keys at the same time and then pressing the S key.)

    6. Now use the Project → Add Windows Form menu sequence to invoke the dialog, as shown in Figure 2.9. The starting point for all C# programs is with a method named Main(). For consistency, therefore, this text always names the starting form as frmMain.cs. Although this is not a C# requirement, this convention is used throughout the text. When you click the Add button, an empty form appears where the Source Code window was. This new window is called the Form Designer

    Enjoying the preview?
    Page 1 of 1