BeginnerLesson 2 of 16
Variables & Data Types – C#
Numbers, text, booleans, var and conversions.
C# is statically typed: every variable has a fixed type that the compiler checks. With var you let the compiler infer the type – it stays fixed nonetheless.
string name = "Ada";
int alter = 36;
double groesse = 1.68;
decimal preis = 19.99m; // m suffix for decimal
bool aktiv = true;
char buchstabe = 'A';
var zahl = 42; // compiler infers int
const double Pi = 3.14159;
Console.WriteLine($"{name} is {alter} years old");
Console.WriteLine(zahl.GetType()); // System.Int32With string interpolation ($"...") you insert values directly into text. You convert numbers with int.Parse, int.TryParse or casts. Be careful when dividing integers:
Console.WriteLine(7 / 2); // 3 (int / int = int)
Console.WriteLine(7 / 2.0); // 3.5
Console.WriteLine(7 % 2); // 1
Console.WriteLine((double)7 / 2); // 3.5
Console.WriteLine(Math.Pow(2, 10)); // 1024
int n = int.Parse("42");
bool ok = int.TryParse("abc", out int wert);
Console.WriteLine($"{n} {ok} {wert}"); // 42 False 0
decimal betrag = 12.5m;
Console.WriteLine($"{betrag:F2}"); // 12.50Warning
int / int truncates the decimal places (7 / 2 = 3). For monetary amounts use decimal, not double – floating-point numbers are binary and do not calculate 0.1 + 0.2 exactly.Tip
int.TryParse does not throw an exception on invalid input but returns false – ideal for user input.