Why types matter from the first line
In a dynamically typed language such as Python, a variable is a label you can stick on any value. In C#, a variable is a box of a particular shape, and the compiler will not let you put the wrong thing in it. Write int count = "three"; and the program does not build.
That strictness pays for itself in two ways. First, mistakes appear as red underlines in your editor instead of as crashes in production. Second, the type tells the reader, and the runtime, exactly how a value is stored, which is why C# can be both safe and fast. But it also means you must know your types. Is a price an int, a double or a decimal? What happens when an int gets too big? Why does 7 / 2 equal 3? This lesson answers those questions, then turns to the statements that make programs decide and repeat.
The built-in types
C# has a small set of built-in types, each an alias for a .NET type:
| C# | .NET type | Size | Holds |
|---|---|---|---|
bool | System.Boolean | 1 byte | true or false |
byte | System.Byte | 8 bits | 0 to 255 |
short | System.Int16 | 16 bits | about ±32 thousand |
int | System.Int32 | 32 bits | about ±2.1 billion |
long | System.Int64 | 64 bits | about ±9.2 × 10¹⁸ |
float | System.Single | 32 bits | binary floating point, about 7 significant digits |
double | System.Double | 64 bits | binary floating point, about 15–16 significant digits |
decimal | System.Decimal | 128 bits | base-10 floating point, 28–29 significant digits |
char | System.Char | 16 bits | one UTF-16 code unit |
string | System.String | varies | an immutable sequence of char |
There are also unsigned versions (uint, ulong, ushort, sbyte for signed bytes) and the platform-sized nint and nuint, but int, long, double, decimal, bool, char and string cover nearly everything you will write.
Definition— Value type and reference type
A value type (all the numeric types, bool, char, and any struct) holds its data directly: assigning it copies the data. A reference type (string, arrays, and any class) holds a reference to an object elsewhere in memory: assigning it copies the reference, so two variables can point at the same object.
You will meet this distinction again and again; the lesson on classes and structs, and the one on memory, go deeper.
Literals and var
A literal's form decides its type: 42 is an int, 42L a long, 4.2 a double, 4.2f a float, 4.2m a decimal, 'x' a char, "x" a string. Underscores may separate digits (1_000_000), and 0x and 0b start hexadecimal and binary literals.
When the type is obvious from the right-hand side, var lets the compiler infer it:
var total = 0m; // decimal
var names = new List<string>();
var answer = 6 * 7; // intvar is still static typing: total is a decimal forever, and assigning a string to it later is a compile error. Teams differ on how much to use var; a common rule is to use it when the type is evident from the same line, and to write the type out when it is not. A const declares a value fixed at compile time: const int DaysPerWeek = 7;.
Numbers: exact, approximate and overflowing
Run this program and read its output carefully; nearly every line is a lesson.
// Integers: exact, but with a fixed range.
int big = int.MaxValue;
Console.WriteLine($"int.MaxValue = {big}");
Console.WriteLine($"int.MaxValue + 1 = {unchecked(big + 1)}");
long wide = (long)big + 1;
Console.WriteLine($"as a long = {wide}");
// Integer division truncates toward zero; % keeps the sign of the left side.
Console.WriteLine($"7 / 2 = {7 / 2}, 7 % 2 = {7 % 2}");
Console.WriteLine($"-7 / 2 = {-7 / 2}, -7 % 2 = {-7 % 2}");
Console.WriteLine($"7.0 / 2 = {7.0 / 2}");
// double is binary floating point; decimal is base-10 and exact for money.
double d = 0.1 + 0.2;
decimal m = 0.1m + 0.2m;
Console.WriteLine($"double: {d} equals 0.3? {d == 0.3}");
Console.WriteLine($"decimal: {m} equals 0.3? {m == 0.3m}");
// checked arithmetic turns silent wrap-around into an error.
try
{
int oops = checked(big + 1);
Console.WriteLine(oops);
}
catch (OverflowException)
{
Console.WriteLine("checked: overflow detected");
}It prints:
int.MaxValue = 2147483647
int.MaxValue + 1 = -2147483648
as a long = 2147483648
7 / 2 = 3, 7 % 2 = 1
-7 / 2 = -3, -7 % 2 = -1
7.0 / 2 = 3.5
double: 0.30000000000000004 equals 0.3? False
decimal: 0.3 equals 0.3? True
checked: overflow detectedWhat it teaches:
- Integer overflow wraps silently by default. An
intis 32 bits of two's complement, and one past the largest value is the smallest. C# does not check by default because checking costs a little time on every operation. Insidechecked(...)(or achecked { }block, or with the project settingCheckForOverflowUnderflow) overflow throws anOverflowExceptioninstead. (Thetry/catchthat handles it is the subject of a later lesson.) Constant expressions such asint.MaxValue + 1written directly are rejected at compile time, which is why the program goes through a variable. - Widen before you add.
(long)big + 1converts tolongfirst, so the addition happens in 64 bits.(long)(big + 1)would overflow first and widen the wrong answer. /on two integers is integer division, truncating toward zero, and%is the remainder with the sign of the left operand. If either side is adouble, you get ordinary division. When you need a floor-style remainder that is never negative (for example, to wrap an index), write((a % n) + n) % n.doublecannot represent 0.1 exactly, because 0.1 has no finite binary expansion. Never compare doubles with==after arithmetic; compare with a tolerance,Math.Abs(a - b) < 1e-9.decimalworks in base 10, so 0.1 is exact: use it for money, prices and anything a human will add up by hand. Usedoublefor measurements, science, graphics and anything where speed matters more than exact decimal digits.
Note
Numbers are printed using the current culture of the computer. On a machine set to French or German, 3.5 prints as 3,5. For output that other programs will read (files, logs, JSON), format with CultureInfo.InvariantCulture, for example value.ToString(CultureInfo.InvariantCulture), from System.Globalization.
Conversions, characters and strings
C# converts implicitly only when nothing can be lost: int to long, int to double, float to double. Anything that could lose information needs an explicit cast, written (type)value, and you must know what it does. Text from outside the program needs parsing.
string[] inputs = ["42", " 17 ", "4.5", "forty-two", "-3"];
foreach (string text in inputs)
{
if (int.TryParse(text, out int value))
{
Console.WriteLine($"'{text}' -> {value * 2} when doubled");
}
else
{
Console.WriteLine($"'{text}' is not a whole number");
}
}
// Casting a double to an int drops the fraction; Math.Round rounds to even by default.
double price = 2.5;
Console.WriteLine($"(int)2.5 = {(int)price}, Math.Round(2.5) = {Math.Round(price)}, Math.Round(3.5) = {Math.Round(3.5)}");
// char is a UTF-16 code unit; arithmetic on chars gives ints.
char letter = 'C';
Console.WriteLine($"'{letter}' is code {(int)letter}; the next letter is {(char)(letter + 1)}");
// A raw string literal (C# 11) needs no escaping.
string json = """
{ "city": "Kraków", "path": "C:\data\new" }
""";
Console.WriteLine(json);
Console.WriteLine($"Length of \"Kraków\": {"Kraków".Length}");It prints:
'42' -> 84 when doubled
' 17 ' -> 34 when doubled
'4.5' is not a whole number
'forty-two' is not a whole number
'-3' -> -6 when doubled
(int)2.5 = 2, Math.Round(2.5) = 2, Math.Round(3.5) = 4
'C' is code 67; the next letter is D
{ "city": "Kraków", "path": "C:\data\new" }
Length of "Kraków": 6int.TryParse(text, out int value)returnstrueand setsvalueif the text is a whole number (surrounding spaces are allowed), and returnsfalseotherwise. Its siblingint.Parsethrows an exception on bad input. PreferTryParsewhenever bad input is expected, which is always when people type it. Theout int valuedeclares the variable right in the call.- Casting a
doubleto aninttruncates toward zero. To round, callMath.Round, and know that by default it rounds halves to the nearest even number ("banker's rounding"), so 2.5 becomes 2 and 3.5 becomes 4. PassMidpointRounding.AwayFromZeroif you want the school-book rule. - A
charis a 16-bit number.'C'is 67; adding 1 gives theint68, and casting back gives'D'. Most text fits onecharper letter, but some characters (many emoji, some rare Chinese characters) take twochars, soLengthcounts UTF-16 code units, not what a reader would call letters. - Strings are immutable. Methods such as
ToUpper,ReplaceandTrimreturn new strings. To build a long string piece by piece in a loop, useSystem.Text.StringBuilder, which does not copy everything at each step. - Three kinds of string literal. Ordinary strings use backslash escapes (
"\n"is a newline,"\""a quote). Verbatim strings, prefixed with@, take backslashes literally and are handy for Windows paths. Raw string literals (C# 11), delimited by three or more double quotes, take everything literally, including quotes; when they span lines, the indentation of the closing quotes is removed from every line. Any of them can be interpolated with a$in front.
Deciding and repeating
C#'s control-flow statements will look familiar from almost any language with curly braces: if and else, while, do-while, for, foreach, break and continue. Conditions must be bool: unlike C, if (count) does not compile when count is an int; write if (count != 0). The logical operators && and || short-circuit (the right side is evaluated only if needed), and cond ? a : b chooses between two values.
Here is a complete algorithm that uses most of them: the Luhn check, a simple checksum that bank card numbers and many identity numbers carry so that a mistyped digit is caught before anything is sent anywhere. Starting from the rightmost digit, double every second digit (subtracting 9 if the result exceeds 9), add everything up, and accept the number if the total is a multiple of 10.
// The Luhn check, used on bank card and many ID numbers to catch typing mistakes.
bool PassesLuhn(string number)
{
int sum = 0;
bool doubleIt = false;
for (int i = number.Length - 1; i >= 0; i--)
{
char c = number[i];
if (c == ' ') continue;
if (!char.IsAsciiDigit(c)) return false;
int digit = c - '0';
if (doubleIt)
{
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
doubleIt = !doubleIt;
}
return sum % 10 == 0;
}
string[] numbers = ["4539 1488 0343 6467", "4539 1488 0343 6476", "79927398713", "12a4"];
foreach (string n in numbers)
{
string verdict = PassesLuhn(n) ? "valid" : "invalid";
Console.WriteLine($"{n,-20} {verdict}");
}It prints:
4539 1488 0343 6467 valid
4539 1488 0343 6476 invalid
79927398713 valid
12a4 invalidNotice the second number: it is the first with two digits swapped, and the check catches it. Some details worth taking away:
- The loop counts down:
for (int i = number.Length - 1; i >= 0; i--). continueskips the rest of this pass of the loop (spaces are ignored);return falseleaves the whole function immediately.c - '0'turns a digit character into its value, because the digit characters'0'to'9'have consecutive codes.char.IsAsciiDigit(.NET 7) accepts only those ten characters; the olderchar.IsDigitalso accepts digits from other scripts, such as Arabic-Indic or Devanagari digits, whichc - '0'would turn into nonsense.- An
ifwith a single statement may omit its braces, as thecontinueline does. Many teams require braces everywhere anyway, because adding a second line to a brace-lessifis a classic bug.
Switch statements and switch expressions
A classic switch statement compares a value with constant case labels. C# does not let one case "fall through" into the next by accident: each section must end with break, return or another jump.
switch (dayNumber)
{
case 6:
case 7:
Console.WriteLine("weekend");
break;
default:
Console.WriteLine("weekday");
break;
}More common in modern code is the switch expression (C# 8), which produces a value. Combined with relational patterns (C# 9) it reads like a lookup table. The arms are tried from top to bottom, and _ matches anything:
// switch expressions with relational patterns (C# 9) read like a table.
string Advice(int uvIndex) => uvIndex switch
{
< 0 => throw new ArgumentOutOfRangeException(nameof(uvIndex)),
<= 2 => "low: no protection needed",
<= 5 => "moderate: hat and sunscreen",
<= 7 => "high: seek shade at midday",
<= 10 => "very high: avoid the midday sun",
_ => "extreme: stay indoors if you can",
};
int[] readings = [1, 4, 6, 9, 11];
foreach (int uv in readings)
{
Console.WriteLine($"UV {uv,2}: {Advice(uv)}");
}
// while and do-while
int n = 1_000_000;
int digits = 0;
while (n > 0)
{
n /= 10;
digits++;
}
Console.WriteLine($"1_000_000 has {digits} digits");
int attempts = 0;
do
{
attempts++;
} while (attempts < 0);
Console.WriteLine($"a do-while body runs at least once: {attempts}");
// Indices and ranges (C# 8)
string word = "Johannesburg";
Console.WriteLine($"{word[0]} ... {word[^1]}, first five: {word[..5]}, last four: {word[^4..]}");It prints:
UV 1: low: no protection needed
UV 4: moderate: hat and sunscreen
UV 6: high: seek shade at midday
UV 9: very high: avoid the midday sun
UV 11: extreme: stay indoors if you can
1_000_000 has 7 digits
a do-while body runs at least once: 1
J ... g, first five: Johan, last four: burgAdvice is written with =>, an expression body: a method whose whole body is one expression. A throw can appear as a switch arm, which is a neat way to reject impossible input. If no arm matches at run time, a switch expression throws, and the compiler warns you when it can see that some input is not covered. The lesson on pattern matching shows how far this goes.
Finally, indices and ranges: ^1 means "one from the end", so word[^1] is the last character, and a..b is a range from a up to but not including b, with either end optional. They work on strings, arrays, lists and spans.
Common misconceptions
Misconception
"double is fine for money if I round at the end." Errors in binary floating point accumulate across thousands of additions and show up as a cent missing from an invoice total. Use decimal for currency; it is slower, but correctness comes first.
Misconception
"If my numbers get too big, the program will crash and tell me." Not by default: int arithmetic wraps around silently. If overflow would be a bug, use long, use checked, or turn on overflow checking for the project. Many teams enable it in debug builds.
Misconception
"var makes C# dynamically typed." var only asks the compiler to work out the type it would have made you write. The variable's type is fixed at compile time. (C# does have a dynamic type, for interoperating with dynamic languages and COM, but it is rarely the right tool in new code.)
Misconception
"string.Length counts letters." It counts UTF-16 code units. "Kraków" has six and so does its Length, but an emoji such as a flag can be four code units long. For user-visible characters, look at System.Globalization.StringInfo or the EnumerateRunes method.
Exercises
Predict each answer before you run anything. When you check, run the code exactly as written.
1. Types, operators and control flow
Warm-upComputationalWhat does this line print?
Console.WriteLine(17 / 5 * 5 + 17 % 5);
2. Types, operators and control flow
CoreComputationalWhat does Console.WriteLine(-17 % 5); print?
3. Types, operators and control flow
Warm-upHumanA market stall app adds up the prices of items in a basket and prints a receipt. Which type should hold the prices?
4. Types, operators and control flow
CoreComputationalWhat does Console.WriteLine((int)-3.9); print?
5. Types, operators and control flow
CoreComputationalWhat does this program print?
string s = "Lumenary";
Console.WriteLine(s[^3..] + s[..2]);
6. Types, operators and control flow
CoreComputationalWhat does Console.WriteLine(Math.Round(0.5) + Math.Round(1.5)); print?
7. Types, operators and control flow
CoreComputationalWhat does this program print?
string Size(int grams) => grams switch
{
< 100 => "letter",
< 2000 => "small parcel",
< 20000 => "parcel",
_ => "freight",
};
Console.WriteLine($"{Size(99)}, {Size(100)}, {Size(20000)}");
8. Types, operators and control flow
StretchComputationalWhat does this program print?
int total = 0;
for (int i = 1; i <= 20; i++)
{
if (i % 3 == 0) continue;
if (i > 10) break;
total += i;
}
Console.WriteLine(total);
Further reading and resources
- Built-in types · MicrosoftThe table of every built-in type, its .NET name and its range.
- C# operators and expressions · MicrosoftEvery operator, with precedence and associativity.
- Selection statements · Microsoftif and switch in full detail.
- What Every Computer Scientist Should Know About Floating-Point Arithmetic · David Goldberg · 1991The classic explanation of why 0.1 + 0.2 is not 0.3 in binary floating point.