Lesson 5 — Types
Data Types
C# has a rich type system including the critical decimal type for financial precision. Choosing the right type prevents silent bugs in production systems.
CSHARP — Numeric types
// INTEGERS:
byte b = 255;
short s = 32_000;
int i = 2_000_000; // most common
long l = 9_876_543_210L;
// FLOATING-POINT:
float f = 3.14f; // 7 decimal digits — use only when forced
double d = 3.14159265; // 15-16 digits — general purpose
// EXACT DECIMAL — for financial data:
decimal price = 1_299.99m; // 28-29 significant digits
decimal vatRate = 0.15m;
decimal total = price * (1 + vatRate);
Console.WriteLine($"Total: R{total:F2}"); // R1 494,99
// WHY decimal matters:
double wrong = 0.1 + 0.2;
Console.WriteLine(wrong); // 0.30000000000000004
decimal right = 0.1m + 0.2m;
Console.WriteLine(right); // 0.3
Reference Types
CSHARP — String operations
// string is immutable — operations return new strings
string name = "Thandi";
string upper = name.ToUpper(); // new string — name unchanged
Console.WriteLine($"{name} / {upper}");
Console.WriteLine(name.Length);
Console.WriteLine(name.Contains("han"));
Console.WriteLine(name.Replace("Th", "L")); // Landi
Console.WriteLine(string.IsNullOrWhiteSpace(" ")); // True
Type Conversion
CSHARP — Conversion
// Implicit (widening — no data loss):
int n = 42;
double d = n; // int → double: safe
// Explicit cast (may lose data):
double avg = 74.8;
int floor = (int) avg; // 74 — truncated
// TryParse — safe, no exception on bad input:
if (int.TryParse("abc", out int result))
Console.WriteLine(result);
else
Console.WriteLine("Not a valid integer.");
// Parse — throws FormatException on bad input:
int parsed = int.Parse("100");
Practice Task
Your Turn
Store a product price as decimal, quantity as int, and discount percentage as decimal. Calculate total = price × quantity × (1 − discount/100). Print formatted to 2 decimal places. Use int.TryParse on the string "abc" and print whether it succeeded.
Common Mistakes
- Using
doublefor money — always usedecimal. - Forgetting the
msuffix on decimal literals —decimal d = 3.14;is a compile error. - Forgetting the
fsuffix on float literals. - Using
Parse()without try-catch — useTryParsefor user input.
Professional Tip
For any monetary value in a South African business application, use decimal. A rounding error of one cent across millions of transactions is a real financial problem.
Mini Quiz
Which C# type should you use for financial amounts?
decimal uses base-10 arithmetic and avoids binary floating-point rounding errors that affect float and double.