Data type, database, Lieutenant Commander Data... it’s all important stuff. Without data, your programs are useless. You need information from your users, and you use that to look up or produce new information to give back to them. In fact, almost everything you do in programming involves working with data in one way or another. In this chapter, you’ll learn the ins and outs of C#’s data types, see how to work with data in your program, and even figure out a few dirty secrets about objects (pssst...objects are data, too).

The variable’s type determines what kind of data it can store

There are a bunch of types built into C#, and each one stores a different kind of data. You’ve already seen some of the most common ones, and you know how to use them. But there are a few that you haven’t seen, and they can really come in handy, too.

Types you’ll use all the time

It shouldn’t come as a surprise that int, string, bool, and double are the most common types.

int can store any whole number from –2,147,483,648 to 2,147,483,647.

Note

A whole number doesn’t have a decimal point.

string can hold text of any length (including the empty string "").

bool is a Boolean value—it’s either true or false.

double can store real numbers from ±5.0 × 10–324 to ±1.7 × 10308 with up to 16 significant figures. That range looks weird and complicated, but it’s actually pretty simple. The “significant figures” part means the precision of the number: 35,048,410,000,000, 1,743,059, 14.43857, and 0.00004374155 all have seven significant figures. The 10308 thing means that you can store any number as large as 10308 (or 1 followed by 308 zeroes)—as long as it only has 16 or fewer significant figures. On the other end of the range, 10-324 means that you can store any number as small as 10-324 (or a decimal point followed by 324 zeroes followed by 1)... but, you guessed it, as long as it only has 16 or fewer significant figures.

Note

“float” is short for “floating point”—as opposed to a “fixed point” number, which always has the same number of decimal places.

More types for whole numbers

Once upon a time, computer memory was really expensive, and processors were really slow. And, believe it or not, if you used the wrong type, it could seriously slow down your program. Luckily, times have changed, and most of the time if you need to store a whole number you can just use an int. But sometimes you really need something bigger... and once in a while, you need something smaller, too. That’s why C# gives you more options:

Note

A lot of times, if you’re using these types it’s because you’re solving a problem where it really helps to have the “wrapping around” effect that you’ll read about in a few minutes.

Types for storing really HUGE and really tiny numbers

Sometimes 7 significant figures just isn’t precise enough. And, believe it or not, sometimes 1038 isn’t big enough and 10-45 isn’t small enough. A lot of programs written for finance or scientific research run into these problems all the time, so C# gives us two more types:

float can store any number from ±1.5. × 10-45 to ±3.4 × 1038 with 7 significant digits.

decimal can store any number from ±1.0 × 10-28 to ±7.9 × 1028 with 28–29 significant digits.

Note

When your program needs to deal with currency, you usually want to use a decimal to store the number.

Note

When you used the Value property in your numericUpDown control, you were using a decimal.

Note

A “literal” just means a number that you type into your code. So when you type “int i = 5;”, the 5 is a literal.

Literals have types, too

When you type a number directly into your C# program, you’re using a literal... and every literal is automatically assigned a type. You can see this for yourself—just enter this line of code that assigns the literal 14.7 to an int variable:

int myInt = 14.7;

Now try to build the program. You’ll get this:

That’s the same error you’ll get if you try to set an int equal to a double variable. What the IDE is telling you is that the literal 14.7 has a type—it’s a double. You can change its type to a float by sticking an F on the end (14.7F). And 14.7M is a decimal.

Note

If you try to assign a float literal to a double or a decimal literal to a float, the IDE will give you a helpful message reminding you to add the right suffix. Cool!

Note

The “M” stands for “money”—seriously!

A few more useful built-in types

Sometimes you need to store a single character like Q or 7 or $, and when you do you’ll use the char type. Literal values for char are always inside single quotes ('x', '3'). You can include escape sequences in the quotes, too ('\n' is a line break, '\t' is a tab). You write an escape sequence in your C# code using two characters, but your program stores each escape sequence as a single character in memory.

Note

You’ll learn a lot more about how char and byte relate to each other in Chapter 9.

And finally, there’s one more important type: object. You’ve already seen how you can create objects by creating instances of classes. Well, every one of those objects can be assigned to an object variable. You’ll learn all about how objects and variables that refer to objects work later in this chapter.

Brain Power

Windows 7 has a really neat feature in Calculator called “Programmer” mode, where you can see binary and decimal at the same time!

You can use the Windows calculator to convert between decimal (normal, base-10) numbers and binary numbers (base-2 numbers written with only ones and zeroes)—put it in Scientific mode, enter a number, and click the Bin radio button to convert to binary. Then click Dec to convert it back. Now enter some of the upper and lower limits for the whole number types (like –32,768 and 255) and convert them to binary. Can you figure out why C# gives you those particular limits?

A variable is like a data to-go cup

All of your data takes up space in memory. (Remember the heap from last chapter?) So part of your job is to think about how much space you’re going to need whenever you use a string or a number in your program. That’s one of the reasons you use variables. They let you set aside enough space in memory to store your data.

Note

Not all data ends up on the heap. Value types usually keep their data in another part of memory called the stack. You’ll learn all about that in Chapter 14.

Think of a variable like a cup that you keep your data in. C# uses a bunch of different kinds of cups to hold different kinds of data. And just like the different sizes of cups at the coffee shop, there are different sizes of variables, too.

Numbers that have decimal places are stored differently than whole numbers. You can handle most of your numbers that have decimal places using float, the smallest data type that stores decimals. If you need to be more precise, use a double. And if you’re writing a financial application where you’ll be storing currency values, you’ll want to use the decimal type.

It’s not always about numbers, though. (You wouldn’t expect to get hot coffee in a plastic cup or cold coffee in a paper one.) The C# compiler also can handle characters and non-numeric types. The char type holds one character, and string is used for lots of characters “strung” together. There’s no set size for a string object, either. It expands to hold as much data as you need to store in it. The bool data type is used to store true or false values, like the ones you’ve used for your if statements.

10 pounds of data in a 5 pound bag

When you declare your variable as one type, that’s how your compiler looks at it. Even if the value is nowhere near the upper boundary of the type you’ve declared, the compiler will see the cup it’s in, not the number inside. So this won’t work:

20,000 would fit into a short, no problem. But since leaguesUnderTheSea is declared as an int, the compiler sees it as int-sized and considers it too big to put in a short container. The compiler won’t make those translations for you on the fly. You need to make sure that you’re using the right type for the data you’re working with.

Sharpen your pencil

Three of these statements won’t compile, either because they’re trying to cram too much data into a small variable or because they’re putting the wrong type of data in. Circle them.

Try building your program. Uh oh—you got an error that looks like this:

Make the error go away by casting the decimal to an int. Once you change the second line so it looks like this, your program will compile and run:

So what happened?

The compiler won’t let you assign a value to a variable if it’s the wrong type—even if that variable can hold the value just fine—because that’s the underlying cause behind an enormous number of bugs. When you use casting, you’re essentially making a promise to the compiler that you know the types are different, and that in this particular instance it’s OK for C# to cram the data into the new variable.

Note

Take a minute to flip back to the beginning of the last chapter and check out how you used casting when you passed the NumericUpDown. Value to the Talker Tester form.

Sharpen your pencil Solution

Three of these statements won’t compile, either because they’re trying to cram too much data into a small variable or because they’re putting the wrong type of data in. Circle them.

When you cast a value that’s too big, C# will adjust it automatically

Wrap it yourself!

There’s no mystery to how casting “wraps” the numbers—you can do it yourself. Just pop up the Windows calculator, switch it to Scientific mode, and calculate 365 Mod 256 (using the “Mod” button, which does a modulo calculation). You’ll get 109.

You’ve already seen that a decimal can be cast to an int. It turns out that any number can be cast to any other number. But that doesn’t mean the value stays intact through the casting. If you cast an int variable that’s set to 365 to a byte variable, 365 is too big for the byte. But instead of giving you an error, the value will just wrap around: for example, 256 cast to a byte will have a value of 0. 257 would be converted to 1, 258 to 2, etc., up to 365, which will end up being 109. And once you get back to 255 again, the conversion value “wraps” back to zero.

Yes! The + operator converts for you.

What you’ve been doing is using the + operator, which does a lot of converting for you automatically—but it’s especially smart about it. When you use + to add a number or Boolean to a string, then it’ll automatically convert that value to a string, too. If you use + (or *, /, or -) with two different types, it automatically converts the smaller type to the bigger one. Here’s an example:

Since an int can fit into a float but a float can’t fit into an int, the + operator converts myInt to a float before adding it to myFloat.

Sharpen your pencil

You can’t always cast any type to any other type. Create a new project, drag a button onto a form, double-click on it, and type these statements in. Then build your program—it will give lots of errors. Cross out the ones that give errors. That’ll help you figure out which types can be cast, and which can’t!

C# does some casting automatically

There are two important conversions that don’t require you to do the casting. The first is done automatically any time you use arithmetic operators, like in this example:

Sharpen your pencil Solution

You can’t always cast any type to any other type. Create a new project, drag a button onto a form, and type these statements into its method. Then build your program—it will give lots of errors. Cross out the ones that give errors. That’ll help you figure out which types can be cast, and which can’t!

The other way C# converts types for you automatically is when you use the + operator to concatenate strings (which just means sticking one string on the end of another, like you’ve been doing with message boxes). When you use + to concatenate a string with something that’s another type, it automatically converts the numbers to strings for you. Here’s an example. The first two lines are fine, but the third one won’t compile.

The C# compiler spits out an error that mentions something about invalid arguments (an argument is what C# calls the value that you’re passing into a method’s parameter). That’s because the parameter for MessageBox.Show() is a string, and this code passed a long, which is the wrong type for the method. But you can convert it to a string really easily by calling its ToString() method. That method is a member of every value type and object. (All of the classes you build yourself have a ToString() method that returns the class name.) That’s how you can convert x to something that MessageBox.Show() can use:

MessageBox.Show(x.ToString());

When you call a method, the arguments must be compatible with the types of the parameters

Note

A parameter is what you define in your method. An argument is what you pass to it. A method with an int parameter can take a byte argument.

Try calling MessageBox.Show(123)—passing MessageBox.Show() a literal (123) instead of a string. The IDE won’t let you build your program. Instead, it’ll show you an error in the IDE: “Argument ‘1’: cannot convert from ‘int’ to ‘string’.” Sometimes C# can do the conversion automatically—like if your method expects an int, but you pass it a short—but it can’t do that for ints and strings.

But MessageBox.Show() isn’t the only method that will give you compiler errors if you try to pass it a variable whose type doesn’t match the parameter. All methods will do that, even the ones you write yourself. Go ahead and try typing this completely valid method into a class:

When the compiler gives you an “invalid arguments” error, it means that you tried to call a method with variables whose types didn’t match the method’s parameters.

It works just fine if you pass it what it expects (a bool)—call MyMethod(true) or MyMethod(false), and it compiles just fine.

But what happens if you pass it an integer or a string instead? The IDE gives you a similar error to the one that you got when you passed 123 to MessageBox.Show(). Now try passing it a Boolean, but assigning the return value to a string or passing it on to MessageBox.Show(). That won’t work, either—the method returns an int, not a long or the string that MessageBox.Show() expects.

Note

You can assign anything to a variable, parameter, or field with the type object.

if statements always test to see if something’s true

Did you notice how we wrote our if statement like this:

if (yesNo) {

We didn’t have to explicitly say “if (yesNo == true)”. That’s because an if statement always checks if something’s true. You check if something’s false using ! (an exclamation point, or the NOT operator). “if (!yesNo)” is the same thing as “if (yesNo == false)”. In our code examples from now on, you’ll usually just see us do “if (yesNo)” or “if (!yesNo)”, and not explicitly check to see if a Boolean is true or false.

Exercise

Note

Actually, C# does give you a way to use reserved keywords as variable names, by putting @ in front of the keyword. You can do that with non-reserved names too, if you want to.

There are about 77 reserved words in C#. These are words reserved by the C# compiler; you can’t use them for variable names. You’ll know a lot of them really well by the time you finish the book. Here are some you’ve already used. Write down what you think these words do in C#.

Create a reimbursement calculator for a business trip. It should allow the user to enter a starting and ending mileage reading from the car’s odometer. From those two numbers, it will calculate how many miles she’s traveled and figure out how much she should be reimbursed if her company pays her $.39 for every mile she puts on her car.

Start with a new Windows project.

Make the form look like this:

When you’re done with the form, double-click on the button to add some code to the project.

Create the variables you’ll need for the calculator.

Put the variables in the class definition at the top of Form1. You need two whole number variables to track the starting odometer reading and the ending odometer reading. Call them startingMileage and endingMileage. You need three numbers that can hold decimal places. Make them doubles and call them milesTraveled, reimburseRate, and amountOwed. Set the value for reimburseRate to .39.

Make your calculator work.

Add code in the button1_Click() method to:

Make sure that the number in the Starting Mileage field is smaller than the number in the Ending Mileage field. If not, show a message box that says “The starting mileage must be less than the ending mileage”. Make the title for the message box “Cannot Calculate”.

Subtract the starting number from the ending number and then multiply it by the reimburse rate using these lines:

Type in some values and see what happens. First enter a starting mileage and ending mileage, and click the Calculate button. Then click the Display Miles button to see what’s stored in the milesTraveled field.

Um, something’s not right...

No matter what numbers you use, the number of miles always matches the amount owed. Why?

Combining = with an operator

Take a good look at the operator we used to subtract ending mileage from starting mileage (-=). The problem is it doesn’t just subtract, it also assigns a value to the variable on the left side of the subtraction sign. The same thing happens in the line where we multiply number of miles traveled by the reimbursement rate. We should replace the -= and the *= with just - and *:

So can good variable names help you out here? Definitely! Take a close look at what each variable is supposed to do. You already get a lot of clues from the name milesTraveled—you know that’s the variable that the form is displaying incorrectly, and you’ve got a good idea of how that value ought to be calculated. So you can take advantage of that when you’re looking through your code to try to track down the bug. It’d be a whole lot harder to find the problem if the incorrect lines looked like this instead:

Objects use variables, too

So far, we’ve looked at objects separate from other types. But an object is just another data type. Your code treats objects exactly like it treats numbers, strings, and Booleans. It uses variables to work with them:

Using an int

Write a statement to declare the integer.

int myInt;

Assign a value to the new variable.

myInt = 3761;

Use the integer in your code.

while (i < myInt) {

Using an object

Write a statement to declare the object.

Assign a value to the object.

spot = new Dog();

Check one of the object’s fields.

while (spot.IsHappy) {

Objects are just one more type of variable your program can use.

If your program needs to work with a whole number that’s really big, use a long. If it needs a whole number that’s small, use a short. If it needs a yes/no value, use a boolean. And if it needs something that barks and sits, use a Dog. No matter what type of data your program needs to work with, it’ll use a variable.

Refer to your objects with reference variables

When you create a new object, you use code like new Guy(). But that’s not enough; even though that code creates a new Guy object on the heap, it doesn’t give you a way to access that object. You need a reference to the object. So you create a reference variable: a variable of type Guy with a name, like joe. So joe is a reference to the new Guy object you created. Any time you want to use that particular guy, you can reference it with the reference variable called joe.

Note

That’s called instantiating the object.

So when you have a variable that is an object type, it’s a reference variable: a reference to a particular object. Take a look:

References are like labels for your object

In your kitchen, you probably have a container of salt and sugar. If you switched their labels, it would make for a pretty disgusting meal—even though the labels changed, the contents of the containers stayed the same. References are like labels. You can move labels around and point them at different things, but it’s the object that dictates what methods and data are available, not the reference itself.

When your code needs to work with an object in memory, it uses a reference, which is a variable whose type is a class of the object it’s going to point to. A reference is like a label that your code uses to talk about a specific object.

You never refer to your object directly. For example, you can’t write code like Guy.GiveCash() if Guy is your object type. The C# compiler doesn’t know which Guy you’re talking about, since you might have several instances of Guy on the heap. So you need a reference variable, like joe, that you assign to a specific instance, like Guy joe = new Guy().

Now you can call methods, like joe.GiveCash(). joe refers to a specific instance of the Guy class, and your C# compiler knows exactly which instance to use. And, as you saw above, you might have multiple labels pointing to the same instance. So you could say Guy dad = joe, and then call dad.GiveCash(). That’s OK, too—that’s what Joe’s kid does every day.

If there aren’t any more references, your object gets garbage-collected

If all of the labels come off of an object, programs can no longer access that object. That means C# can mark the object for garbage collection. That’s when C# gets rid of any unreferenced objects, and reclaims the memory those objects took up for your program’s use.

Here’s some code that creates an object.

For an object to stay in the heap, it has to be referenced. Some time after the last reference to the object disappears, so does the object.

Now let’s create a second object.

Let’s take the reference to the first object, and change it to point at the second object.

Typecross

Take a break, sit back, and give your right brain something to do. It’s your standard crossword; all of the solution words are from this chapter.

Multiple references and their side effects

You’ve got to be careful when you start moving around reference variables. Lots of times, it might seem like you’re simply pointing a variable to a different object. But you could end up removing all references to another object in the process. That’s not a bad thing, but it may not be what you intended. Take a look:

Dog rover = new Dog();
rover.Breed = "Greyhound";

Objects:___1_______

References:___1_______

Dog fido = new Dog();
fido.Breed = "Beagle";
Dog spot = rover;

Objects:___2_______

References:___3_______

Dog lucky = new Dog();
lucky.Breed = "Dachshund";
fido = rover;

Objects:___2_______

References:___4_______

Sharpen your pencil

Now it’s your turn. Here’s one long block of code. Figure out how many objects and references there are at each stage. On the right-hand side, draw a picture of the objects and labels in the heap.

Create a program with an elephant class. Make two elephant instances and then swap the reference values that point to them, without getting any Elephant instances garbage-collected.

Start with a new Windows Application project.

Make the form look like this:

Create the Elephant class.

Add an Elephant class to the project. Have a look at the Elephant class diagram—you’ll need an int field called EarSize and a String field called Name. (Make sure both are public.) Then add a method called WhoAmI() that displays a message box that tells you the name and ear size of the elephant.

Create two Elephant instances and a reference.

Add two Elephant fields to the Form1 class (in the area right below the class declaration) named Lloyd and Lucinda. Initialize them so they have the right name and ear size. Here are the Elephant object initializers to add to your form:

Have the Lloyd button call lloyd.WhoAmI() and the Lucinda button call lucinda.WhoAmI().

Hook up the swap button.

Here’s the hard part. Make the Swap button exchange the two references, so that when you click Swap, the Lloyd and Lucinda variables swap objects and a “Objects swapped” box is displayed. Test out your program by clicking the Swap button and then clicking the other two buttons. The first time you click Swap, the Lloyd button should pop up Lucinda’s message box, and the Lucinda button should pop up Lloyd’s message box. If you click the Swap button again, everything should go back.

C# garbage-collects any object with no references to it. So here’s your hint: If you want to pour a glass of beer into another glass that’s currently full of water, you’ll need a third glass to pour the water into....

Exercise Solution

Create a program with an elephant class. Make two elephant instances and then swap the reference values that point to them, without getting any Elephant instances garbage-collected.

Note

strings and arrays are different from all of the other data types you’ve seen, because they’re the only ones without a set size (think about that for a bit).

Brain Power

Why do you think we didn’t add a Swap() method to the Elephant class?

Two references means TWO ways to change an object’s data

Besides losing all the references to an object, when you have multiple references to an object, you can unintentionally change an object. In other words, one reference to an object may change that object, while another reference to that object has no idea that something has changed. Watch:

Do this

Add another button to your form.

Add this code for the button. Can you guess what’s going to happen when you click it?

OK, go ahead and click the new button. Wait a second, that’s the Lucinda message box. Didn’t we call the WhoAmI() method from Lloyd?

A special case: arrays

If you have to keep track of a lot of data of the same type, like a list of heights or a group of dogs, you can do it in an array. What makes an array special is that it’s a group of variables that’s treated as one object. An array gives you a way of storing and changing more than one piece of data without having to keep track of each variable individually. When you create an array, you declare it just like any other variable, with a name and a type:

Use each element in an array like it is a normal variable

When you use an array, first you need to declare a reference variable that points to the array. Then you need to create the array object using the new statement, specifying how big you want the array to be. Then you can set the elements in the array. Here’s an example of code that declares and fills up an array—and what’s happening on the heap when you do it. The first element in the array has an index of zero.

Arrays can contain a bunch of reference variables, too

You can create an array of object references just like you create an array of numbers or strings. Arrays don’t care what type of variable they store; it’s up to you. So you can have an array of ints, or an array of Duck objects, with no problem.

Here’s code that creates an array of 7 Dog variables. The line that initializes the array only creates reference variables. Since there are only two new Dog() lines, only two actual instances of the Dog class are created.

When you set or retrieve an element from an array, the number inside the brackets is called the index. The first element in the array has an index of zero.

An array’s length

You can find out how many elements are in an array using its Length property. So if you’ve got an array called heights, then you can use heights.Length to find out how long it is. If there are 7 elements in the array, that’ll give you 7—which means the array elements are numbered 0 to 6.

Welcome to Sloppy Joe’s Budget House o’ Discount Sandwiches!

Sloppy Joe has a pile of meat, a whole lotta bread, and more condiments than you can shake a stick at. But what he doesn’t have is a menu! Can you build a program that makes a new random menu for him every day?

MenuMaker

Randomizer

Meats

Condiments

Breads

GetMenuItem()

Do this

Start a new project and add a MenuMaker class

If you need to build a menu, you need ingredients. And arrays would be perfect for those lists. We’ll also need some way of choosing random ingredients to combine together into a sandwich. Luckily, the .NET Framework has a built-in class called Random that generates random numbers. So we’ll have four fields in our class: a Randomizer field that holds a reference to a Random object, and three arrays of strings to hold the meats, condiments, and breads.

Add a GetMenuItem() method to the class that generates a random sandwich

The point of the class is to generate sandwiches, so let’s add a method to do exactly that. It’ll use the Random object’s Next() method to choose a random meat, condiment, and bread from each array. When you pass an int parameter to Next(), the method returns a random that’s less than that parameter. So if your Random object is called Randomizer, then calling Randomizer.Next(7) will return a random number between 0 and 6.

So how do you know what parameter to pass into the Next() method? Well, that’s easy—just pass in each array’s Length. That will return the index of a random item in the array.

How it works...

Build your form

Add six labels to the form, label1 through label6. Then add code to set each label’s Text property using a MenuMaker object. You’ll need to initialize the object using a new instance of the Random class. Here’s the code:

Objects use references to talk to each other

So far, you’ve seen forms talk to objects by using reference variables to call their methods and check their fields. Objects can call one another’s methods using references, too. In fact, there’s nothing that a form can do that your objects can’t do, because your form is just another object. And when objects talk to each other, one useful keyword that they have is this. Any time an object uses the this keyword, it’s referring to itself—it’s a reference that points to the object that calls it.

Elephant

Name

EarSize

WhoAmI()

TellMe()

SpeakTo()

Here’s a method to tell an elephant to speak

Let’s add a method to the Elephant class. Its first parameter is a message from an elephant. Its second parameter is the elephant that said it:

Here’s what it looks like when it’s called. You can add to button4_Click(), but add it before the statement that resets the references! (lloyd = lucinda;)

lloyd.TellMe("Hi", lucinda);

We called Lloyd’s TellMe() method, and passed it two parameters: “Hi” and a reference to Lucinda’s object. The method uses its whoSaidIt parameter to access the Name parameter of whatever elephant was passed into TellMe() using its second parameter.

Here’s a method that calls another method

Now let’s add this SpeakTo() method to the Elephant class. It uses a special keyword: this. That’s a reference that lets an object talk about itself.

Let’s take a closer look at how this works.

lloyd.SpeakTo(lucinda, "Hello");

When Lloyd’s SpeakTo() method is called, it uses its talkTo parameter (which has a reference to Lucinda) to call Lucinda’s TellMe() method.

So Lucinda acts as if she was called with ("Hello", lloyd), and shows this message:

Where no object has gone before

There’s another important keyword that you’ll use with objects. When you create a new reference and don’t set it to anything, it has a value. It starts off set to null, which means it’s not pointing to anything.

There are no Dumb Questions

Q:

Q: One more time—my form is an object?

A:

A: Yes! That’s why your class code starts with a class declaration. Open up code for a form and see for yourself. Then open up Program.cs in any program you’ve written so far and look inside the Main() method—you’ll find “new Form1()”.

Q:

Q: Why would I ever use null?

A:

A: There are a few ways you see null used in typical programs. The most common way is testing for it:

if (lloyd == null) {

That test will return true if the lloyd reference is set to null.

Another way you’ll see the null keyword used is when you want your object to get garbage-collected. If you’ve got a reference to an object and you’re finished with the object, setting the reference to null will immediately mark it for collection (unless there’s another reference to it somewhere).

Q:

Q: You keep talking about garbage collecting, but what’s actually doing the collecting?

A:

A: Remember how we talked about the Common Language Runtime (or CLR) back at the beginning of the first chapter? That’s the virtual machine that runs all .NET programs. A virtual machine is a way for it to isolate running programs from the rest of the operating system. One thing that virtual machines do is manage the memory that they use. That means that it keeps track of all of your objects, figures out when the last reference to the object disappears, and frees up the memory that it was using.

There are no Dumb Questions

Q:

Q: I’m still not sure I get how references work.

A:

A: References are the way you use all of the methods and fields in an object. If you create a reference to a Dog object, you can then use that reference to access any methods you’ve created for the Dog object. If you have a (non-static) method called Dog.Bark() or Dog.Beg(), you can create a reference called spot. Then you can use that to access spot.Bark() or spot.Beg(). You could also change information in the fields for the object using the reference. So you could change a Breed field using spot.Breed.

Q:

Q: Wait, then doesn’t that mean that every time I change a value through a reference I’m changing it for all of the other references to that object, too?

A:

A: Yes. If rover is a reference to the same object as spot, changing rover.Breed to “beagle” would make it so that spot.Breed was “beagle.”

Q:

Q: I still don’t get that stuff about different types holding different sized values. What’s the deal with that?

A:

A: OK. The thing about variables is they assign a size to your number no matter how big its value is. So if you name a variable and give it a long type even though the number is really small (like, say, 5), the CLR sets aside enough memory for it to get really big. When you think about it, that’s really useful. After all, they’re called variables because they change all the time.

The CLR assumes you know what you’re doing and you’re not going to give a variable a type that you don’t need. So even though the number might not be big now, there’s a chance that after some math happens, it’ll change. The CLR gives it enough memory to handle whatever type of number you call it.

Q:

Q: Remind me again—what does “this” do?

A:

A:this is a special variable that you can only use inside an object. When you’re inside a class, you use this to refer to any field or method of that particular instance. It’s especially useful when you’re working with a class whose methods call other classes. One object can use it to send a reference to itself to another object. So if Spot calls one of Rover’s methods passing this as a parameter, he’s giving Rover a reference to the Spot object.

Any time you’ve got code in an object that’s going to be instantiated, the instance can use the special this variable that has a reference to itself.

Bullet Points

Note

There’s actually a very specific case where you don’t declare a type – you’ll learn about it when you use the “var” keyword in Chapter 14.

When you declare a variable you ALWAYS give a type. Sometimes you combine it with setting the value.

There are value types for variables that hold different sizes of numbers. The biggest numbers should be of the type long and the smallest ones (up to 255) can be declared as bytes.

Every value type has a size, and you can’t put a value of a bigger type into a smaller variable, no matter what the actual size of the data is.

When you’re using literal values, use the F suffix to indicate a float (15.6F) and M for a decimal (36.12M).

There are a few types (like short to int) that C# knows how to convert automatically. When the compiler won’t let you set a variable equal to a value of a different type, that’s when you need to cast it.

There are some words that are reserved by the language and you can’t name your variables with them. They’re words like for, while, using, new, and others that do specific things in the language.

References are like labels: you can have as many references to an object as you want, and they all refer to the same thing.

If an object doesn’t have any references to it, it eventually gets garbage-collected.

Sharpen your pencil

Here’s an array of Elephant objects and a loop that will go through it and find the one with the biggest ears. What’s the value of the biggestEars.Earsafter each iteration of the for loop?

Your job is to take code snippets from the pool and place them into the blank lines in the code. You may use the same snippet more than once, and you won’t need to use all the snippets. Your goal is to make a class that will compile and run and produce the output listed.

Bonus Question!

For extra bonus points, use snippets from the pool to fill in the two blanks missing from the output.

Build a typing game

You’ve reached a milestone...you know enough to build a game! Here’s how your game will work. The form will display random letters. If the player types one of them, it disappears and the accuracy rate goes up. If the player types an incorrect letter, the accuracy rate goes down. As the player keeps typing letters, the game goes faster and faster, getting more difficult with each correct letter. If the form fills up with letters, the game is over!

Do this

Build the form.

Here’s what the form will look like in the form designer:

You’ll need to:

Turn off the minimize box and maximize box. Then set the form’s FormBorderStyle property to Fixed3D. That way, the player won’t be able to accidentally drag and resize it. Then resize it so that it’s much wider than it is tall (we set our form’s size to 876, 174).

Drag a ListBox out of the Toolbox onto the form. Set its Dock property to Fill, and its MultiColumn property to True. Set its Font to 72 point bold.

In the Toolbox, expand the “All Windows Forms” group at the top. This will display many controls. Find the Timer control and double-click on it to add it to your form.

Find the StatusStrip in the “All Windows Forms” group in the Toolbox and double-click on it to add a status bar to your form. You should now see the StatusStrip and Timer icons in the gray area at the bottom of the form designer:

See how you can use a Timer to make your form do more than one thing at once? Take a minute and flip to #3 in the “Leftovers” appendix to learn about another way to do that.

Set up the StatusStrip control.

Take a closer look at the status bar at the bottom of the screenshot. On one side, it’s got a series of labels:

Relax

You’ll be using three new controls, but they’re easy to work with!

Even though you haven’t seen a ListBox, StatusStrip, or Timer before, you already know how to set their properties and work with them in your code. You’ll learn a lot more about them in the next few chapters.

And on the other side, it’s got a label and a progress bar:

Add a StatusLabel to your StatusStrip by clicking its drop-down and selecting StatusLabel:

Set the StatusStrip’s SizingGrip property to False.

Use the Properties window to set its (Name) to correctLabel and its Text to “Correct: 0”. Add three more StatusLabels: missedLabel, totalLabel, and accuracyLabel.

Add one more StatusLabel. Set its Spring to True, TextAlign to MiddleRight, and Text to “Difficulty”. Finally, add a ProgressBar and name it difficultyProgressBar.

Set up the Timer control.

Did you notice how your Timer control didn’t show up on your form? That’s because the Timer is a non-visual control. It doesn’t actually change the look and feel of the form. It does exactly one thing: it calls a method over and over again. Set the Timer control’s Interval property to 800, so that it calls its method every 800 milliseconds. Then double-click on the timer1 icon in the designer. The IDE will do what it always does when you double-click on a control: it will add a method to your form. This time, it’ll add one called timer1_Tick. Here’s the code for it:

Add a class to keep track of the player stats.

If the form is going to display the total number of keys the player pressed, the number that were missed and the number that were correct, and the player’s accuracy, then we’ll need a way to keep track of all that data. Sounds like a job for a new class! Add a class called Stats to your project. It’ll have four int fields called Total, Missed, Correct, and Accuracy, and a method called Update with one bool parameter: true if the player typed a correct letter that was in the ListBox, or false if the player missed one.

Stats

Total

Missed

Correct

Accuracy

Update()

Add fields to your form to hold a Stats object and a Random object.

You’ll need an instance of your new Stats class to actually store the information, so add a field called stats to store it. And you already saw that you’ll need a field called random—it’ll contain a Random object.

There’s one last thing your game needs to do: any time the player hits a key, it needs to check if that key is correct (and remove the letter from the ListBox if it is), and update the stats on the StatusStrip.

Go back to the form designer and select the form. Then go to the Properties window and click on the lightning bolt button. Scroll to the KeyDown row and double-click on it. This tells the IDE to add a method called Form1_KeyDown() that gets called every time the user presses a key. Here’s the code for the method:

Run your game.

Your game’s done! Give it a shot and see how well you do. You may need to adjust the font size of the ListBox to make sure it holds exactly 7 letters, and you can change the difficulty by adjusting the values that are subtracted from timer1.Interval in the Form1_KeyDown() method.

Exercise Solutions

There are about 77 reserved words in C#. These are words reserved by the C# compiler; you can’t use them for variable names. You’ll know a lot of them really well by the time you finish the book. Here are some you’ve already used. Write down what you think these words do in C#.

Typecross Solution

Sharpen your pencil Solution

Here’s an array of Elephant objects and a loop that will go through it and find the one with the biggest ears. What’s the value of the biggestEars.Earsafter each iteration of the for loop?

Code Magnets Solution

The code for a button is all scrambled up on the fridge. Can you reconstruct the code snippets to make a working method that produces the output listed below?

Pool Puzzle Solution

The best content for your career. Discover unlimited learning
on demand for around $1/day.