How To Write An Extension Method

  • OOP
You are currently viewing How To Write An Extension Method

How To Write An Extension Method

Extension methods are extremely useful and structurally necessary methods. With extension methods, a lot of flexibility can be provided in the project. The Extension Method is written for the classes that we do not want to make any changes but want to expand and add. In this way, we write a method for that class without making any changes to the class.

There are a few rules to consider when writing these methods:

  1. These methods must be defined as static.
  2. These methods must be defined in a static class.
  3. The class for which the Extension method will be written is specified after the this keyword in the first parameter of the method.

Let’s prove this with an example. In the example below, we wrote the Extension Method for the string class. The first method converts Turkish characters in a sentence to English characters and returns the converted string directly. The second method is removing the parts in the sentence according to the string parameter we give. We can access these methods through any string variable.

namespace ExtensionTest
{
    public static class StringExtension
    {
        public static string ChangeTurkishCharacters(this string text)
        {
            char[] turkishChars = new[] { 'ç', 'ğ', 'ı', 'ö', 'ş', 'ü', 'Ç', 'Ğ', 'İ', 'Ö', 'Ş', 'Ü' };
            char[] replacedChars = new[] { 'c', 'g', 'i', 'o', 's', 'u', 'C', 'G', 'I', 'O', 'S', 'U' };

            for (int index = 0; index < turkishChars.Length; index++)
            {
                text = text.Replace(turkishChars[index], replacedChars[index]);
            }

            return text;
        }
        
        public static string RemoveChars(this string text, string input)
        {
            text = text.Replace(input, "");
            return text;
        }
    }
    
    class Program
    {
        static void Main()
        {
            string text = "Üç sabah erken kalkan, bir gün kazanır.";
            Console.WriteLine(text);
            
            text = text.ChangeTurkishCharacters();
            Console.WriteLine(text);
            
            text = text.RemoveChars(" ");
            Console.WriteLine(text);
        }
    }
}

In the example, we are converting the Turkish characters of the sentence into English characters using an Extension Method. Then we remove all the spaces in the sentence with the help of an Extension Method. The output is as follows.

Üç sabah erken kalkan, bir gün kazanır.
Uc sabah erken kalkan, bir gun kazanir.
Ucsabaherkenkalkan,birgunkazanir.

As a result, we were able to extend the class from outside without adding anything to the string class. With this method, flexibility can be created in projects without causing complexity.

Leave a Reply