Why Variables?
All computer programming languages use variables. Variables give us the ability to store data in memory, and reference that data again later in our program. You can visualize a variable as a "box". We can put information in the box, like names or addresses or phone numbers or ages. We can replace the information in the box with new information.
Let's Not Be Literal
The statement below uses a literal:
Console.WriteLine("Hello, World!");
"Hello, World!"
is a string literal. It's a string because it's a sequence of characters surrounded by "quotation marks". It's a literal because it always has that value.
In contrast to literals, we have variables. Instead of...
Console.WriteLine("Hello, World!");
I could have used a variable to write the exact same message to the console:
string message = "Hello, World!";
Console.WriteLine(message);
In the example above, we declared a variable named message
and stored the string Hello, World!
in it. In the second line, we replaced the string literal with the message
variable. When written this way, the contents of the message
variable will be written to the console. In both cases, "Hello, World!" is the result!
Variables are variable
In C#, a variable's type is defined, but its value can vary (thus the name). Remember, variables are like a box in which we can store a value, but they also allow us to change the value that is stored.
Let's declare a variable named message
and store the string I am Sam
in it. Then we will reassign the value of message
to the string I am Spartacus
. Notice the difference in the messages that are printed to the console:
string message = "I am Sam";
Console.WriteLine(message); // prints "I am Sam"
message = "I am Spartacus";
Console.WriteLine(message); // prints "I am Spartacus"
Reusing Variables
Notice that in the previous example, when we first used our message
variable, we specified its type as string
:
string message = "I am Sam";
Console.WriteLine(message);
When we reassigned its value, we didn't specify a type:
message = "I am Spartacus";
Console.WriteLine(message);
That's because we had already declared the variable. We declare a variable only once.
Breaking Down the the Variable Definition
When we do this:
string message = "I am Sam";
We are really combining these two things:
string message;
message = "I am Sam";
Declaring a Variable
We declare a variable by giving it a type and a name. That's what we did here:
string message;
The variable's type is string
. Its name is message
.
Initializing a variable
When we initialize a variable, we are joining the declaration and assignment into a single line of code:
string message; // Declaring the message variable with a name and type
message = "I am Sam"; // Assigning a value to the message variable
...which can be simplified as...
string message = "I am Sam"; // Initializing the message variable by giving it a name, type, and value
Variable Naming Conventions
We will talk about naming conventions quite a bit. They're important, since they reduce the cognitive load of people that need to look at your code. (This person might be you.)
Apart from constants (more on that later), we use camelCase
to name variables. The first letter should be lowercase, and the first letter of each additional word in a variable's name should be uppercase:
Use camelCase:
string myVariable = "my variable's value"; // Like this!
Not lowercase:
string myvariable = "my variable's value"; // Not this.
Not PascalCase:
string MyVariable = "my variable's value"; // Not this, either.
Good Naming Practices
The name we give our variables is for our use, so let's make it a good one! Below is a list of good variable naming practices:
FOLLOW THE C# RULES:
- All variable names must start with a letter or _underscore, not a number or symbol.
- Variables cannot be named the same as a C# reserved word, such as
int
,class
, orprivate
.
BE DESCRIPTIVE:
- Describe the data that you intend to store in your variable, such as
userName
,temperature
,accountBalance
. - Variable names can be long. There is no need to abbreviate like
usrNm
,temp
, oracctBal
. - Be precise. Instead of using general terms like
log
,number
, orvalue
, use a more specific name or add an adjective. Can you see howplayerNumber
andnumberOfPlayers
represent the different values they store?
Basic Data Types
Data Storage
Computer memory is measured in bytes. Every byte is made up of 8 bits. A bit is represented by one of two states- either 0 or 1. Therefore, if you do the math, every byte can store 256 different states. In order to represent more than 256 states, we need more bytes.
For example,
- The number 1 is stored with 1 byte of memory as
00000001
- The number 2 is stored with 1 byte memory as
00000010
- The letter 'A' is stored with 2 bytes of memory as
00000000 01000001
The amount of memory, or "space", that is required to store a variable is determined by its type. Some types use 1 byte of storage, others use 4, 8, or 16.
Built In Types
C# is not a pure object-oriented language. That is to say that it allows for primitive types as well as objects. For now, recognize that primitive types are declared in lowercase. Real objects will have their types capitalized.
Booleans
A bool
variable holds either the value true
or false
. It uses 1 byte of memory.
bool writingCodeIsFun = true;
bool rootCanalsAreFun = false; // unless you're a dentist?
Integer Types
There are four sizes of integer (whole number) types: byte
, short
, int
, and long
. They vary in their maximum and minimum values:
byte
will hold a number that can be stored within one byte (8 bits). Its values range from 0 to 255.short
supports a range of values from -32,768 to 32,767 and requires 2 bytes of memory.int
supports a smaller range of values thanlong
supports. We useint
s (short for "integer") for most practical purposes. It requires 4 bytes of memory and represents values from roughly -2,147,000,000 to 2,147,000,000.long
is the largest integer type. We often seelong
s for things like database record ids since we may have a lot of records in a database. It uses 8 bytes to store numbers that range from +/- 9 quintillion!
All of the following are valid:
byte answerByte = 42;
short answerShort = 42;
int answerInt = 42;
long answerLong = 42;
Floating Point Types
Floating point (numbers with decimal fractions) types are float
, double
, and decimal
.
float
requires 4 bytes of storage and provides 7 digits of floating point precision. Note that we append 'f' to the value for the float variable.double
is more precise thanfloat
. It uses 8 bytes and has 15-16 digits of precision.decimal
is very precise and is often used to represent money. It uses 16 bytes and has 28-29 digits of precision. It requires 'm' at the end of any literal value in order to be treated as a decimal type.
Let's try it:
class Program
{
static void Main(string[] args)
{
double doubleValue = 2.16440330489723961032;
Console.WriteLine(doubleValue);
float floatValue = 2.16440330489723961032f;
Console.WriteLine(floatValue);
decimal decimalValue = 2.16440330489723961032m;
Console.WriteLine(decimalValue);
Console.ReadLine();
}
}
The values assigned to each variable are the same. Try it. What do you see?
Computers aren't as good at math as you thought, eh?
Character primitives
The char
type holds individual characters. We define char
literals by using single apostrophes. It uses 2 bytes of memory.
char myChar = 'a';
String objects
Strings are proper objects. We'll talk more about them later. We've seen them. We denote their values with quotation marks:
string myDeclaration = "I can code";