Master C# Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Advanced Features

Learn important advanced C# features including Exception Handling, Delegates, Events, Lambda Expressions, Extension Methods, and LINQ. These features are widely used in modern .NET and ASP.NET Core applications.

Module Objective: Understand how advanced C# features improve application reliability, flexibility, code reusability, and data processing.

1. Exception Handling

Exception handling is used to handle runtime errors in a program without terminating the application unexpectedly.

Simple Definition: An exception is an unexpected error that occurs while a program is running.

Why Do We Need Exception Handling?

  • Prevents application crashes.
  • Provides meaningful error messages.
  • Allows the application to continue safely.
  • Helps developers identify runtime problems.
  • Improves application reliability.

try-catch

The try block contains code that may generate an exception. The catch block handles the exception.

C#
using System;
 
try
{
    int a = 10;
    int b = 0;

    int result = a / b;

    Console.WriteLine(result);
}
catch (Exception ex)
{
    Console.WriteLine("An error occurred.");
}
Output
An error occurred.

Displaying Exception Message

C#
using System;
 
try
{
    int number = int.Parse("ABC");
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
Output
The input string 'ABC' was not in a correct format.

Multiple catch Blocks

Multiple catch blocks can be used to handle different types of exceptions separately.

C#
using System;
try
{
    int[] numbers = { 10, 20, 30 };

    Console.WriteLine(numbers[5]);
}
catch (IndexOutOfRangeException)
{
    Console.WriteLine("Invalid array index.");
}
catch (Exception)
{
    Console.WriteLine("Some other error occurred.");
}
Output
Invalid array index.

finally Block

The finally block executes whether an exception occurs or not. It is commonly used for cleanup operations.

C#
using System;
 
try
{
    Console.WriteLine("Try block executed.");
}
catch
{
    Console.WriteLine("Catch block executed.");
}
finally
{
    Console.WriteLine("Finally block executed.");
}
Output
Try block executed.
Finally block executed.

throw Keyword

The throw keyword is used to explicitly generate an exception.

C#
using System;
 
int age = 15;

if (age < 18)
{
    throw new Exception("Age must be 18 or above.");
}
CIIT Practical Point: Exception handling is essential in ASP.NET Core applications for handling database errors, API failures, validation errors, file operations, and unexpected runtime problems.

2. Delegates and Events

Delegates and events provide a mechanism for passing methods as values and creating event-driven applications.

What is a Delegate?

A delegate is a type-safe reference to a method. It can store a reference to a method and invoke that method later.

C#
using System;
 
delegate void MessageDelegate();

class Program
{
    static void ShowMessage()
    {
        Console.WriteLine("Welcome to C#");
    }

    static void Main()
    {
        MessageDelegate message = ShowMessage;

        message();
    }
}
Output
Welcome to C#

Delegate with Parameters

C#
using System;
 
delegate void CalculateDelegate(int a, int b);

class Program
{
    static void Add(int a, int b)
    {
        Console.WriteLine(a + b);
    }

    static void Main()
    {
        CalculateDelegate calculate = Add;

        calculate(10, 20);
    }
}
Output
30

What is an Event?

An event is used to notify other parts of an application when something happens.

Examples include button clicks, payment completion, order placement, and user registration.

Event Example

C#
using System;
 
class Order
{
    public event Action OrderPlaced;

    public void PlaceOrder()
    {
        Console.WriteLine("Order placed.");

        OrderPlaced?.Invoke();
    }
}

class Program
{
    static void Main()
    {
        Order order = new Order();

        order.OrderPlaced += SendNotification;

        order.PlaceOrder();
    }

    static void SendNotification()
    {
        Console.WriteLine("Notification sent.");
    }
}
Output
Order placed.
Notification sent.
CIIT Practical Point: Delegates and events are useful in event-driven systems, notification systems, UI applications, callbacks and application-level communication.

3. Lambda Expressions

Lambda expressions provide a short and readable syntax for writing anonymous functions.

Simple Definition: A lambda expression is a compact way of representing a method or function.

Lambda Syntax

C#
(parameters) => expression

Simple Lambda Example

C#
using System;
 
Func<int, int> square = number => number * number;

Console.WriteLine(square(5));
Output
25

Lambda with Multiple Parameters

C#
using System;
 
Func<int, int, int> add =
    (a, b) => a + b;

Console.WriteLine(add(10, 20));
Output
30

Lambda with List

C#
using System;
using System.Collections.Generic;

namespace ListExample
{
    class Program
    {
        static void Main()
        {
            List numbers =
                new List { 10, 20, 30, 40, 50 };

            numbers.ForEach(number =>
                Console.WriteLine(number));
        }
    }
}
Output
10
20
30
40
50
CIIT Practical Point: Lambda expressions are heavily used with LINQ, collections, filtering, sorting, searching and event handling in modern .NET applications.

4. Extension Methods

Extension methods allow developers to add new methods to an existing type without modifying the original type or creating a derived class.

Extension Method Syntax

An extension method is defined inside a static class. The first parameter uses the this keyword.

C#
public static class StringExtensions
{
    public static bool IsLong(this string text)
    {
        return text.Length > 5;
    }
}

Extension Method Example

C#
using System;
 
public static class StringExtensions
{
    public static bool IsLong(this string text)
    {
        return text.Length > 5;
    }
}

class Program
{
    static void Main()
    {
        string name = "Rahul";

        Console.WriteLine(name.IsLong());
    }
}
Output
False

Another Extension Method Example

C#
using System;
 
public static class NumberExtensions
{
    public static bool IsEven(this int number)
    {
        return number % 2 == 0;
    }
}

class Program
{
    static void Main()
    {
        int number = 20;

        Console.WriteLine(number.IsEven());
    }
}
Output
True
CIIT Practical Point: Extension methods are commonly used in .NET libraries and application utility classes to add reusable functionality to existing types.

5. LINQ

LINQ stands for Language Integrated Query. It provides a consistent way to query and manipulate data from collections, databases, XML and other data sources.

Simple Definition: LINQ allows us to filter, sort, search, group and transform data using readable C# syntax.

Why Do We Use LINQ?

  • Filter data easily.
  • Sort collections.
  • Search for records.
  • Select specific fields.
  • Group data.
  • Calculate values such as Sum and Average.
  • Write readable data-processing code.

Where() Method

Where() is used to filter data based on a condition.

C#
using System;
 
List<int> numbers =
    new List<int> { 10, 15, 20, 25, 30 };

var result = numbers.Where(n => n > 20);

foreach (int number in result)
{
    Console.WriteLine(number);
}
Output
25
30

Select() Method

Select() is used to transform or project each element.

C#
using System;
 
List<int> numbers =
    new List<int> { 1, 2, 3, 4, 5 };

var squares = numbers.Select(n => n * n);

foreach (int number in squares)
{
    Console.WriteLine(number);
}
Output
1
4
9
16
25

OrderBy()

OrderBy() sorts data in ascending order.

C#
using System;
 
List<int> numbers =
    new List<int> { 50, 20, 40, 10, 30 };

var result = numbers.OrderBy(n => n);

foreach (int number in result)
{
    Console.WriteLine(number);
}
Output
10
20
30
40
50

OrderByDescending()

C#
using System;
 
List<int> numbers =
    new List<int> { 10, 40, 20, 50, 30 };

var result = numbers.OrderByDescending(n => n);

foreach (int number in result)
{
    Console.WriteLine(number);
}
Output
50
40
30
20
10

First() and FirstOrDefault()

First() returns the first element of a collection. FirstOrDefault() returns the first element or the default value when no matching element exists.

C#
using System;
 
List<string> names =
    new List<string> { "Rahul", "Sneha", "Amit" };

string firstName = names.First();

Console.WriteLine(firstName);
Output
Rahul

Any() Method

Any() checks whether at least one element satisfies a specified condition.

C#
using System;
 
List<int> numbers =
    new List<int> { 10, 20, 30, 40 };

bool result = numbers.Any(n => n > 25);

Console.WriteLine(result);
Output
True

Count() Method

C#
using System;
 
List<int> numbers =
    new List<int> { 10, 20, 30, 40, 50 };

int count = numbers.Count();

Console.WriteLine(count);
Output
5

Sum() and Average()

C#
using System;
 
List<int> marks =
    new List<int> { 80, 90, 70, 85, 75 };

int total = marks.Sum();
double average = marks.Average();

Console.WriteLine("Total: " + total);
Console.WriteLine("Average: " + average);
Output
Total: 400
Average: 80

LINQ Method Summary

Method Purpose
Where() Filters data
Select() Transforms data
OrderBy() Sorts ascending
OrderByDescending() Sorts descending
First() Returns the first element
FirstOrDefault() Returns the first element or default
Any() Checks whether any element matches
Count() Counts elements
Sum() Calculates total
Average() Calculates average
CIIT Practical Point: LINQ is extensively used in .NET applications for processing collections, filtering database records, querying Entity Framework data and transforming application data.

Summary

In this module, you learned how to handle runtime errors using Exception Handling. You also learned how Delegates and Events are used for method references and event-driven programming.

Lambda Expressions provide a short and readable way to write functions, while Extension Methods allow developers to add functionality to existing types.

You also learned how LINQ can be used to filter, sort, search, transform, and process data from collections.

Understanding these advanced C# features is an important step toward developing modern and maintainable .NET and ASP.NET Core applications.

Practice Questions

  1. Create a program using try-catch for division by zero.
  2. Create a program using multiple catch blocks.
  3. Demonstrate the use of the finally block.
  4. Create a custom exception using the throw keyword.
  5. Create a delegate that accepts two integer parameters.
  6. Create an event for an order placement operation.
  7. Create a lambda expression to calculate the square of a number.
  8. Create a lambda expression to find the larger of two numbers.
  9. Create an extension method for checking whether a number is even.
  10. Use LINQ Where() to filter numbers greater than 50.
  11. Use LINQ Select() to calculate squares of numbers.
  12. Use OrderBy() and OrderByDescending() on a List.
  13. Use Any() to check whether a collection contains matching values.
  14. Use Sum() and Average() on student marks.
  15. Explain the difference between delegates and events.