- •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
The program has features that might not be immediately apparent. To keep the program interesting, the problems are randomly generated each time the program is run. Also, because the game is for younger children, I decided that the answers should always be positive integers. (The problems are fixed so that subtractions will never come out negative, and division problems will never have a remainder.) The program keeps track of the number of questions the user answers and gives a score based on the user’s responses.
Using Numeric Variables
A computer programmer needs to understand how computers work with information. The hardware of modern computers works with little on/off switches that work in Base−two mathematics. Some people refer to this type of mathematics as binary mathematics and use values of 1 and 0 instead of on and off switches. All information in a computer, from text to video games, is converted internally into binary numbers before the computer can do something useful with it. In the earliest days of computer programming, you had to work in binary notation to do anything.
Fortunately, modern languages such as C# spare you this tedium. You can tell the computer that you want to work with text (which programmers call strings, as you recall from Chapter 1, “Basic Input and Output: A Mini Adventure”), integers (positive and negative numbers without decimal values), real numbers (numbers with decimal values), and complex types of information, such as dates, pictures, sounds, and whatever else you can store in a computer. Although you don’t need to be fluent in binary to be a computer programmer, you do need to understand that the computer uses different tricks to translate all these kinds of data into binary information.
The Simple Math Game
Computers are good at math, but you must look out for a few things. The various types of data storage can have some surprising side effects. The following program, shown in Figure 2.3, illustrates some of the things that can go wrong.
Figure 2.3: The computer can do math, but it gave some strange results here. Is 5 divided by 4 really 1?
This program is silly but it illustrates some important points about how numbers work in computing. Take a look at the source code for this program, and I’ll explain what’s going on:
using System;
33
namespace SimpleMath
{
///<summary>
///Demonstrates basic variable stuff
///Andy Harris, 11/09/01
///</summary>
class DoMath
{
static void Main(string[] args)
{
int a = 1; int b = 2;
float c = 2.4f; float d = 4.7f;
Console.WriteLine("Math Demo"); Console.WriteLine(); Console.WriteLine();
//addition with integers works as expected Console.WriteLine("5 + 4 = {0}", 5 + 4); Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
//division by integers can cause problems Console.WriteLine("5/4 = {0}", 5 / 4);
//dividing by floating point values works better Console.WriteLine("{0} / {1} = {2}", c, d, c/d); Console.WriteLine("5f/4f = {0}", 5f / 4f);
Console.WriteLine();
Console.WriteLine();
Console.Write("Please press \"enter\" to continue");
Console.ReadLine();
} // end main } // end class
}// end namespace
The design of this program is straightforward. The computer simply performs basic mathematical operations and reports the results. The program demonstrates important details about how numeric variables are created and used. I’ll explain how this program works in the next few sections. First, take a look at variable types.
Numeric Variable Types
C# supports a number of numeric variable types. Each type specifies a different way the numeric data is translated into binary. Table 2.1 describes several key data types in C#.
C# supports other types of variables besides the ones listed here, but for a beginning programmer, these variable types work just fine. Each type of variable takes up a specific amount of memory and is best suited for working with a particular type of number. In general, you work with two primary types of numbers in C# programming: the int and double types.
Hint The reference to unicode in the table above refers to a scheme for storing characters in binary form in computer memory. Computers have used a scheme called ASCII for many years, but C# and a number of other languages now use the unicode standard, because it provides support for most written languages, including those which do not use Roman characters.
34
Table 2.1: Selected Data Types
Type |
Description |
Values |
Examples |
bool |
Boolean (true/false) |
True or false |
true |
char |
One character |
Characters in English |
‘a’ |
|
|
or other languages |
|
|
|
(with unicode) |
|
int |
Integer (positive or negative value |
–2 billion to 2 |
34 |
|
without a decimal point) |
billion (roughly) |
−7 |
long |
Long integer |
+/– 9 * 1018r |
3L |
|
|
|
−23L |
float |
Floating−point real number |
+/– 3.5 * 1038, |
1.5f |
|
|
7 significant digits |
−3.1415927f |
double |
Double−precision real number |
+/– 1.7 * 10308, |
−2.5 |
|
|
15 significant digits |
3.1415 |
Integer Variables
You might remember from grade school that integers are positive and negative numbers and zero but not numbers that end in a decimal (or fractional) value. For example, 3, –100, and 0 are integers, but 3.14159 and –0.5 are not. Most of the time in your programming career, you will work with integer values. Although in math integers can be infinitely large or small, they aren’t in computing. Storing a number in a computer’s memory takes a finite amount of space, so the variable types are organized according to how much memory they use. The more memory a variable type uses, the larger range of numbers it can handle.
C# has two main types of integers. The int variable type uses 32 digits of binary to represent a number, meaning that an int variable values roughly between 2 billion and negative 2 billion. This range is related to the largest and smallest numbers that can be stored in 32 digits of binary math. Most of the math you do on a computer probably falls within that range, so if you don’t need a decimal point, you can make an int variable. Any time you refer to a number without a decimal point in your code, the number is interpreted as an int value. The values 5 and 4 are called literal values, because they are not variables. However, the computer still needs to assign a type to such values, and because there is no decimal point in the values, they will be interpreted as literal ints.
Console.WriteLine("5 + 4 = {0}", 5 + 4);
5 and 4 are int literals, but you can also create a variable that is defined as an int. Take a look at these lines in the Simple Math code:
int a = 1; int b = 2;
The keyword int is used to indicate that the compiler should generate a variable of type int. The computer reserves the appropriate amount of memory, and then the user can refer to that chunk of memory as ‘a.’ The value 1 is immediately stored into that memory location.
For example, this code
Console.WriteLine("variable a is {0}", a);
35
produces the following output.
Output:
variable a is 1
Trick Although it isn’t necessary, you can assign a value to a variable as you are creating it, as I did in this program. This ensures that the variable always has a legitimate value. The C# compiler complains if you create a variable that doesn’t have a value assigned. If you prefer, you can simply create a variable without assigning a value, like this: int a; Then assign the value later: a = 1;
Long Integers
At times you need a value larger or smaller than the range of the int. If you need a very large or small integer, you can use the long variable type. A long integer stores its information in 64 digits of binary, so it can handle large (or, of course, small) values. If you need to create a long integer, just use the keyword long, like this:
long a;
If you want to use a long integer as a literal value (for example, assigning a value to a long variable), you use the modifier L at the end of the number, like this:
long a = 21L;
Trap Remember to use a capital L to specify that the value is a long integer. The lowercase l looks a lot like the numeral 1, which can be extremely confusing.
Floating−Point Variables
Like integers, real numbers have multiple kinds of number schemes. Real numbers are those numbers that include decimal values. Computer systems often store real numbers in a floating−point notation, meaning that the decimal point can go anywhere in a number, which gives you a lot of flexibility. Although integers are described by their range (their minimum and maximum values), the most important characteristic of a real number is its precision, the number of significant digits it supports. Floating−point numbers store their values in a form of scientific notation, so they can be extremely large or extremely small. C# uses two main types of real numbers. The float type uses 32 digits of binary and supports a large range. The double type (for the double−precision floating type) uses 64 digits and handles larger values and values extremely close to zero. You probably won’t be surprised to find that you create a floating−point value by using the float keyword, like this:
float myFloat;
You refer to a float value with an f character at the end of the number, like this:
myFloat = 32.4f;
Likewise, you generate a double−precision float with the double keyword:
double myDouble;
You can use the d character to force a number to double status, but doing so is unnecessary because any literal number with a decimal point is presumed to be a double.
36