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.
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.
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.
Let's create an example where we want to add a method that checks whether a string is a palindrome.
csharpusing 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
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.
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.
csharpclass Program { static void Main() { string word = "radar"; bool isPalindrome = word.IsPalindrome(); Console.WriteLine($"Is '{word}' a palindrome? {isPalindrome}"); } }
Following is the list that needs to be considered when we create an extension method.
Copyrights © 2024 letsupdateskills All rights reserved