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 the 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" for which you are supposed to solve. 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 Studio (or your IDE of choice) and create a new C# console project, like we did in the previous tutorial. Make your code look like the following:

`int score;`

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.

A variable's type 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 how to store these other types.

The second part of defining a variable is to give it a name. It is important to remember that a variable's name is for humans. 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 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.

A variable declaration is another type of statement, and C# statements typically end with ;, so this code does that as well.

## 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 is done using the assignment operator: =. So below the line we already have, add this line:

`score = 0;`

In programming, the = sign usually means something a little different than it does in math. It doesn't mean that two things are always equal; rather, it takes the value on the right side and stores it in the variable named on the left side. Think of a statement like this not as "score equals zero" but as "score is assigned the value of 0."

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 soon), so "whenever you want" doesn't mean much yet.

Even cooler, you can combine variable declaration with assignment in a single step:

`int theMeaningOfLife = 42;`

This is quite common because you must assign a value to a variable before you can read its contents back out. The first assignment to a variable is called initialization, so you might say that you cannot read the value in a variable until after it has been initialized.

The statement above makes a variable called theMeaningOfLife that can store int-typed values and initializes it to the number 42.

## The Types of Variables

There is more to life than just integers. 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 your numbers might get. 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 doesn'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 numbers 3 and 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 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. (In fact, float is usually good enough for nearly everything in games, so you don't even see doubles all that 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 what makes for a good variable name, 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): "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 of writing readable code and are 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 single 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 must, but don't call it jambalaya, p, or bob.

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 usually 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 in many languages, but not anymore. Most descriptive names will need more than a letter or two to correctly convey what is contained in the variable, so if your names are always really short, you may not be descriptive enough. If you're worried about having to type a lot of characters, fear not: Visual Studio's auto-complete feature will make it easy to quickly fill in even long variable names. Obviously, there are exceptions to this rule. If you're talking about x- and y-coordinates for something, the names x and y are plenty descriptive. But those are exceptions to this guideline, not commonplace.

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) 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. By far, the most common convention among C# programmers is the first style, with a capital letter for words besides the first. This style is called camelCase or sometimes lowerCamelCase to differentiate it from UpperCamelCase. I strongly recommend giving this style a try, but if you choose not to, at least be consistent with what you pick.

## A More Complete Example

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

```// 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, we're ready to start doing some real work. Our first step will be to cover some basic math operations (computers love math!). Before long, you'll be making the programs of your dreams!