C#
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented C#
-
Section 4: Working with Data
-
Section 5: Error Handling
-
Section 6: Delegates and Events
-
Section 7: Async Programming
-
Section 8: More Language Features
-
Section 9: File I/O and Serialization
-
Section 10: Networking in .NET
-
Section 11: The .NET Ecosystem
-
Section 12: Memory and Performance
-
Section 13: Concurrency Beyond Async
-
Section 14: Reflection and Attributes
-
Section 15: Testing and Best Practices
-
Section 16: Design Patterns in C#
-
Section 17: Standard Library Deep Dive
-
Section 18: Data Structures and Algorithms in C#
-
Section 19: GUI and Desktop Development Overview
-
Section 20: Practical Projects
-
Section 21: More Practice Exercises
-
Section 22: More Standard Library and Text Processing
-
Section 23: More Design Patterns
-
Section 24: More Projects
-
Section 25: Interview Practice
-
Section 26: C# Keywords Reference (Modifiers)
-
Section 27: C# Keywords Reference (Statements)
-
Section 28: C# Keywords Reference (Operators)
-
Section 29: BCL: System.Collections.Generic
-
Section 30: BCL: System.Linq
-
Section 31: BCL: System.Threading
-
Section 32: BCL: System.IO
-
Section 33: BCL: System.Text and System.Text.Json
-
Section 34: BCL: System.Net.Http
-
Section 35: C# Language Specification Topics
-
Section 36: More Practice Exercises
-
Section 37: More Async Patterns
-
Section 38: More BCL: System.Reflection and System.Diagnostics
-
Section 39: Nullable Reference Types In Depth
-
Section 40: C# Records and Pattern Matching In Depth
-
Section 41: Dependency Injection Deep Dive
-
Section 42: More Interview and Whiteboard Practice
114: The Math Class and Numeric Types
Think of handling numbers in C# like working in a high-end carpentry shop. You don't just have one "measuring tool." You have a rough tape measure for quick estimates, a precision caliper for engine parts, and a specialized jig for perfect 45-degree cuts. If you try to measure a microscopic screw with a chunky construction tape measure, you're going to have a bad time. The same thing happens in code; if you pick the wrong numeric type or try to do manual math when a specialized tool exists, you'll end up with "rounding drift" that can crash a program or lose a company money.
In C#, the "measuring tools" are your numeric types (like int, double, and decimal), and the "specialized jigs" are the static methods found in the System.Math class.
Picking the Right Tool for the Job
I see a lot of developers default to double for everything. I'll tell you right now: don't do that. A double is a "floating-point" number. It's incredibly fast and can handle massive ranges, but it's not perfectly precise. It's great for physics engines or scientific simulations where a tiny fraction of a difference doesn't matter.
But if you're dealing with money, use decimal. Period. The decimal type is slower, but it's designed for financial calculations where 0.1 + 0.2 must equal exactly 0.3. If you use double for a shopping cart, you'll eventually find a penny missing from your totals because of how binary floating-point math works under the hood.
double physicsDistance = 1234.56789; // Great for coordinates
decimal productPrice = 19.99m; // The 'm' suffix tells C# this is a decimal
int itemQuantity = 5; // Whole numbers only
Cleaning Up the Mess
In the real world, math is messy. You'll often end up with a number like 14.333333335, but your UI only has room for two decimal places. This is where the Math class comes in. It's a "static class," meaning you don't need to create an object to use it; you just call Math.MethodName().
You have three main ways to "trim" your numbers. Math.Round is the most common, but be careful—by default, it uses "Banker's Rounding" (rounding to the nearest even number). If you want the rounding you learned in grade school, you'll need to specify a MidpointRounding mode.
double rawValue = 12.5;
double rounded = Math.Round(rawValue, 0); // Might be 12 or 13 depending on the mode
double ceiling = Math.Ceiling(rawValue); // Always goes UP to 13
double floor = Math.Floor(rawValue); // Always goes DOWN to 12
I usually reach for Math.Ceiling when calculating pagination. If you have 51 items and 10 items per page, 51/10 is 5.1. You can't have 5.1 pages, and 5 pages would leave one item behind, so you "ceiling" it up to 6 pages.
The Heavy Lifters
Finally, there are the methods that save you from writing complex loops or importing huge libraries. Instead of multiplying a number by itself five times, use Math.Pow. Instead of guessing the side of a square from its area, use Math.Sqrt.
One of my favorites for game logic or UI layout is Math.Clamp (introduced in newer versions of .NET). It forces a number to stay between a minimum and a maximum value. It's way cleaner than writing a bunch of if statements to make sure a player's health doesn't go above 100 or below 0.
// Calculate the hypotenuse of a triangle (a^2 + b^2 = c^2)
double sideA = 3.0;
double sideB = 4.0;
double hypotenuse = Math.Sqrt(Math.Pow(sideA, 2) + Math.Pow(sideB, 2));
// Keep a volume slider between 0 and 100
int userSetting = 150;
int finalVolume = Math.Clamp(userSetting, 0, 100); // Result: 100
📋 Practical Task
Build a Precision Currency Converter
You are building a currency converter for a travel app. You need to handle a conversion where the exchange rate results in many decimal places, but the final output must be formatted for a bank statement.
Requirements:
- Create a
decimalvariable for theamountInUSD(e.g., 100.50). - Create a
decimalvariable for theexchangeRate(e.g., 0.923456). - Calculate the
totalInEURby multiplying the two. - Use
Math.Roundto round the final EUR result to exactly 2 decimal places usingMidpointRounding.AwayFromZero(this ensures .005 rounds UP to .01). - Print the raw result and the rounded result to the console to see the difference.
There are no comments for now.