Extension Methods

Extension methods are methods that add functionality to .NET types or types that you have defined. For example, you can extend the System.String class by adding a Reverse method that reverses the string. The following program shows an example of an extension method.

using System;

namespace ExtensionMethodsDemo
{
    public static class StringExtender                                   
    {                                                                    
        public static string Reverse(this string myString)               
        {                                                                
            char[] reverse = new char[myString.Length];                  
                                                                         
            for (int i = myString.Length - 1, j = 0; i >= 0; i--, j++)   
            {                                                            
                reverse[j] = myString[i];                                
            }                                                            
                                                                         
            string returnString = new string(reverse);                   
                                                                         
            return returnString;                                         
        }                                                                
    }                                                                    

    public class Program
    {
        public static void Main()
        {
            string myMessage = "This message will be reversed.";

            Console.WriteLine(myMessage);
            Console.WriteLine(myMessage.Reverse());
        }
    }
}

Example 1 – Extention Methods Demo

This message will be reversed.
.desrever eb lliw egassem sihT

To define an extension method, you first need to create a static class that will hold the extension method. You must import the necessary namespace for the type that you want to extend. Inside the static class, we defined the extension method. Extension methods must also be static, can have any return type, and can possess any number of parameters just like any function. But extension methods follow a different syntax.

public static returnType methodName(this type name, param1 ... paramN)
{
 method codes...
}

As you can see inside the parameters list, we first used the this keyword then the type (such as string) that we want to extend followed by an instance name. This will hold the instance of that type so that we can used it inside our method for manipulation. We then followed them by a comma-separated list of parameters. The extension method we defined in Figure 1 needs no parameters. You can now create strings in your program and use the Reverse method. Note that extension methods are useful if you want to extend predefined types and classes from the .NET Framework. You can also use it on your custom class, but it would be better to just add the method to the class itself.

Inside the method, we declared a character array and assigned the value of the string message. We used the ToCharArray() method to convert the string into a series of characters. We do this so that we can modify each of the characters of the message. We used a for loop that will iterate the character array from the beginning and the message from the last position. The last character of the string was assigned to the first position of the character array. The second to the last character of string is assigned to the second position of the character array and so on. Since the return type of the extension method is string, we need to convert the character array back to a string. We do this by creating a new instance of the string and use its constructor that accepts a character array. We then return the converted reversed string back to the caller.

To give you an example of an extension method that has parameters, let’s modify our extension method in figure one so that it will accept a boolean value that will determine whether to retain the casing of the string message.

using System;

namespace ExtensionMethodsDemo2
{
    public static class StringExtender
    {
        public static string Reverse(this string myString, bool retainCase)
        {
            char[] reverse = myString.ToCharArray();

            for (int i = myString.Length - 1, j = 0; i >= 0; i--, j++)
            {
                reverse[j] = myString[i];
            }

            string returnString = new string(reverse);

            if (retainCase == false)
            {
                returnString = returnString.ToLower();
            }

            return returnString;
        }
    }

    public class Program
    {
        public static void Main()
        {
            string myMessage = "THIS MESSAGE WILL BE REVERSED.";

            Console.WriteLine(myMessage);
            Console.WriteLine(myMessage.Reverse(false));

        }
    }
}

Example 2 – Parameterized Extention Methods

THIS MESSAGE WILL BE REVERSED.
.desrever eb lliw egassem siht

We added a boolean parameter that will determine if the reversed message will retain the casing of the original message. We added an if statement that will use the parameter to determine whether to retain the casing of the reversed message. The ToLower() method of the System.String class converts all the characters into its lowercase representation. The returned converted string is then assigned to the variable that will be returned by the extension method.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *