What is extension method with example in c#


An extension method in C# allows you to add methods to existing types without modifying their source code or inheriting from them. These methods appear as if they were part of the original type. 

Here's an example of an extension method:

*** csharp code
using System;

public static class StringExtensions
{
    // Extension method to reverse a string
    public static string Reverse(this string input)
    {
        char[] charArray = input.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
}

class Program
{
    static void Main(string[] args)
    {
        string originalString = "hello";
        string reversedString = originalString.Reverse(); // Calling the extension method
        Console.WriteLine($"Original string: {originalString}"); // Output: Original string: hello
        Console.WriteLine($"Reversed string: {reversedString}"); // Output: Reversed string: olleh
    }
}
****

In this example:

- We define a static class `StringExtensions` to contain our extension method(s).
- The extension method `Reverse` is defined to operate on strings (`this string input`). This syntax indicates that `Reverse` is an extension method for the `string` type.
- Inside the `Reverse` method, we reverse the characters of the input string and return the result.
- In the `Main` method, we call the extension method `Reverse` on a string object `originalString`. This call appears as if the `Reverse` method is a member of the `string` class, even though it's actually defined in the `StringExtensions` class.

Extension methods are powerful tools for adding functionality to existing types, especially when you can't or don't want to modify the original source code. They're commonly used in C# to provide additional convenience methods for existing types or to integrate with third-party libraries.

Comments

Popular posts from this blog

What is hash table in c# and when we should use it

What is valuetuple in c# with example