What is Extension Method in C# and how to use them?

An extension method in C# allows you to add new methods to existing types, including types defined in the .NET Framework or your own custom types. Extension methods provide a way to extend the functionality of a type without modifying its original source code. They are defined as static methods but are called as if they were instance methods of the extended type.

Here’s an overview of how to define and use extension methods in C#:

  1. Definition:
    • An extension method is defined as a static method within a static class.
    • The class containing the extension method must be visible and accessible where you want to use the extension method.
    • The first parameter of the extension method specifies the type being extended, preceded by the this keyword.
  2. Usage:
    • To use an extension method, you need to import the namespace where the extension method is defined.
    • After importing the namespace, you can call the extension method on an instance of the extended type as if it were an instance method of that type.
    • The instance on which the extension method is called becomes the first parameter of the extension method.

Example usage of extension methods:

// Extension method class
public static class StringExtensions
{
    public static bool IsPalindrome(this string str)
    {
        // Implementation to check if a string is a palindrome
        // ...
    }
}

// Usage of extension method
string myString = "madam";
bool isPalindrome = myString.IsPalindrome();  // Calling the extension method

In this example, the StringExtensions class defines an extension method called IsPalindrome(). The extension method is defined for the string type, as indicated by the this keyword before the first parameter.

To use the extension method, the namespace containing the StringExtensions class must be imported. Once imported, the extension method can be called on an instance of the string type (myString in this case) as if it were a regular instance method.

Extension methods provide a way to add custom functionality to existing types without modifying their original source code. They are commonly used to augment the functionality of types in the .NET Framework or to add convenience methods to your own custom types.

It’s important to note that extension methods cannot access private members of the extended type and cannot override existing methods. They are only visible and accessible if the namespace where the extension methods are defined is imported.

error: Content is protected !!