This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

Extension Method


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?

Extension methods are widely used in real-world applications for enhancing existing types, improving code readability, and making APIs more fluent and discoverable. 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. You can define an extension method by creating a static method in a static class, with the this keyword in the parameter list of the first parameter.

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

Extension Method in C#

Real-World Example

1.  LINQ Extension Methods

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.

Example - Filtering a Collection

Suppose you have a list of employees, and you want to filter out employees who are older than a certain age.

Extension Method in C#

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.

2. Extension Methods in ASP.NET Core

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.

Extension Method in C#
Prev Next