Variables: Storing Data

Variables

The Crash Course

• Variables store all sorts of stuff:
• byte, short, int, and long store integer values of 1 byte, 2 bytes, 4 bytes, and 8 bytes respectively.
• float, and double store floating point values using 4 bytes and 8 bytes respectively.
• decimal stores floating point values with 16 bytes, with a smaller range, and more accuracy than double.
• char stores a single character.
• string stores text.
• bool stores a true or false value.
• You declare a variable by stating its type and a name like this: int aNumber;
• Names must start with a letter (a-z or A-Z), can contain any letters, numbers, and the underscore ('_') character, and can be basically any length.
• You can assign values to variables using the equal ('=') sign like this: aNumber = 3;
• You can declare a variable and assign it a value all in one statement, like this: int anotherNumber = 5;

Introduction

In this tutorial, we'll cover one of the most important fundamentals of programming: variables. Variables are used to store your data, and any program that does anything real will use them. In this tutorial, we'll discuss how to make them in a C# program, and how to put stuff in them. We'll also discuss the different types of variables that you can use.

What is a Variable?

A core part of any programming language, and any program you make, is the ability to store information. For example, a player's score, or number of lives left.

You may remember discussing variables in math classes, but these are a little different. In math, we talk about variables being an "unknown quantity" that you are supposed to solve for. In other words, just something to figure out.

In programming, a variable is like a little bucket to put stuff in. You can put different things in the bucket, allowing the contents of the bucket to vary. (Hence the name, "variable".)

In C#, like many other programming languages, there are many types of buckets, each of which can store different types of data, like numbers, characters, and so on. (While you probably don't care too much at this point, languages that are like this are called "strongly typed". Some languages have essentially one type of bucket that anything can go in. These are called "weakly typed".)

We'll discuss the different types of C# variables in more detail in a minute. First, let's look at the basics of how to create a variable.

Creating Variables

So let's make our first variable. Go to Visual C# Express (or Visual Studio if you are using it) and create a new C# console project, like we did in the previous tutorial. Inside of the Main method, add the following single line of code:

```int score;
```

Congratulations! You've made your first variable! OK, it's no big deal, but still…. There are two parts to creating, or "defining" a variable. First, you need to indicate the type of the variable. There are certain keywords that are used in C# to choose which type of variable you are creating.

Remember that the type of variable determines what kind of stuff you can store in it. In this case, the type we are using is int, which means it can store integer values. (Integer values, in case you don't remember from math class, are whole numbers and their negatives, so 0, 1, 2, 3, 4, 5, 6, … and -1, -2, -3, -4, -5, -6…. In this particular type of variable that we have defined, we could store the number 100, or the number -75946, but we could not store the number 1.3483 (it's not an integer), and we also could not store a word like "hamburger" (it's not an integer either). In a minute, we'll discuss variable types in more detail.

The second part of defining a variable is to give it a name. It is important to remember that a variable's name is really for humans only. The computer doesn't care what it is called (and in fact, once you hand it off to the computer, it changes the name to a memory location anyway). So you want to choose a name that makes sense for what you are going to put into it.

In math, we often call variables by a single letter (like 'x') but in programming, we can be more precise, and call it something like "score" instead.

Also, as always, all C# statements end with a ';', which tells the computer it has reached the end of the statement.

Assigning Values to Variables

The next thing we want to do is give your new variable a value. This is called "assigning" a value to the variable, and it is done using the assignment operator: "=". So below the previous line you added, add this line:

```score = 0;
```

In programming, the "=" sign usually means something a little different from what you might be used to from math. I'll explain what I mean in the next tutorial, when we discuss basic math in C#. Usually, when I see a statement that looks like score = 0;, I try to think of it as "score gets assigned the value 0", "score gets 0", or "score now has a value of 0" as opposed to "score equals 0", because this is different from the mathematical "=" sign.

Of course, you can assign any value to score:

```score = 4;
score = 11;
score = -1564;
```

You can assign a value to a variable whenever you want. Of course, right now, we haven't really learned very powerful tools for programming (We'll get there! Don't worry!) so "whenever you want" doesn't mean a whole lot, yet.

Even cooler, you can combine defining a variable and assigning a variable into one single step:

```int theMeaningOfLife = 42;
```

In this statement, we created a variable called theMeaningOfLife, with a type of int for integer numbers, and gave it a starting value of 42.

The Types of Variables

OK, integers can be a bit boring. Let's take a look at the common variable types that we'll see in a C# program, and discuss the differences between them, and when you'll use them.

Here is a table containing the main variable types in C#:

 Type Name Description Bytes Data Range Example short stores smaller integers 2 -32,768 to 32,767 short score = 495; int stores medium sized integers 4 -2,147,483,648 to 2,147,483,647 int score = 450000; long stores very large integers 8 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 long highScore = 4043333; byte stores small unsigned (no + or -) integers 1 0 to 255 byte color = 55; ushort stores small unsigned integers 2 0 to 65,535 ushort score = 495; uint stores medium unsigned integers 4 0 to 4,294,967,295 uint score = 4500000; ulong stores large unsigned integers 8 0 to 18,446,744,073,709,551,615 ulong highScore = 4043333; float stores smaller real (floating point) numbers 4 ±1.5 × 10^−45 to ±3.4 × 10^38, 7 digits of accuracy float xPosition = 3.2f; double stores larger real numbers 8 ±5.0 × 10^−324 to ±1.7 × 10^308, 15 to 16 digits of accuracy double yPosition = 3.3; decimal real numbers, smaller range, higher accuracy 16 ±1.0 × 10^−28 to ±7.9 × 10^28, 28 to 29 digits of accuracy decimal zPosition = 3.3; char stores a single character or letter 2 any single character char myFavoriteLetter = 'c'; string stores a sequence of numbers, letters, or symbols any a sequence of any character of any length string message = "Hello World!" bool stores a true or false value 1 true or false bool levelComplete = true;

The contents of this table probably require a little bit more explanation. Let's start with a brief look at the first three integer types, short, int, and long. The more bytes they use, the larger the number can be, but also the more memory they take up. So before deciding between the three, you need to know how big of numbers you might be storing. In most (but not all) cases, int is probably the size you want to go with.

There are also unsigned equivalents for those three types, which are ushort, uint, and ulong each of these types don't involve a sign, everything is assumed to be positive. This allows these types to store twice as big of numbers, though you can't use negative numbers at all. (Zero is fine.)

The byte type is only a single byte, and it, too, is unsigned. This may seem pretty limiting, since it can only hold up to the number 255. But the byte type is also used for pushing around raw bytes that don't have any meaning, as far as the computer is concerned. For instance, the contents of files or images, or the data being transmitted across a network. This data may include integers or other types of information, but the program may not care about it right at the moment.

The types float, double, and decimal store what math people call "real numbers" and what computer people call "floating point numbers". All of the other types before can store the number 3, and the number 4, but they can't store the number 3.5. Fractional numbers, or numbers with a decimal point, must be stored in variables with a floating point type. The float type is for smaller numbers that require less accuracy, while the double type is for larger numbers that require more accuracy. The decimal type has a smaller range than either of those two, but has a whole lot more accuracy than either. So depending on what you want, you'll have to choose between them. decimal is not needed very often in games, so you will see float and double a lot more often.

char and string are for text, with char being only for a single letter, and string being for a "string" or sequence of letters, numbers, and symbols.

Finally, bool is used for logic (we'll see a lot more of this in a few tutorials) to determine if something is true or false, and then to do different things, depending on the state.

Printing the Content of Variables

Any of these variables can be written out in a way similar to what we did in the previous tutorial, using Console.WriteLine. For example:

```int score = 35;
Console.WriteLine(score);

bool levelComplete = true;
Console.WriteLine(levelComplete);

string message = "Hello World!";
Console.WriteLine(message);
```

RB's Guide to Good Variable Names

Before we wrap up here, I want to take a minute and explain some things about naming variables. There's a lot of debate in the programming world about specifics of naming variables, and I'm going to give you my ideas here.

The motivation for good variable names is to make it easy for someone else to read and understand your code, or even for you to understand your code when you come back to it a week, month, or year later. I once heard a quote (I wish I could remember who said it) that went "When I first wrote this code, only me and God knew what it did. Now, only God knows!" Good variable names are an absolutely critical part to writing readable code, and is not something to be ignored.

For starters, there are some built-in rules for variable naming in C#. All variable names have to start with a letter (a-z or A-Z) and can then contain any number of other letters, numbers, or the underscore ('_') character. If you do anything else, the compiler will get mad at you, and won't compile the program.

My one, most important rule, that you really ought to follow, is to name your variables something that describes what you are putting in it. If you are putting a player's score in it, call it "score", or "playerScore", or even "plrscr" if you have to, but don't call it "jambalaya" or "p".

"plrscr" brings up another point, though. It sort of resembles "player score", but if you don't already know what it does, you have to sit there and try to fill in the missing letters. Is it "plar scare", or "plor score"? Nope, it is "player score", you just have to sit there and think about it, if you don't already know. So rule #2 is, don't abbreviate, unless it is a common abbreviation, like HTML.

Rule #3: variables should, in most (but not all) cases have at least three letters, and don't worry too much if it gets kind of long. It's better to be descriptive. (Back in the day, there was an eight character limit to variable names, but not any more. And if a variable name seems like it will be hard to type, you can use Visual C# Express's autocomplete feature, and you won't need to actually type the whole thing in.) If you are talking about an x- and y-coordinate, x and y are probably fine because they are so standardized, but usually, one or two letters doesn't accurately describe what you're storing.

Rule #4: If you start sticking numbers on the end of your variables, you're probably doing it wrong, and you should consider giving them different names. Instead of count1 and count2, perhaps it is better to call it "rowCount" and "columnCount". Also, usually "data", "text", "number", and "item" are not descriptive enough.

Rule #5: In most cases, a variable should be named with a noun (a person, place, thing, or idea, remember?) or a noun phrase (like "player score" is).

Rule #6: Make the words of the variable name stand out from each other, to make it more readable, since you can't use spaces in your variable names. playerScore and player_score are both more readable than playerscore. My personal preference is the first, where you capitalize the first letter in each word, but using underscores is also fine.

A More Complete Example

Below is some code that showcases how these variables are defined and assigned in various ways:

```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Variables
{
class Program
{
static void Main(string[] args)
{
// This declares and assigns these variables
// all in one step.
short levelNumber = 3;
int score = 0;

// This declares a variable, and assigns it
// at a later point in time.
long aBigNumber;
aBigNumber = -17;

// Here is a byte, which contains any value
// between 0 and 255 inclusive.
byte aSingleByte = 55;

// Here's the unsigned stuff.
ushort thisHoldsPositivesOnly = 45;
uint sameHere = 503494;
ulong sameHereButBigger = 449494033;

// The text-based variable types
char myFavoriteLetter = 'c'; // It's my favorite, because it's for cookie.
string aMessage = "You've received a new message at your private terminal.";

// The Boolean type.
bool stillWorking = true;
stillWorking = false;
}
}
}
```

What's Next?

With a basic understanding of variables under our belt, we're ready to start to do some real work. Our first step will be to cover some basic math operations (computer's love math!). Before long, you'll be making the programs of your dreams!