// Value types (stored on stack)
int i = 42;
double d = 3.14159;
float f = 3.14f;
bool b = true;
char c = 'A';
decimal money = 99.99m; // use decimal for financial calculations!
long big = 9_999_999_999L;
// Reference types (stored on heap)
string name = "Alice";
string? nullable = null; // nullable reference type (C# 8+)
// var — type inference (compiler figures out the type)
var count = 10; // int
var pi = 3.14; // double
var greeting = "hello"; // string
// const and readonly
const int MaxRetries = 3; // compile-time constant
readonly int instanceMax; // set once in constructor
// String operations
string first = "Hello";
string combined = first + " World";
string interpolated = $"The answer is {42}";
string verbatim = @"C:\Users\Alice"; // no escape sequences
string multi = @"Line 1
Line 2
Line 3";
Console.WriteLine(name.Length); // 5
Console.WriteLine(name.ToUpper()); // ALICE
Console.WriteLine(name.Contains("li")); // True
Console.WriteLine(name.Replace("i", "I")); // AlIce
// Nullable value types
int? maybeNull = null;
int value = maybeNull ?? 0; // null-coalescing: use 0 if null
Console.WriteLine(value); // 0
C# distinguishes between value types (int, double, bool, struct) and reference types (class, string, arrays). Value types are copied on assignment; reference types share the same underlying data.
// Type conversion
int n = 42;
double d = n; // implicit widening
int back = (int)3.99; // explicit cast: truncates to 3
string s = n.ToString(); // int to string
int parsed = int.Parse("42"); // string to int (throws if invalid)
bool ok = int.TryParse("abc", out int result); // safe parse
Console.WriteLine(ok); // False
// Tuples (C# 7+)
(string name, int age) person = ("Alice", 30);
Console.WriteLine(person.name); // Alice
var (n2, a2) = person; // deconstruct
Console.WriteLine(n2); // Alice
⚠ Warning
Use decimal, not double, for money and financial calculations. double has floating-point precision issues: 0.1 + 0.2 != 0.3. decimal has more precision and exact decimal representation.