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.
1. Exception Handling
Exception handling is used to handle runtime errors in a program without terminating the application unexpectedly.
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.
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
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.
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.
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.
using System;
int age = 15;
if (age < 18)
{
throw new Exception("Age must be 18 or above.");
}
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.
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
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
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.
3. Lambda Expressions
Lambda expressions provide a short and readable syntax for writing anonymous functions.
Lambda Syntax
(parameters) => expression
Simple Lambda Example
using System;
Func<int, int> square = number => number * number;
Console.WriteLine(square(5));
Output
25
Lambda with Multiple Parameters
using System;
Func<int, int, int> add =
(a, b) => a + b;
Console.WriteLine(add(10, 20));
Output
30
Lambda with List
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
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.
public static class StringExtensions
{
public static bool IsLong(this string text)
{
return text.Length > 5;
}
}
Extension Method Example
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
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
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.
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.
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.
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.
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()
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.
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.
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
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()
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 |
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
- Create a program using try-catch for division by zero.
- Create a program using multiple catch blocks.
- Demonstrate the use of the finally block.
- Create a custom exception using the throw keyword.
- Create a delegate that accepts two integer parameters.
- Create an event for an order placement operation.
- Create a lambda expression to calculate the square of a number.
- Create a lambda expression to find the larger of two numbers.
- Create an extension method for checking whether a number is even.
- Use LINQ Where() to filter numbers greater than 50.
- Use LINQ Select() to calculate squares of numbers.
- Use OrderBy() and OrderByDescending() on a List.
- Use Any() to check whether a collection contains matching values.
- Use Sum() and Average() on student marks.
- Explain the difference between delegates and events.