- •Microsoft C# Programming for the Absolute Beginner
- •Table of Contents
- •Microsoft C# Programming for the Absolute Beginner
- •Introduction
- •Overview
- •Chapter 1: Basic Input and Output: A Mini Adventure
- •Project: The Mini Adventure
- •Reviewing Basic C# Concepts
- •Namespaces
- •Classes
- •Methods
- •Statements
- •The Console Object
- •.NET Documentation
- •Getting into the Visual Studio .Net Environment
- •Examining the Default Code
- •Creating a Custom Namespace
- •Adding Summary Comments
- •Creating the Class
- •Moving from Code to a Program
- •Compiling Your Program
- •Looking for Bugs
- •Getting Input from the User
- •Creating a String Variable
- •Getting a Value with the Console.ReadLine() Method
- •Incorporating a Variable in Output
- •Combining String Values
- •Combining Strings with Concatenation
- •Adding a Tab Character
- •Using the Newline Sequence
- •Displaying a Backslash
- •Displaying Quotation Marks
- •Launching the Mini Adventure
- •Planning the Story
- •Creating the Variables
- •Getting Values from the User
- •Writing the Output
- •Finishing the Program
- •Summary
- •Chapter 2: Branching and Operators: The Math Game
- •The Math Game
- •Using Numeric Variables
- •The Simple Math Game
- •Numeric Variable Types
- •Integer Variables
- •Long Integers
- •Data Type Problems
- •Math Operators
- •Converting Variables
- •Explicit Casting
- •The Convert Object
- •Creating a Branch in Program Logic
- •The Hi Bill Game
- •Condition Testing
- •The If Statement
- •The Else Clause
- •Multiple Conditions
- •Working with The Switch Statement
- •The Switch Demo Program
- •Examining How Switch Statements Work
- •Creating a Random Number
- •Introducing the Die Roller
- •Exploring the Random Object
- •Creating a Random Double with the .NextDouble() Method
- •Getting the Values of Dice
- •Creating the Math Game
- •Designing the Game
- •Creating the Variables
- •Managing Addition
- •Managing Subtraction
- •Managing Multiplication and Division
- •Checking the Answers
- •Waiting for the Carriage Return
- •Summary
- •Chapter 3: Loops and Strings: The Pig Latin Program
- •Project: The Pig Latin Program
- •Investigating The String Object
- •The String Mangler Program
- •A Closer Look at Strings
- •Using the Object Browser
- •Experimenting with String Methods
- •Performing Common String Manipulations
- •Using a For Loop
- •Examining The Bean Counter Program
- •Creating a Sentry Variable
- •Checking for an Upper Limit
- •Incrementing the Variable
- •Examining the Behavior of the For Loop
- •The Fancy Beans Program
- •Skipping Numbers
- •Counting Backwards
- •Using a Foreach Loop to Break Up a Sentence
- •Using a While Loop
- •The Magic Word Program
- •Writing an Effective While Loop
- •Planning Your Program with the STAIR Process
- •S: State the Problem
- •T: Tool Identification
- •A: Algorithm
- •I: Implementation
- •R: Refinement
- •Applying STAIR to the Pig Latin Program
- •Stating the Problem
- •Identifying the Tools
- •Creating the Algorithm
- •Implementing and Refining
- •Writing the Pig Latin Program
- •Setting Up the Variables
- •Creating the Outside Loop
- •Dividing the Phrase into Words
- •Extracting the First Character
- •Checking for a Vowel
- •Adding Debugging Code
- •Closing Up the code
- •Summary
- •Introducing the Critter Program
- •Creating Methods to Reuse Code
- •The Song Program
- •Building the Main() Method
- •Creating a Simple Method
- •Adding a Parameter
- •Returning a Value
- •Creating a Menu
- •Creating a Main Loop
- •Creating the Sentry Variable
- •Calling a Method
- •Working with the Results
- •Writing the showMenu() Method
- •Getting Input from the User
- •Handling Exceptions
- •Returning a Value
- •Creating a New Object with the CritterName Program
- •Creating the Basic Critter
- •Using Scope Modifiers
- •Using a Public Instance Variable
- •Creating an Instance of the Critter
- •Adding a Method
- •Creating the talk() Method for the CritterTalk Program
- •Changing the Menu to Use the talk() Method
- •Creating a Property in the CritterProp Program
- •Examining the Critter Prop Program
- •Creating the Critter with a Name Property
- •Using Properties as Filters
- •Making the Critter More Lifelike
- •Adding More Private Variables
- •Adding the Age() Method
- •Adding the Eat() Method
- •Adding the Play() Method
- •Modifying the Talk() Method
- •Making Changes in the Main Class
- •Summary
- •Introducing the Snowball Fight
- •Inheritance and Encapsulation
- •Creating a Constructor
- •Adding a Constructor to the Critter Class
- •Creating the CritViewer Class
- •Reviewing the Static Keyword
- •Calling a Constructor from the Main() Method
- •Working with Multiple Files
- •Overloading Constructors
- •Viewing the Improved Critter Class
- •Adding Polymorphism to Your Objects
- •Modifying the Critter Viewer in CritOver to Demonstrate Overloaded Constructors
- •Using Inheritance to Make New Classes
- •Creating a Class to View the Clone
- •Creating the Critter Class
- •Improving an Existing Class
- •Introducing the Glitter Critter
- •Adding Methods to a New Class
- •Changing the Critter Viewer Again
- •Creating the Snowball Fight
- •Building the Fighter
- •Building the Robot Fighter
- •Creating the Main Menu Class
- •Summary
- •Overview
- •Introducing the Visual Critter
- •Thinking Like a GUI Programmer
- •Creating a Graphical User Interface (GUI)
- •Examining the Code of a Windows Program
- •Adding New Namespaces
- •Creating the Form Object
- •Creating a Destructor
- •Creating the Components
- •Setting Component Properties
- •Setting Up the Form
- •Writing the Main() Method
- •Creating an Interactive Program
- •Responding to a Simple Event
- •Creating and Adding the Components
- •Adding an Event to the Program
- •Creating an Event Handler
- •Allowing for Multiple Selections
- •Choosing a Font with Selection Controls
- •Creating the User Interface
- •Examining Selection Tools
- •Creating Instance Variables in the Font Chooser
- •Writing the AssignFont() Method
- •Writing the Event Handlers
- •Working with Images and Scroll Bars
- •Setting Up the Picture Box
- •Adding a Scroll Bar
- •Revisiting the Visual Critter
- •Designing the Program
- •Determining the Necessary Tools
- •Designing the Form
- •Writing the Code
- •Summary
- •Chapter 7: Timers and Animation: The Lunar Lander
- •Introducing the Lunar Lander
- •Reading Values from the Keyboard
- •Introducing the Key Reader Program
- •Setting Up the Key Reader Program
- •Coding the KeyPress Event
- •Coding the KeyDown Event
- •Determining Which Key Was Pressed
- •Animating Images
- •Introducing the ImageList Control
- •Setting Up an Image List
- •Looking at the Image Collection
- •Displaying an Image from the Image List
- •Using a Timer to Automate Animation
- •Introducing the Timer Control
- •Configuring the Timer
- •Adding Motion
- •Checking for Keyboard Input
- •Working with the Location Property
- •Detecting Collisions between Objects
- •Coding the Crasher Program
- •Getting Values for newX and newY
- •Bouncing the Ball off the Sides
- •Checking for Collisions
- •Extracting a Rectangle from a Component
- •Getting More from the MessageBox Object
- •Introducing the MsgDemo Program
- •Retrieving Values from the MessageBox
- •Coding the Lunar Lander
- •The Visual Design
- •The Constructor
- •The timer1_Tick() Method
- •The moveShip() Method
- •The checkLanding() Method
- •The theForm_KeyDown() Method
- •The showStats() Method
- •The killShip() Method
- •The initGame() Method
- •Summary
- •Chapter 8: Arrays: The Soccer Game
- •The Soccer Game
- •Introducing Arrays
- •Exploring the Counter Program
- •Creating an Array of Strings
- •Referring to Elements in an Array
- •Working with Arrays
- •Using the Array Demo Program to Explore Arrays
- •Building the Languages Array
- •Sorting the Array
- •Designing the Soccer Game
- •Solving a Subset of the Problem
- •Adding Percentages for the Other Players
- •Setting Up the Shot Demo Program
- •Setting Up the List Boxes
- •Using a Custom Event Handler
- •Writing the changeStatus() Method
- •Kicking the Ball
- •Designing Programs by Hand
- •Examining the Form by Hand Program
- •Adding Components in the Constructor
- •Responding to the Button Event
- •Building the Soccer Program
- •Setting Up the Variables
- •Examining the Constructor
- •Setting Up the Players
- •Setting Up the Opponents
- •Setting Up the Goalies
- •Responding to Player Clicks
- •Handling Good Shots
- •Handling Bad Shots
- •Setting a New Current Player
- •Handling the Passage of Time
- •Updating the Score
- •Summary
- •Chapter 9: File Handling: The Adventure Kit
- •Introducing the Adventure Kit
- •Viewing the Main Screen
- •Loading an Adventure
- •Playing an Adventure
- •Creating an Adventure
- •Reading and Writing Text Files
- •Exploring the File IO Program
- •Importing the IO Namespace
- •Writing to a Stream
- •Reading from a Stream
- •Creating Menus
- •Exploring the Menu Demo Program
- •Adding a MainMenu Object
- •Adding a Submenu
- •Setting Up the Properties of Menu Items
- •Writing Event Code for Menus
- •Using Dialog Boxes to Enhance Your Programs
- •Exploring the Dialog Demo Program
- •Adding Standard Dialogs to Your Form
- •Using the File Dialog Controls
- •Responding to File Dialog Events
- •Using the Font Dialog Control
- •Using the Color Dialog Control
- •Storing Entire Objects with Serialization
- •Exploring the Serialization Demo Program
- •Creating the Contact Class
- •Referencing the Serializable Namespace
- •Storing a Class
- •Retrieving a Class
- •Returning to the Adventure Kit Program
- •Examining the Room Class
- •Creating the Dungeon Class
- •Writing the Game Class
- •Writing the Editor Class
- •Writing the MainForm Class
- •Summary
- •Chapter 10: Chapter Basic XML: The Quiz Maker
- •Introducing the Quiz Maker Game
- •Taking a Quiz
- •Creating and Editing Quizzes
- •Investigating XML
- •Defining XML
- •Creating an XML Document in .NET
- •Creating an XML Schema for Your Language
- •Investigating the .NET View of XML
- •Exploring the XmlNode Class
- •Exploring the XmlDocument Class
- •Reading an Existing XML Document
- •Creating the XML Viewer Program
- •Writing New Values to an XML Document
- •Building the Document Structure
- •Adding an Element to the Document
- •Displaying the XML Code
- •Examining the Quizzer Program
- •Building the Main Form
- •Writing the Quiz Form
- •Writing the Editor Form
- •Summary
- •Overview
- •Introducing the SpyMaster Program
- •Creating a Simple Database
- •Accessing the Data Server
- •Accessing the Data in a Program
- •Using Queries to Modify Data Results
- •Limiting Data with the SELECT Statement
- •Using an Existing Database
- •Adding the Capability to Display Queries
- •Creating a Visual Query Builder
- •Working with Relational Databases
- •Improving Your Data with Normalization
- •Using a Join to Connect Two Tables
- •Creating a View
- •Referring to a View in a Program
- •Incorporating the Agent Specialty Attribute
- •Working with Other Databases
- •Creating a New Connection
- •Converting a Data Set to XML
- •Reading from XML to a Data Source
- •Creating the SpyMaster Database
- •Building the Main Form
- •Editing the Assignments
- •Editing the Specialties
- •Viewing the Agents
- •Editing the Agent Data
- •Summary
- •List of Figures
- •List of Tables
- •List of Sidebars
program. After reading this chapter, you will be able to write something like it.
Note that the user interface is Spartan—no flashy graphics or eye−catching buttons and menus. For now, you are concentrating on the underlying concepts. Those other elements will come soon enough, but they add complications to your life (which you don’t need just yet).
Reviewing Basic C# Concepts
The C# language was designed to profit from the experiences of other programming languages. The basic concepts behind C# programming are apparent in even the simplest programs. Essentially, a C# program can be thought of as an onion with a bunch of layers (see Figure 1.3).
Figure 1.3: In C# programming, you have code inside methods, which are inside classes, which are inside namespaces
In the .NET environment (of which C# is a primary language) are layers of code that go from general to specific. The outer, most general, layer is the namespace. Inside a namespace, you find a series of classes, which contain methods, which contain statements.
Trap Actually, this is a simplified view. As you progress through this book (and beyond), you will see that the .NET model contains other elements. However, this reduced version of the model will suffice for now.
6
Namespaces
The various layers of programming help you organize your programs. Even as a beginner, you need to understand a little bit about the various layers because even the most rudimentary programs use them. Think of the layers as something like an address on an envelope. When you address an envelope, you write specific information, such as the house number. You also put the street name, which is more general, and the state, which is broad. The post office can deliver your letter by getting it to the correct state, then the correct city, then the right part of the city, and finally the specific house. Namespaces in the C# language work very much like this.
The largest landscape in the C# universe is a namespace. You can think of a namespace as a state in the postal analogy. A namespace is an element that enables you to group together a series of other things. Each project you create is usually a namespace. In addition, all the various things you can use in your programs—including the computer system itself, and Windows elements, such as text boxes and buttons—are separated into namespaces. Frequently, you specify which namespaces you want to work with, for example, to define whether a program should use Windows forms or a special library of math functions. If all this seems unclear to you, don’t worry about it. Soon you will see examples that make it clear.
Classes
A namespace is usually made up of one or more classes. A class is a definition for a specific kind of object. Throughout the entire book, you will be learning about classes and objects, but essentially, they are used to describe some type of entity.
Anything a computer can describe (a database, a file, an image, a cow, whatever) can be encoded as an object. The things an object can do are called its methods, and the characteristics of an object are called its properties. Don’t worry, there isn’t a quiz on all this theory. You do need an introduction to these concepts, though, because all of C# is based on the idea of objects.
Methods
Classes always have methods. A method is a structure that contains instructions. All the commands in a program are housed in various methods of objects. Most programs have a special method named Main() (method names always end in parentheses), which is meant to execute as soon as the program begins running. If you are familiar with other languages, such as C or Visual Basic, you will see that methods are a lot like functions or subprograms in those languages.
Statements
Inside a method, you write the instructions you want the computer to execute. A statement is an instruction. Many statements (sometimes also called commands) involve using methods of built−in objects. Of course, a computer scientist wouldn’t usually say using a method, because everyone would understand that. Often C# folks will refer to the process as invoking a method. Maybe at dinner tonight rather than asking somebody to pass the salt, you could say “Could you please invoke the salt shaker object’s pass method?” It should liven up the conversation. Other commands are built in to the structure of the language.
Trick Don’t worry if all this talk about methods and namespaces is making you dizzy. You don’t have to memorize all this now, but you will be using it later. Even the simplest program uses all these levels of instruction, so you need to have some idea of these terms. However, you probably won’t fully understand them until you build a few custom namespaces, classes,
7
and methods down the road. Everybody spends time in confusion until the larger picture becomes clear.
The Console Object
To see how all this works, take a look at one specific object, the console. In the bad old days of computing before visual interfaces like Windows, all interaction with a computer was done through a plain text screen. The combination of the text screen and the keyboards is usually referred to as the console. Although programming on the console might seem kind of old−fashioned, it’s a good place to start because programs which feature the console are easier to write than the fancier programs using Windows forms. In C#, everything is an object, so you’ll work with the console by working with a special object, also called the Console. Note that the names of classes are capitalized, so when I’m referring to the actual Console, class, I use a capital C. Most of your early programs will be built using the Console object, so taking a look at how C# sees this object is a good idea. If you remember working in DOS or command−line UNIX, you probably have some fond memories of the console. Most console applications use only text and appear only in black and white. Modern programs for end users don’t usually work with the console because it makes things much more difficult for users who prefer menus, buttons, and toolbars. However, knowing how to program on the console is still useful because some applications don’t require a graphic user interface, such as server−side programs in Web development, code libraries, and simple applications. The main reason I’m starting you out on the console, though, is that it’s a much easier place to program. Although all those graphic elements make the user’s life easier, they can cause headaches for beginning programmers.
Trick In the earlier days of computing, all computing happened on a simple black−and−white text screen. It was an easy way to learn programming because you had fewer things to learn (and fewer things could go wrong). Programming on the console is still a very important skill, and because it’s still a relatively easy place to work, you start there in your programming journey. You will be able to write programs that look more familiar to a Windows user or a Web surfer as you progress through this book, but all the main ideas can be demonstrated using the generally simpler console.
The console itself can be thought of as a DOS window. If you’ve been around computing for a while, you probably remember the days when you had to type all your commands into a text−only window. The Console object is the way C# views that window, which is still available in modern computing, and is surprisingly useful. To do anything useful with the console, you need to know how to use the Console class within C#, which ships with documentation describing all the various parts of the language. Looking through this documentation will also give you a sense of how the language is organized.
.NET Documentation
To understand the general layout of the language, take a look at Microsoft’s official documentation for the .NET framework. This should be installed on your machine as part of the Visual Studio environment, but it may appear as a separate element in the Start menu. (On my machine, it is Programs, Microsoft .NET framework SDK, Documentation.) Figure 1.4 shows this screen in action.
8
Figure 1.4: Here’s the .NET documentation. I’ve expanded the tree on the left to show the various namespaces available in the .NET environment.
Trick If the .NET documentation is not available on your machine, you should install it before going much further. It is a road map to all of C#, and your way will be much easier if you have access to this map.
A huge amount of information is in the .NET documentation, but you don’t need to concern yourself with all of it. For now, I just want you to see what’s there. The right panel shows a long (intimidating) list of namespaces available to you as a programmer. When the documentation first comes up, you won’t see much in the right−hand panel, so, click the System link under Namespaces to see the contents of the System namespace.
In the Real World
You might be confused about the relationship between C# and .NET. This confusion is understandable because the two technologies are very closely intertwined. .NET is Microsoft’s term for its new programming architecture. The basic idea of .NET is to have several languages use the same underlying architecture, which should have a natural relationship with the various forms of the Windows operating system. Most of Microsoft’s next generation of programming languages, including the latest editions of C++ and Visual Basic, use the .NET environment. However, C# is the first major language designed from the beginning with .NET in mind. Because of this, many pundits speculate that C# will be the most commonly used language in the .NET universe. All programmers in the Microsoft world (there are other kinds of programming) will probably have to learn some form of the .NET model, so C# is a natural choice because of its close relationship with the model. Throughout this book, when you learn about specific syntax issues (such as where to put semicolons and how the assignment operator works), you’re actually learning the C# language. When you learn about certain objects, such as the Console object or command buttons, you’re learning about the .NET universe. If you don’t see the distinction yet, that’s okay. Just note that if you ever want to learn another .NET language (such as Visual Basic, or VB), you will find it an easy jump because both C# and VB use the.NET framework. The .NET framework also provides some interesting possibilities for Internet programming, but these techniques do not work on every web server.
9
The System Namespace
As you can see in Figure 1.5, the System namespace consists of many (again, intimidating) classes. Each of these classes represents an object you can use to write your programs. For now, you can safely ignore most of them, but there is a class to represent the console. Click the appropriate link to examine the Console class. The page of text you see is almost useless, but at the bottom of that page is a link named Console Members. Click this link to learn about the characteristics of the Console class and the things it can do.
Figure 1.5: Some classes in the System namespace. The Console has features for communicating with the user that will be helpful.
The Console Class
The Console is a simple (but important) class. Like most classes, it has properties (which you will ignore for now) and methods (shown in Figure 1.6). Methods are the tasks that the Console object knows how to do. You want to do one thing in this program—write a message to the user.
Fortunately, the Console class contains several methods designed to do exactly that. Take a careful look at Write().
10
Figure 1.6: The members of the Console class.
The Write() Method
The Write() method enables you to write a message to the text screen. Anything you want to write to the screen should be enclosed in quotes inside the parentheses. If you want to write Hi, Mom!, use this command:
System.Console.Write("Hi, Mom!");
This command demonstrates the entire hierarchy of structures in C#. System is a namespace, which contains the Console class, which contains the Write() method. This is cumbersome enough to warrant a loophole. If you use the command
using System;
at the beginning of your program, you no longer have to specify System, and you can simply write
Console.Write("Hi, Mom!");
The WriteLine() Method
The Write() method has an even smarter cousin, named WriteLine(). The easiest way to explain the difference between them is with a demonstration.
This code fragment
Console.Write("Hi, ");
Console.Write("Mom!");
appears on the console as Hi, Mom!.
11
Trap Console.Write does not add anything to the text. Note that I include a space after the comma in "Hi, ". Without the space, the output would be Hi,Mom!.
Each invocation of Console.Write() causes the new text to be written at the next spot on the screen, usually on the same line. Often, you are generating one line of text at a time. The Console.WriteLine() method is used to write text as a complete line, adding a new line (like pressing the Enter key in a word processor) to the end of the line. Here’s an example:
Console.WriteLine("Hi");
Console.WriteLine("Mom");
Output:
Hi
Mom
Although knowing about the Write() and WriteLine() methods is helpful, understanding how to get around in the documentation is even more important. Whenever you want to accomplish a task in C#, usually you can find a method attached to an object in a particular namespace that will fulfill your needs.
Saying “Hello, World!”
The programming world has a surprising number of well−established traditions. One of them is the Hello World program, which is the first program you write in any new environment. It simply pops up on the screen and says, Hello, World!. This is a fun tradition but also has a practical side. It is usually the simplest kind of activity you can make a computer do in a given language. By starting with such a simple program, you can focus your efforts on becoming comfortable with the programming environment. With a debugging and programming package as complex as Visual Studio, starting with a simple program so that you can get your feet wet in the environment makes a lot of sense.
The Hello World program featured in Figure 1.7 doesn’t do much, but it illustrates several important ideas in programming. When you understand the code behind this very simple program, you will have a framework that can be reused for every C# program you write.
Figure 1.7: As advertised, the program says “Hello, World!”
12