Lesson 7/30

Tutorials C# Mastery

The Precision of Numbers: Checked vs Unchecked Math

On this page

The Precision of Numbers

In high-frequency systems, math isn't just about addition; it's about Precision and Overflow. If you add 1 to the largest possible int, C# will "Wrap Around" to a massive negative number without telling you. This silent bug can destroy financial or healthcare systems.

1. Integral Types: From SByte to ULong

Choosing the right size matters. A byte (0-255) consumes a fraction of the memory of a long.

Type Bytes Range Example
byte10 to 255
short2+/- 32,000
int4+/- 2 Billion
long8Astronomical

2. The "Checked" Keyword (Safety First)

By default, C# math is Unchecked. If you want a crash (OverflowException) instead of a silent wrap-around, you must use the checked block.

int val = int.MaxValue;

// ❌ SILENT BUG: becomes -2,147,483,648
val = val + 1; 

// ✅ THROWS EXCEPTION: Your app crashes safely so you can fix the logic!
checked 
{
    val = val + 1; 
}

3. Floating Point vs Decimal

NEVER use double for money. Double uses binary approximation and suffers from "Rounding Errors." Always use decimal for precision-critical data.

double d = 0.1 + 0.2; // Might result in 0.30000000000004
decimal m = 0.1m + 0.2m; // Exactly 0.3m

4. Interview Mastery

Q: "Why is decimal slower than double or float if it's more accurate?"

Architect Answer: "Float and Double are 'Native' types. Modern CPUs have physical circuits (FPUs) designed specifically to do binary floating-point math at the speed of light. `Decimal`, on the other hand, is not a native CPU type; it is a 128-bit structure managed by the C# runtime. Every addition or multiplication on a decimal requires several CPU operations and manual normalization by the CLR. We trade incredible raw speed for absolute decimal precision, which is non-negotiable in financial engineering."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

C# Mastery
Course syllabus
1. Modern C# & Framework Fundamentals
2. Control Flow & Logical Structures
3. Object-Oriented Mastery
4. Functional C# & Collections
5. Asynchronous & Parallel Programming
6. Advanced Engineering & High Performance
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details