In this article we are going to discuss about Extension Method with examples in C#.
What are Extension Methods in C#? When to use extension methods?
An Extension Method lets you add new methods to an existing type (class, struct, or interface) without modifying the original source code or creating a derived type. Whether you're using LINQ for querying collections or configuring middleware in ASP.NET Core, extension methods provide a powerful and flexible way to extend the functionality of existing types.
Extension methods allow you to add new methods to existing types without modifying their source code.
Static methods inside a static class.
The
first
parameter is preceded by the
this
keyword - it tells C# which type the method
extends.
Example
using System;
public static class StringExtensions
{
public static string CapitalizeFirstLetter(this string str)
{
if (string.IsNullOrEmpty(str))
{
return str;
}
return char.ToUpper(str[0]) + str.Substring(1);
}
}
public class Program
{
public static void Main()
{
string name = "rohatash";
string capitalized = name.CapitalizeFirstLetter();
Console.WriteLine(capitalized); // Output: Rohatash
}
}
Output
One of the most well-known uses of extension methods in the real world is LINQ (Language Integrated Query) in C#. LINQ provides a set of methods for querying collections, such as Where, Select, OrderBy, etc. These methods are implemented as extension methods on the IEnumerable<T> interface.
Suppose you have a list of employees, and you want to filter out employees who are older than a certain age.
In this example, Where is an extension method defined in the System.Linq namespace. It allows you to filter the List<Employee> based on a predicate.
In ASP.NET Core, extension methods are used extensively to configure services and the application pipeline. For example, configuring middleware in the Startup class uses extension methods like UseRouting and UseEndpoints.