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
44: Practice Exercise: Building Robust Input Validation
I've seen this a thousand times in code reviews for junior devs: a programmer uses int.Parse() or Convert.ToInt32() and assumes that because the variable should be a number, the code will just work. They think they've "handled" the input because they've converted the string to an integer.
Assuming Parse() is Safe
Here is the classic mistake. Imagine you're building a simple system to take a quantity for a customer's order:
Console.WriteLine("How many widgets would you like to buy?");
int quantity = int.Parse(Console.ReadLine());
Console.WriteLine($"You ordered {quantity} widgets!");
On paper, this is fine. But the second a user accidentally hits the 's' key instead of '5', or leaves the field blank and hits Enter, your entire application crashes with a FormatException. In a real production environment, crashing the app because of a typo is an absolute non-starter. You can't trust your users; they will provide the weirdest, most unexpected input you can possibly imagine.
Embracing TryParse() and Validation Loops
The correct way to handle this isn't to wrap everything in a giant try-catch block—that's expensive and messy. Instead, we use int.TryParse(). This method doesn't throw an exception; it returns a boolean telling you if the conversion worked, and it uses an out parameter to give you the resulting value.
But just calling TryParse once isn't enough. If the input is bad, you don't want the program to just move on with a default value of 0; you want to give the user a chance to fix it. I always use a while loop for this pattern:
int quantity;
bool isValid = false;
while (!isValid)
{
Console.WriteLine("Please enter the number of widgets (1-100):");
string input = Console.ReadLine();
if (int.TryParse(input, out quantity))
{
isValid = true;
}
else
{
Console.WriteLine("That wasn't a valid number. Please try again.");
}
}
Now, the program is "robust." It won't crash, and it refuses to proceed until it has a usable piece of data.
Beyond the Type Check: Range and Logic
Here is the second trap: thinking that "it's an integer" means "it's a valid value." If I'm ordering widgets, I can't order -500 of them. If I'm entering my age, I can't be 12,000 years old.
Validation isn't just about data types; it's about business logic. I recommend combining your type check and your range check into a single validation step. This keeps your loop clean and ensures the data is actually useful for the rest of your program.
int quantity;
bool isValid = false;
while (!isValid)
{
Console.Write("Enter quantity (1-100): ");
if (int.TryParse(Console.ReadLine(), out quantity) && quantity >= 1 && quantity <= 100)
{
isValid = true;
}
else
{
Console.WriteLine("Invalid entry. Please enter a whole number between 1 and 100.");
}
}
By chaining the TryParse with the range comparison using the && operator, we ensure that isValid only becomes true when the input is both a valid integer AND within our acceptable bounds. This is the foundation of professional-grade input handling.
📋 Practical Task
Exercise: The Warehouse Inventory Intake System
You are writing a console tool for a warehouse manager to log new shipments. The manager needs to enter three specific pieces of data, and the program must not proceed to the final summary until all three are validated correctly.
- Item ID: Must be a positive integer greater than 0.
- Quantity: Must be a positive integer between 1 and 10,000.
- Weight (kg): Must be a valid decimal/double between 0.1 and 500.0.
Requirements:
- Implement a
whileloop for each input to ensure the user is prompted repeatedly until they provide valid data. - Use
TryParse(eitherint.TryParseordouble.TryParse) to prevent the application from crashing on non-numeric input. - Provide a specific error message if the input is either the wrong type or outside the allowed range.
- Once all three are collected, print a final confirmation message:
"Shipment Logged: Item #[ID], Quantity: [Qty], Weight: [Weight]kg".
There are no comments for now.