Extension Method in Csharp

In c#, extension methods are features that allow developers to add new methods in the existing type without modifying the other type or source code. This feature is only useful for enhancing the classes in the .NET framework or any other library where you can not change the original implementation.

In this article, we will cover the fundamentals of extension methods, how to create and use them, and the best examples to keep in mind.

What Are Extension Methods?

Extension methods are a special type of static method that can be called as if they were instance methods on the type being extended. They are defined in static classes and use the 'this' keyword to specify the type they extend.

Why Use Extension Methods?

  1. Readability: They allow for a more natural, fluent syntax.
  2. Separation of Concerns: You can extend functionality without modifying the original class.
  3. Code Reusability: Common methods can be reused across different classes without inheritance.

How to create an extension method?

To create an extension method, we define a static method inside a static class. The first parameter of the method should be the type we want to extend, prefixed with the "this" keyword.

Example

Let's create an example where we want to add a method that checks whether a string is a palindrome.

csharp
using System; public static class StringExtensions { // Create an extension method public static bool IsPalindrome(this string str) { if (string.IsNullOrEmpty(str)) return false; int left = 0; int right = str.Length - 1; while (left < right) { if (str[left] != str[right]) return false; left++; right--; } return true; } } // using extension method class Program { static void Main() { string word = "radar"; // extension method bool isPalindrome = word.IsPalindrome(); Console.WriteLine($"Is '{word}' a palindrome? {isPalindrome}"); } }

Output

Is 'radar' a palindrome? True

Explanation

In the above code, there is a class which is String Extension, it is a static class that contains our extension method. Then we create a static method, IsPalindrome that extends the String type. Then we used this keyword: "this" The string str parameter indicates that this method can be called on any string object.

How to invoke the extension method?

Like any normal method, extension methods are invoked using the dot operator. Once you've defined an extension method, we can use it as if it were a regular instance method.

csharp
class Program { static void Main() { string word = "radar"; bool isPalindrome = word.IsPalindrome(); Console.WriteLine($"Is '{word}' a palindrome? {isPalindrome}"); } }

Important Notes:

Following is the list that needs to be considered when we create an extension method.

  • Namespace: Ensure that the namespace of your static class includes the file where you want to use the extension method. Otherwise, he won’t be considered.
  • Method Overloading: Extension methods can be overloaded, but be careful as they can create ambiguity in some cases.
  • Naming Conflict: If the extension method has the same name as the existing instance method, the instance method will take precedence.
  • Performance: Extension methods do not generate additional overhead beyond regular method calls, but avoid using them excessively in performance-critical code.
line

Copyrights © 2024 letsupdateskills All rights reserved