C# Programming Tutorial: From Fundamentals to Advanced Application Development

4.48K 0 0 0 0

📘 Chapter 5: Advanced Topics in C#

🧠 Introduction

Now that you’ve learned the basics of C# syntax and object-oriented programming, it's time to explore advanced features that take your programming skills to the next level. These features enable you to write cleaner, more powerful, scalable, and high-performance C# applications.

In this chapter, you’ll learn:

  • Delegates and Events
  • LINQ (Language Integrated Query)
  • Anonymous Methods and Lambda Expressions
  • Generics
  • Asynchronous Programming with async/await
  • Nullable Reference Types and Pattern Matching

1. Delegates in C#

🔹 What is a Delegate?

A delegate is a type that represents references to methods with a particular parameter list and return type. Think of it as a function pointer or a type-safe callback mechanism.

Basic Delegate Example:

public delegate int Operation(int x, int y);

 

class Calculator

{

    public static int Add(int a, int b) => a + b;

}

 

class Program

{

    static void Main()

    {

        Operation op = new Operation(Calculator.Add);

        Console.WriteLine(op(5, 3)); // Output: 8

    }

}


📋 Delegate Syntax Summary

Keyword

Use

delegate

Declares a delegate type

new

Instantiates the delegate with a method

Invoke()

Calls the method (optional syntax)


📣 2. Events in C#

🔹 What is an Event?

An event in C# is a way for a class to provide notifications to clients when something happens. It is based on delegates.


Event Example:

public class Button

{

    public event Action Clicked;

 

    public void Click()

    {

        Clicked?.Invoke();

    }

}

 

class Program

{

    static void Main()

    {

        var button = new Button();

        button.Clicked += () => Console.WriteLine("Button clicked!");

        button.Click();  // Output: Button clicked!

    }

}


📋 Event vs Delegate

Feature

Delegate

Event

Definition

Function reference

Event notification system

Access

Can be directly invoked

Only publisher can invoke

Flexibility

More flexible

Safer encapsulation


🔍 3. Lambda Expressions & Anonymous Methods

🔹 Lambda Expressions

A concise way to write inline methods or delegates.

Func<int, int, int> multiply = (x, y) => x * y;

Console.WriteLine(multiply(4, 5));  // Output: 20


🔹 Anonymous Methods

Action greet = delegate { Console.WriteLine("Hello!"); };

greet();  // Output: Hello!


📋 Table: Lambda vs Anonymous Methods

Feature

Lambda

Anonymous Method

Syntax

(x) => x + 1

delegate (int x) { return x+1; }

Parameters

Inferred or declared

Explicit

Verbosity

More concise

More verbose


📊 4. Generics

🔹 What are Generics?

Generics allow you to define classes, methods, interfaces, and delegates with placeholders for the data type. They provide type safety and code reusability.


Generic List Example

List<string> names = new List<string>();

names.Add("Alice");


Generic Method

public T Max<T>(T a, T b) where T : IComparable<T>

{

    return a.CompareTo(b) > 0 ? a : b;

}


Generic Class

public class Box<T>

{

    public T Value { get; set; }

}


📋 Table: Built-in Generic Types

Generic Type

Description

List<T>

Dynamic array

Dictionary<K,V>

Key-value pair collection

Queue<T>

FIFO structure

Stack<T>

LIFO structure


📈 5. LINQ (Language Integrated Query)

LINQ allows querying objects, databases, XML, and collections using SQL-like syntax within C#.


LINQ Query Syntax

int[] numbers = { 1, 2, 3, 4, 5 };

 

var even = from n in numbers

           where n % 2 == 0

           select n;

 

foreach (var num in even)

    Console.WriteLine(num);  // Output: 2, 4


LINQ Method Syntax

var even = numbers.Where(n => n % 2 == 0).ToList();


📋 Common LINQ Methods

Method

Description

Where

Filter elements

Select

Transform elements

OrderBy

Sort elements

GroupBy

Group by a field

Sum, Count

Aggregate operations


️ 6. Asynchronous Programming

🔹 What is async/await?

Asynchronous programming allows execution of tasks without blocking the main thread.


Async Example

async Task DownloadAsync()

{

    await Task.Delay(1000);

    Console.WriteLine("Download complete.");

}

csharp

CopyEdit

await DownloadAsync();


📋 Table: Async Keywords

Keyword

Purpose

async

Declares asynchronous method

await

Suspends execution until task completes

Task<T>

Represents an async operation


Example: HTTP Call with HttpClient

using System.Net.Http;

 

async Task GetData()

{

    HttpClient client = new HttpClient();

    string data = await client.GetStringAsync("https://api.example.com");

    Console.WriteLine(data);

}


7. Pattern Matching

Pattern Matching improves conditional expressions by matching data structures or types directly.


is Pattern

object obj = "hello";

 

if (obj is string s)

{

    Console.WriteLine(s.ToUpper());  // Output: HELLO

}


switch Expression

string fruit = "apple";

 

string result = fruit switch

{

    "apple" => "Red",

    "banana" => "Yellow",

    _ => "Unknown"

};


Summary Table


Concept

Description

Delegate

Function pointer for type-safe callbacks

Event

Notification mechanism based on delegates

Lambda

Concise function expressions

Generics

Reusable code with type safety

LINQ

Query data using object-oriented syntax

Async/Await

Asynchronous code execution

Pattern Matching

Type-safe and clean conditional expressions

Back

FAQs


1. Q: Is C# easy to learn for beginners?

A: Yes, especially with Visual Studio and .NET’s extensive documentation and community support.

2. Q: Do I need to know C or C++ before learning C#?

A: Not at all. C# is independent and designed for new learners.

3. Q: Can I build web apps using C#?

A: Yes, using ASP.NET Core you can build scalable web apps and APIs.

4. Q: What’s the difference between C# and Java?

A: Both are similar syntactically, but C# is part of the Microsoft .NET ecosystem and often integrates better with Windows technologies.

5. Q: Is C# only for Windows development?

A: Not anymore. With .NET Core and .NET 8, C# is cross-platform.

6. Q: Is C# good for game development?

A: Absolutely. It is the main language used in Unity.

7. Q: Which IDE is best for C#?

A: Visual Studio is the most powerful and popular IDE for C# development.

8. Q: Can I use C# for mobile development?

 A: Yes, with Xamarin or .NET MAUI, C# can build cross-platform mobile apps.

9. Q: What is the future of C# in 2025 and beyond?

A: C# continues to evolve with modern features and has strong backing from Microsoft, making it future-proof.

10. Q: Do I need internet to use C# tools?

A: No, you can code, compile, and run C# locally, though some online libraries/tools may require internet.