← All lessons

Level 1 / C# Fundamentals / fundamental 1 of 7

Variables and types

Declare variables with the right type, give them values, change them, and print them.

Every C# program starts by holding onto values. A variable is a named box with a type on the label, and the compiler holds you to that label. These reps drill the one shape you will type more than any other: type, name, equals, value, semicolon.

Understand the idea

Type, name, value

A declaration says what kind of value a box can hold (int, double, string, bool), what it is called, and optionally what goes in it first. The type never changes after that: an int box will never hold text.

Pick the right type

int is a whole number, double a fractional number, decimal is for money (it needs an m suffix), string is text in double quotes, char is one character in single quotes, and bool is true or false.

Declare once, assign many times

The type is written only when the variable is created. Later assignments use the name alone. const makes a value that can never change, and var lets the compiler work out the type from the value on the right.

English to C#

“Make an int called age and set it to 30.”

int age = 30;
int
the type: what kind of value it holds
age
the name you will use from now on
= 30
the starting value
;
ends the statement

Rep 1 of 12

Copy it

In English

Make an int called age and set it to 30.

Type the code shown below. Watch it turn green as you go.

int age = 30;

Waiting for you to type · 0 of 5 pieces

Ctrl+Enter checks or moves on. Tab indents. Paste is off on purpose: your hands are learning this too.

Reps

0 of 12 done

Reps unlock in order, because each one builds on the last.

How your code is checked

Drills compare what you type with known-correct C#, token by token. Spacing, line breaks, and comments do not matter; spelling, case, and punctuation do. It is not a compiler, so it accepts the listed spellings of each answer and nothing else.

Try it in a real .NET project

Create a console app with dotnet new console, then declare one variable of each type from this drill in Program.cs and print each with Console.WriteLine. Try assigning text to an int and read the compiler error out loud; that error is the type system doing its job.

Check your understanding

Why does decimal balance = 250.75; fail to compile, while double price = 19.99; works?

Show the explanation

A number with a decimal point is a double literal by default. Converting a double to a decimal can lose precision, so C# will not do it silently. Adding the m suffix makes 250.75m a decimal literal from the start.

Goose School teaches Microsoft's stack. Goose Solutions is not affiliated with, endorsed by, or sponsored by Microsoft.