Advanced C# Concepts
C# is a powerful and versatile programming language that offers a wide range of advanced features. Understanding these advanced concepts can significantly enhance your ability to write efficient, scalable, and maintainable code. This guide will explore four key advanced C# concepts: Generics, Delegates and Events, LINQ, and Asynchronous Programming.
1. Generics
Generics allow you to create classes, methods, and interfaces that can work with any data type. This promotes code reuse and type safety. By using generics, you can write flexible and reusable code without sacrificing type checking.
Example
class GenericList<T> { private List<T> items = new List<T>(); public void Add(T item) { items.Add(item); } public T Get(int index) { return items[index]; } } class Program { static void Main() { GenericList<int> intList = new GenericList<int>(); intList.Add(10); intList.Add(20); Console.WriteLine(intList.Get(0)); // Output: 10 Console.WriteLine(intList.Get(1)); // Output: 20 } }
In this example, the GenericList<T>
class can store and retrieve items of any type. The T
parameter allows the class to be used with different data types, such as integers or strings.
2. Delegates and Events
Delegates and events are essential for implementing the observer pattern in C#. Delegates are type-safe function pointers that can reference methods, while events allow objects to notify other objects when something happens.
Example
delegate void Notify(string message); class Publisher { public event Notify OnPublish; public void Publish(string message) { OnPublish?.Invoke(message); } } class Subscriber { public void HandleNotification(string message) { Console.WriteLine("Received: " + message); } } class Program { static void Main() { Publisher publisher = new Publisher(); Subscriber subscriber = new Subscriber(); publisher.OnPublish += subscriber.HandleNotification; publisher.Publish("Hello, World!"); // Output: Received: Hello, World! } }
In this example, the Publisher
class raises an event when it publishes a message. The Subscriber
class handles the event by printing the message to the console.
3. LINQ (Language Integrated Query)
LINQ provides a consistent query syntax for querying data from different data sources, such as collections, databases, and XML. It allows you to write expressive and readable queries in C#.
Example
class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; var evenNumbers = from num in numbers where num % 2 == 0 select num; foreach (var num in evenNumbers) { Console.WriteLine(num); // Output: 2 4 } } }
In this example, LINQ is used to query a list of numbers and select only the even numbers. The query syntax is concise and easy to understand.
4. Asynchronous Programming
Asynchronous programming allows you to perform long-running tasks without blocking the main thread. This is particularly useful for improving the responsiveness of applications, such as web servers and user interfaces.
Example
class Program { static async Task Main() { Console.WriteLine("Starting long operation..."); await LongOperationAsync(); Console.WriteLine("Long operation completed."); } static async Task LongOperationAsync() { await Task.Delay(2000); // Simulate a long-running task Console.WriteLine("Long operation in progress..."); } }
In this example, the LongOperationAsync
method simulates a long-running task using Task.Delay
. The await
keyword allows the method to run asynchronously without blocking the main thread.