2. Variables and Data Types
Chapter 0010 2
What’s the Point?
-
Know how to select a data type
-
Write code to declare variables and assign values
-
Use standard C# naming conventions
-
Do some basic math calculations
-
Get and process user input
Source code examples from this chapter and associated videos are available on GitHub.
It’s fun to create programs that display stuff on the screen, but that’s pretty limited. To start doing things that are more interesting—and useful—we’ll need to keep track of some information. In computer programming, a piece of information is called data.
In broad terms, there are two kinds of data:
- constant
-
A piece of data that can’t change during program execution.
- variable
-
A piece of data that may change (or "vary") during program execution.
In our Hello World
code, the letters and characters we output are constant data.
HelloWorld
in C#1
Console.WriteLine("Hello World!");
The only way to change what’s output is by editing that constant—in the quotation marks—in our source code, before we run the program.
The string literal in our Hello World code is just one kind of constant. We’ll learn about others later.
|
In order for our programs to be flexible and responsive, we’ll need variables. I encourage beginning students to think of a variable like a container, such as a cup.

The container can hold one thing at a time. We can put coffee in it, or we can put water in it—but we can’t put both. If we start with coffee and decide we want to put water in there, the coffee gets dumped out and is gone forever. That’s fine, but we better make sure we don’t want the coffee anymore before we put something else in the mug.
A variable works the same way. It can hold one value, and that value can vary—remember, that’s where the name comes from—but once it’s changed, that old value is lost.
I guess we could mix coffee and water, but then that’s really a new substance and we can’t get back our plain coffee (or our water). If we want to store coffee and water, we can do that by using two different containers.
From a programming perspective—rather than a coffee perspective—a variable is a location in the computer’s memory where we can store a value. In order to use that value, we have to know where to find it, so we give the memory location a name, technically called an identifier.

And the computer will need to know how much memory to set aside for that variable, which depends on the kinds of values we want to store. Storing the number 7 doesn’t take very much space; storing a picture of John Elway takes a lot more space (but it’s worth it!). The type of data we can store in a variable is called its
…drumroll, please…
data type.
Reserving a memory location by specifying a data type and identifier is known as declaring a variable. Placing data in that variable is referred to as assigning a value to a variable.
If you have programming experience in Python or JavaScript, the idea of a data type might be new to you. In those languages, the interpreter determines the data type for you—so you don’t have to specify it. It’s one reason I prefer to teach beginners using C# or Java, which teaches you how data types work. |
2.1. C# Identifiers
Variable names (more properly called variable identifiers) are the character sequences that identify a variable. There are a few rules that determine whether or not an identifier is valid:
-
Can contain letters (upper or lower case), digits (0 - 9), and/or underscores (_).
-
The first character can’t be a digit.
-
Can’t contain whitespaces (tab, space, etc.) or special characters (like @, #, $, etc.) except for the underscore.
-
Can’t be a C# keyword or reserved word (words that are used in the C# language, like
double
orpublic
)
In addition to those technical rules about identifier names, the convention in C# is to use descriptive names in "camel case" format, as described in the preceding video.
Single-letter variable names, like x
for a number, are fine in your math class, but are generally not okay when you’re coding.
The expectation in my course is that your code will align with those conventions—because that’s what industry people expect—and you will lose points if you don’t.
2.2. Numeric Data Types
Variables for storing numbers come in two flavors: integers and floating-point numbers. As you may remember from your math class, an integer is a whole number; that is, a number that doesn’t include any decimal places or fractional values. 5 is an integer, -824 is an integer, while 3.14 and 7 1/2 are not.
A floating-point number includes decimals, so 3.14 can be stored as a floating-point number. 7 1/2 can also be stored as a floating-point number, but only as a decimal (i.e., 7.5).
The most common numeric data types in C# are int
for integers and double
for floating-point numbers.
You can get pretty far in programming just using those three, and in courses I teach you won’t need to use any other numeric data types—but others do exist.
Other data types for integers are byte
, short
, and long
.
These different types exist because they use different amounts of memory. byte
and short
are smaller than int
, while long
is larger.
The impact of these different memory sizes (or memory allocations) is that the types can store values of different sizes.
For example, a byte
uses 8 bits of memory and can store a number between -128 and 127 (inclusive), while an int
takes 32 bits and can store a value between -2,147,483,648 and 2,147,483,647 (inclusive).
Other floating-point data type in C# are float
and decimal
.
'float' is called "single" in some programming languages, which helps understand where the name double
comes from: double
uses twice as much memory (64 bits) as a float
or "single" (32 bits)--and therefore its range of values is twice as big. Be aware that to make a float
number in C#, you have to add the letter F (in capital or lowercase form) at the end of the number.
The decimal
data type is slower and uses more memory than float or double, but it’s more precise.
It’s used for financial calculations and other situations where precision is important.
1
2
3
int myAge = 21;
float myGPA = 3.75f; (1)
double myFriendsGPA = 3.54;
1 | The f suffix denotes that the value 3.75 is a float rather than a double . |
2.2.1. Who Cares About Variable Size?
The general rule in programming is to be as efficient with your resources (memory, storage, processing speed, network bandwidth, etc.) as possible.
If you’re storing a person’s age, you don’t really need an int
; nobody is going to be two million years old!
A byte
has plenty of room (up to 127) to store even the oldest person’s age, and it uses a fraction of the memory—8 bits instead of 32.
So I should be telling you to use a byte
in this case.
And I should be insisting on decimal
when we store money, because it’s more precise than double
or float
.
But I don’t worry about that stuff with beginning programmers for two reasons.
First, it’s hard enough for a beginner to write programs that work—so instead of asking you to deal with all of the numeric types, I just have you use int
whenever you need a whole number, and double
when you need something with a decimal.
Second, these days even the wimpiest computer has waaaaaay more RAM than is needed by even the most complex program a beginner will write, so we don’t need to worry about it.
But understand that this attitude is only a teaching and learning aid. It’s like saying we shouldn’t worry about the price of groceries because we have plenty of money. That might be true, but it’s good to be careful with your money—and it’s irresponsible of me to tell you to just waste your money.
As you get more comfortable with programming, use your memory resources efficiently. While you’re learning, just worry about getting your code to work.
2.3. bool
Data Type (and Boolean Logic)
A bool
variable has only two possible values: true
and false
.
It’s useful for tracking information that is only one thing or the other.
Am I passing this class?
The answer to that is either true
or false
--there is no other possibility.
Does Julia own a car?
Again, only two possible answers to that question; she either owns one or she doesn’t.
The best practice is to name a bool
variable in a way that expresses this either/or state.
That is to say, we usually name our bool
variables using words like is, has, can, and so on.
1
2
bool isPassing = true;
bool hasCar = false;
boolean
variables go hand-in-hand with Boolean expressions which are statements that evaluate to be either true
or false
, like those questions above.
We’ll look at this "Boolean logic" in the chapter on decisions.
2.4. char
Data Type
If we want to store a single character, like a student’s letter grade or their first initial, we can use the char
data type.
char
literals are created by putting a character in single quotes, and that character can be a letter, number, punctuation mark or symbol—or some other weird stuff, too.
1
2
char myLetterGrade = 'A';
char firstInitial = 'T';
Some people pronounce the char data type like the word "chart" without the "t". And some people pronounce it like the word "care". Either is okay.
|
Also, I pronounce it "char" like "chart" without the "t" and firmly believe that only a sociopath would say it like the word "care". |
A char
is really just an integer, but the number it holds conforms to a standard list of character values called ASCII (with the fun pronunciation "ass key").
In this standard, the number 65 is a capital 'A', 66 is 'B', and so on.
Lowercase letters are considered different characters, so 97 is 'a' and 98 is 'b'. Check out the complete ASCII table if you’re curious.
2.5. Strings
A char
is pretty limited since it can only hold a single character.
If we want to put a collection of characters together to make words and sentences, we need multiple char
s grouped into a single variable.
That data type is called string
, because it strings together a bunch of char
s, like a string of holiday lights.

string
variable is multiple char
s strung together like a set of lights.string
literals are denoted with double quotation marks; remember that char
values use single quotation marks.
string
variable declarations in C#string address = "3000 N. Dysart Road";
string bestClass = "CIS150AB";
Strings are really important and there’s all kinds of fun and useful stuff we can do with them, but we’ll need to save all of that for later while we stay focused on the basics.
Always remember that, in C#, single quotes ' mean a char and double quotes " mean a string . It’s easy to get them mixed up—especially if you’re used to Python, where they are interchangeable—but your code won’t compile if you mix them up.
|
2.6. Declaring Constants
A constant is similar to a variable, with two rules:
-
A value must be assigned when the constant is declared.
-
The assigned value can’t change during program execution.
To create a constant, add the keyword const
at the start of your statement, followed by the rest of a declaration and assignment statement you’d use for a variable.
So that people looking at your code can easily tell it’s a constant rather than a variable, it should be named with all capital letters, using the underscore character to separate words.
const double SALES_TAX_RATE = 8.7;
const int MINIMUM_AGE = 18;
const String FAVORITE_CLASS = "CIS150AB";
There are a few different reasons to use constants in your code. For now: * Constants improve readability—they identify the purpose of a value within your code. * Constants prevent writing code that accidentally changes a value that shouldn’t change. * Constants make code easier to maintain/update. * In some situations, constants are more efficient than variables.
2.7. Outputting Variable (and Constant) Values
Assigning a value to a variable or constant does not produce any output.
If we want to display the output of a variable—or a constant—we just put the identifier in a Write()
or WriteLine()
statement without any quotation marks:
1
2
3
4
5
6
String artistName = "Elvis Presley";
int birthYear = 1935;
Console.Write(artistName);
Console.Write(" was born in ");
Console.WriteLine(birthYear);
This code outputs
Elvis Presley was born in 1935.
2.7.1. Concatenating Output
We can combine output into one statement by creating a string with multiple pieces using the +
symbol.
1
2
3
4
string artistName = "Elvis Presley";
int birthYear = 1935;
Console.WriteLine(artistName + " was born in " + birthYear);
Creating a String
using the +
symbol is called concatenating.
Be thoughtful when concatenating, because the +
symbol is also used to do addition with numbers, as you’ll see soon.
2.7.2. Interpolating Output
Another way to output variables and constants is to use interpolation.
Interpolation is a way to insert the value of a variable or constant into a string.
There are two ways to interpolate in C#.
The easiest for beginners is to put the $
symbol in front of the opening quotation mark of the string, and then put the variable or constant name in curly braces {}
where you want those values inserted.
1
2
3
4
string artistName = "Elvis Presley";
int birthYear = 1935;
Console.WriteLine($"{artistName} was born in {birthYear}");
For my assignments, you can use either concatenation or interpretation, but I encourage you to learn interpolation. It’s easier to read and write than concatenation and is considered the standard approach. Once you’ve gotten the hang of it, it’s very easy to use.
Deep Cut
You can also insert variables into strings using the string.Format()
Method, which uses a similar placeholder syntax.
2.7.3. Choosing an Output Method
For our purposes, there’s no difference between outputting using separate Write()
statements, concatenation, or interpolation; you can use whichever approach you prefer.
Most programmers end up using interpolation because it’s easy to write—and easy to read.
It also lends itself well to formatting output, which means making the output look nice and readable; we don’t worry about that here, but eventually you’ll find it useful.
But as far as I’m concerned, use whatever approach you like.
Take It for a Spin
This is a good time to stop and try out what you’ve learned so far. The Coding Practice assignment for this chapter can be completed with the concepts covered to this point.
2.8. Math Calculations
To start doing some calculations, we’ll use operators.
You can think of an operator as a symbol that performs a calculation or other action.
You’ve been using an operator already: the assignment operator, which uses the =
symbol.
The action it completes is assigning the value on the right of the =
symbol to the variable on the left.
Arithmetic operations work in a similar way.
In C#, there are five basic arithmetic operators:
Operator |
Description |
|
Addition |
|
Subtraction |
|
Multiplication |
|
Division (quotient) |
|
Modulo (remainder) |
The arithmetic operators work pretty much the way you’d expect, except maybe modulo--which might be a term you’ve never heard before. Each operator acts on the value to either side:
1
2
int sum = 5 + 7; (1)
int difference = sum - 2; (2)
1 | The value of sum will be 12 |
2 | The value of difference will be 10 (i.e., 10 - 2) |
2.8.1. Order of Operations
Early on in your math studies you learned about order of operations when an arithmetic expression has more than one calculation, and it works the same in C#. We call this operator precedence, and here are the guidlines:
-
Any operations enclosed in parentheses are evaluated first, following the rest of the rules here.
-
Multiplication, division, and modulus are evaluated next: the
*
,/
, and%
operators. If there are more than one of these operations in the expression, they are evaluated from left to right. -
Addition and subtraction are evaluated last. As above, if the expression contains more than one
+
or-
operator, they evaluate from left to right.
Consider the following examples:
int result1 = 17 - 4 * 6 / 3; (1)
int result2 = 17 - 4 / 2 + 2; (2)
int result3 = 17 - 4 / (2 + 2); (3)
1 | result1 is 9: 4 * 6 is 24, then 24 / 3 is 8, and then 17 - 8 is 9. |
2 | result2 is 17: 4 / 2 is 2, then 17 - 2 is 15, and then 15 + 2 is 17. |
3 | result3 is 16: (2 + 2) is 4, then 4 / 4 is 1, and then 17 - 1 is 16. |
2.8.2. More Arithmetic with Less Typing!
There’s a pretty consistent rule of thumb in coding that says programmers want to type as little as possible, so programming languages often provide shorthand ways of writing code that’s used frequently.
Compound assignment operators (also called shorthand operators) simplify the syntax when you need to change a variable’s value relative to it’s existing value.
For example, if we want to add 10 to a weight
variable that already has the value 145
, we could use the following:
weight = weight + 10;
C# starts on the right side of the assignment expression and retrieves the current value of weight
, which is 145, adds 10 to that value, and stores the result back in weight
.
We can combine the addition operator (`) with the assignment operator (`=`) to make a compound addition operator: `=
, which allows us to rewrite the above line of code as:
weight += 10
;
You can use compound assignment operators for all of the arithmetic operations:
-
+=
adds the value on the right to variable value on the left. -
-=
substracts the value on the right from the variable on the left. -
*=
multiplies the value on the left by the value on the right. -
\=
divides the variable value on the left by the value on the right. -
%=
divides the variable value on the left by value on the right, then assigns the remainder.
An operation we might not use much now, but will start using a lot when we learn to write loops, is incrementing a value, or adding 1 to a value. The increment operator (two plus symbols) gives us a very easy way to do that. On somebody’s birthday, for example, we could write:
age++;
The ++
simply adds 1 to the current value of age
.
The decrement operator is --
, and it subtracts 1 from a variable’s value.
If we’re counting down the number of days until our next birthday, we could execute this expression each morning:
daysRemaining--;
Increment and decrement only require one operand, so we call them unary operators.
There are two forms to the increment and decrement operators: prefix and postfix. These examples use the postfix form, putting the operator after the variable name, whereas a prefix form would have the operator before the variable name: ++age . There’s a subtle difference in how postfix and prefix operations work, but for now you can use them interchangeably. I mention it here only because you might see code examples online using the prefix form.
|
2.9. Handling User Input
Until now, our code hasn’t been interactive—each execution of a program results in the exact same output, and the user never has the chance to input anything.
To produce output, we’ve been using Console.WriteLine
and Console.Write
to display text on the screen.
For input, we’ll use Console.ReadLine
(and, occasionally, Console.Read
).
1
2
3
4
string artist = "";
Console.Write("Enter the name of your favorite music artist: ");
artist = Console.ReadLine();
Console.WriteLine($"Your favorite music artist is: {artist}");
Console.ReadLine
only deals with string
values; even if the user types in a number, it will be stored as a string
--which means we’ll need to convert it to a number if we want to do any math with it.
1
2
3
4
5
int age = -1;
Console.Write("Enter your age: ");
age = Console.ReadLine(); (1)
age++;
Console.WriteLine($"Next year you will be {age}");
1 | This code will not compile because Console.ReadLine returns a string , but we’re trying to assign it to an int . |
2.9.1. Converting Data Types
When we looked at arithmetic, we saw that data types are really important.
For example, if we divide an int
by another int
, the result is an int
--even if we stick that result in a double
variable.
And we learned that we can use a process called type casting to help switch between two numeric types.
But we can’t just cast a string
to numeric type because the string
might not contain a number—it might have letters and weird symbols.
Instead, we need to use a method to convert the string to a number.
There are two basic ways to do the conversion: with the Convert
class or with the Parse
method.
The Convert
class has a few methods for converting values.
The two we’ll use most are:
-
Convert.ToInt32
, which can convert astring
to anint
. -
Convert.ToDouble
which can convert astring
to adouble
.
The 32 in ToInt32 is the number of bits used to store the number, and that’s the size of the int data type. There are methods to convert to 16-bit and 64-bit integers as well, though we won’t be using them.
|
Convert
class 1
2
3
4
5
6
7
8
9
10
int age = -1;
double gpa = -1.0;
Console.Write("Enter your age: ");
age = Convert.ToInt32(Console.ReadLine());
age++;
Console.WriteLine($"Next year you will be {age}");
Console.Write("Enter your GPA: ");
gpa = Convert.ToDouble(Console.ReadLine());
gpa += 0.5;
Console.WriteLine($"If you improve by half a letter grade, you GPA will be {gpa}");
We can also use the Parse
method to convert a string
to a number.
The Parse
method is a little different because it is called on the data type we want to convert to, rather than using a class method.
If we are converting from a string
to an int
, the syntax is int.Parse()
.
For a double, it would be double.Parse()
.
Parse
method 1
2
3
4
5
6
7
8
9
10
int age = -1;
double gpa = -1.0;
Console.Write("Enter your age: ");
age = int.Parse(Console.ReadLine());
age++;
Console.WriteLine($"Next year you will be {age}");
Console.Write("Enter your GPA: ");
gpa = double.Parse(Console.ReadLine());
gpa += 0.5;
Console.WriteLine($"If you improve by half a letter grade, you GPA will be {gpa}");
There are some differences between the two approaches, but for our purposes, they’re interchangeable. You should recognize both, but you can use whichever you prefer in your code.
Check Yourself Before You Wreck Yourself (on the assignments)
Chapter Review Questions
Sample answers provided in the Liner Notes.