You are on page 1of 2

Certainly, let's delve into a few more advanced topics in C#:

1. **Generics**: Generics allow you to create classes, interfaces, and methods that
operate with any data type. They provide type safety and code reusability by
enabling you to write flexible and efficient code. Here's an example of a generic
class:

```csharp
public class Stack<T> {
private T[] items;
private int top;

public Stack(int size) {


items = new T[size];
top = -1;
}

public void Push(T item) {


items[++top] = item;
}

public T Pop() {
return items[top--];
}
}
```

2. **Delegates and Events**: Delegates are type-safe function pointers that allow
you to pass methods as parameters or return values. Events are a special type of
delegate that enable the implementation of the observer design pattern. Here's an
example:

```csharp
public delegate void EventHandler(string message);

public class Publisher {


public event EventHandler OnMessageSent;

public void SendMessage(string message) {


OnMessageSent?.Invoke(message);
}
}

public class Subscriber {


public void HandleMessage(string message) {
Console.WriteLine("Received message: " + message);
}
}

// Usage
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();

publisher.OnMessageSent += subscriber.HandleMessage;
publisher.SendMessage("Hello, world!");
```

3. **LINQ (Language Integrated Query)**: LINQ provides a powerful and concise way
to query and manipulate data in C#. It allows you to query collections, databases,
XML, and other data sources using a consistent syntax. Here's an example of LINQ
querying a collection:

```csharp
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
}
```

4. **Async/Await**: Asynchronous programming allows you to perform time-consuming


operations without blocking the main thread of execution. Async/Await is a pair of
keywords introduced in C# 5.0 that simplify asynchronous programming by making it
look like synchronous code. Here's an example:

```csharp
public async Task<string> DownloadDataAsync(string url) {
using (HttpClient client = new HttpClient()) {
return await client.GetStringAsync(url);
}
}
```

These advanced topics in C# provide you with powerful tools to write efficient,
flexible, and maintainable code. As you become more familiar with these concepts,
you'll be better equipped to tackle complex programming tasks and build high-
quality software applications.

You might also like