Search This Blog

26 November, 2024

C# Intermediate Concepts: Collections, Exception Handling, and Beyond 🚀

C# Intermediate Concepts: Collections, Exception Handling, and Beyond 🚀

Welcome back, fellow coder! 🎉 You’ve mastered the basics of C#, and now it’s time to level up. In this article, we’ll explore intermediate concepts like collections, exception handling, and other essential tools that make your C# programs more powerful and flexible. Let’s dive in! 🏊‍♂️

Collections: Managing Groups of Data Like a Pro 📚

Think of collections as super-powered containers that help you manage and manipulate groups of items, like numbers, names, or even complex objects.

Lists: The Versatile Workhorse 🐴

A List<T> is a dynamic array that grows as needed. It’s perfect for managing a group of items.

Example: Managing a To-Do List 📝
using System; using System.Collections.Generic; class Program { static void Main() { List<string> toDoList = new List<string>(); // Add items toDoList.Add("Learn C#"); toDoList.Add("Write a blog post"); toDoList.Add("Conquer the world 🌍"); // Remove an item toDoList.Remove("Conquer the world 🌍"); // Iterate through the list Console.WriteLine("To-Do List:"); foreach (string item in toDoList) { Console.WriteLine($"- {item}"); } } }

Dictionaries: Key-Value Pair Magic 🔑

A Dictionary<TKey, TValue> lets you map keys to values, like a real-world dictionary.

Example: Tracking High Scores in a Game 🎮
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> highScores = new Dictionary<string, int> { { "Alice", 1500 }, { "Bob", 1200 }, { "Charlie", 2000 } }; // Access a value by key Console.WriteLine($"Alice's score: {highScores["Alice"]}"); // Add or update a key highScores["Diana"] = 1800; // Display all high scores Console.WriteLine("High Scores:"); foreach (var kvp in highScores) { Console.WriteLine($"{kvp.Key}: {kvp.Value}"); } } }

Other Handy Collections

  • Queue<T>: First-In-First-Out (FIFO) structure, like a line at a coffee shop. ☕
  • Stack<T>: Last-In-First-Out (LIFO), like a stack of plates. 🍽️
  • HashSet<T>: Stores unique items only, great for eliminating duplicates.

Exception Handling: Your Safety Net 🛡️

Errors are inevitable, but you don’t want your program to crash. Exception handling ensures your app can recover gracefully.

Try-Catch: Handling Errors Like a Pro

using System; class Program { static void Main() { try { Console.Write("Enter a number: "); int number = int.Parse(Console.ReadLine()); // May throw FormatException Console.WriteLine($"You entered: {number}"); } catch (FormatException) { Console.WriteLine("Oops! That’s not a valid number. 😅"); } catch (Exception ex) // Catch any other exceptions { Console.WriteLine($"Something went wrong: {ex.Message}"); } finally { Console.WriteLine("Thanks for using our app!"); } } }

Common Exceptions You’ll Encounter

  • FormatException: When parsing invalid input.
  • NullReferenceException: When trying to access an object that’s null.
  • IndexOutOfRangeException: Accessing an invalid index in an array or list.

LINQ: Data Filtering and Querying Made Easy 🧐

LINQ (Language Integrated Query) is a powerful way to work with collections, databases, and more using expressive syntax.

Example: Filtering and Sorting a List

using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new List<int> { 5, 3, 9, 1, 7, 4 }; // Use LINQ to filter and sort var evenNumbers = numbers .Where(n => n % 2 == 0) // Filter even numbers .OrderBy(n => n); // Sort ascending Console.WriteLine("Even numbers (sorted):"); foreach (var num in evenNumbers) { Console.WriteLine(num); } } }

Asynchronous Programming: Do More, Wait Less ⏱️

C#’s async and await keywords let you perform time-consuming tasks (like downloading data) without freezing your app.

Example: Simulating a Long Task

using System; using System.Threading.Tasks; class Program { static async Task Main() { Console.WriteLine("Starting task..."); await PerformLongTask(); // Non-blocking Console.WriteLine("Task completed!"); } static async Task PerformLongTask() { await Task.Delay(3000); // Simulate 3-second delay Console.WriteLine("Long task finished! ⏳"); } }

File Handling: Read and Write Data 📂

Files are everywhere, and C# makes it easy to read from or write to them.

Example: Writing and Reading a Text File

using System; using System.IO; class Program { static void Main() { string filePath = "example.txt"; // Write to a file File.WriteAllText(filePath, "Hello, C# World!"); // Read from the file string content = File.ReadAllText(filePath); Console.WriteLine($"File Content: {content}"); } }

Practice Makes Perfect: Mini Challenges 🏋️‍♂️

Test your skills with these:

  1. Shopping Cart: Create a List to store items, add/remove them, and display the total count.
  2. Error-Free Calculator: Build a calculator that handles invalid inputs gracefully.
  3. LINQ Explorer: Use LINQ to filter a list of products by price or category.

What’s Next?

Congratulations! 🎉 You’ve unlocked the power of collections, error handling, and more. You’re now ready to tackle advanced topics like:

  • Delegates and events
  • Generics
  • Working with APIs

Stay tuned for our next article, where we’ll dive into advanced features and create some truly exciting projects. 🚀