Welcome to the final stage of your C# journey! 🎉 You’ve learned the basics, tackled intermediate concepts, and now it’s time to master advanced features. In this article, we’ll:
- Explore delegates, events, and generics.
- Harness the power of APIs.
- Build two exciting projects to put your skills into action.
Let’s dive into the deep end! 🏊♂️
Delegates and Events: The Backbone of Flexibility 🎛️
Delegates and events are like the magic wands of C#. They let you pass behavior (methods) as arguments and respond to actions dynamically.
Delegates: Passing Methods Around
A delegate is a reference to a method, allowing you to store and pass methods like variables.
Example: Custom Calculator
using System;
class Program
{
delegate int MathOperation(int a, int b);
static void Main()
{
MathOperation add = (x, y) => x + y; // Lambda for addition
MathOperation multiply = (x, y) => x * y; // Lambda for multiplication
Console.WriteLine($"Sum: {add(5, 3)}");
Console.WriteLine($"Product: {multiply(5, 3)}");
}
}
Events: Notifying When Something Happens
Events allow objects to notify others when something of interest occurs.
Example: Alarm Clock
using System;
class Alarm
{
public event Action AlarmRang;
public void Ring()
{
Console.WriteLine("⏰ Alarm is ringing!");
AlarmRang?.Invoke(); // Notify subscribers
}
}
class Program
{
static void Main()
{
Alarm myAlarm = new Alarm();
myAlarm.AlarmRang += () => Console.WriteLine("Wake up! 🌞");
myAlarm.AlarmRang += () => Console.WriteLine("Time to start coding! 🖥️");
myAlarm.Ring();
}
}
Generics: Type-Safe Flexibility 📦
Generics allow you to write reusable code that works with any type, ensuring type safety.
Example: Custom Stack Implementation
using System;
class CustomStack<T>
{
private T[] items = new T[10];
private int index = 0;
public void Push(T item) => items[index++] = item;
public T Pop() => items[--index];
}
class Program
{
static void Main()
{
CustomStack<int> numberStack = new CustomStack<int>();
numberStack.Push(10);
numberStack.Push(20);
Console.WriteLine(numberStack.Pop()); // Outputs 20
Console.WriteLine(numberStack.Pop()); // Outputs 10
}
}
Working with APIs: Connecting to the World 🌐
APIs let your application interact with the world, from fetching weather data to posting tweets.
Example: Fetching Data from a REST API
Using HttpClient
to fetch data from a public API:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string url = "https://api.agify.io?name=michael";
using HttpClient client = new HttpClient();
string response = await client.GetStringAsync(url);
Console.WriteLine($"API Response: {response}");
}
}
🧙♂️ Pro Tip: Use libraries like Newtonsoft.Json or System.Text.Json to parse JSON responses.
Advanced C# Projects 🛠️
Now, let’s combine these advanced features into two exciting projects. 🚀
Project 1: Event-Driven Stock Tracker 📈
Build a stock tracker that alerts users when the price of a stock goes above a certain threshold.
Code Example:
using System;
using System.Collections.Generic;
class Stock
{
public string Name { get; set; }
public decimal Price { get; set; }
public event Action<Stock> PriceThresholdReached;
public void UpdatePrice(decimal newPrice)
{
Price = newPrice;
Console.WriteLine($"{Name} new price: ${Price}");
if (Price > 100) // Threshold
{
PriceThresholdReached?.Invoke(this);
}
}
}
class Program
{
static void Main()
{
Stock stock = new Stock { Name = "TechCorp", Price = 90 };
stock.PriceThresholdReached += (s) =>
{
Console.WriteLine($"Alert! {s.Name} price exceeded $100! 🚨");
};
stock.UpdatePrice(105); // Triggers the event
}
}
Project 2: API-Based Weather App 🌤️
Let’s create a console app that fetches weather data using a weather API.
Code Example:
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string city = "London";
string apiKey = "your_api_key_here"; // Replace with a real API key
string url = $"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={apiKey}&units=metric";
using HttpClient client = new HttpClient();
string response = await client.GetStringAsync(url);
var weatherData = JsonSerializer.Deserialize<WeatherResponse>(response);
Console.WriteLine($"The weather in {city} is {weatherData.Main.Temp}°C with {weatherData.Weather[0].Description}.");
}
}
class WeatherResponse
{
public WeatherMain Main { get; set; }
public Weather[] Weather { get; set; }
}
class WeatherMain
{
public float Temp { get; set; }
}
class Weather
{
public string Description { get; set; }
}
👩💻 Next Steps:
- Get a free API key from OpenWeather.
- Replace
your_api_key_here
in the code with the real key.
Tips for Mastering Advanced C# 🏋️♂️
- Read the Documentation: The official C# docs are a treasure trove.
- Contribute to Open Source: Gain experience by contributing to projects on GitHub.
- Experiment Boldly: Build fun projects like chatbots, games, or automation tools.
Wrapping Up: You’re a C# Master Now! 🏆
Congratulations on completing this series! 🎉 You’ve traveled from C# basics to advanced features, building real-world projects along the way. The possibilities are endless from here:
- Dive into .NET Core for web development.
- Build mobile apps with Xamarin or .NET MAUI.
- Try game development with Unity.
👩💻 Your next challenge: Create your own advanced project and share it with the world!