Extension Methods allow you to extend existing types by adding methods to them. The extension methods are special static methods and they are called the same way as type’s instance methods. In this example we will implement an extension method called IsPalindrome which extends strings and you can check them if they are palindrome. After that you can use the IsPalindrome() method just like any string method, for example Trim().

First of all you have to create a new static class that will contain the static method (extension method) and will have to be visible to the client code. The method needs to have at least the same visibility as the class. The method with the code should be something like this:

public static class ExtensionMethods
    public static bool IsPalindrome(this String strIn)
        for (int i = 0; i < strIn.Length / 2; i++)
            if (strIn[i] != strIn[strIn.Length - i - 1])
                return false;
        return true;

The only difference in the syntax between normal static methods and extension methods is the word “this” in the arguments. If you have added the class to the same namespace or use the new namespace to your client code, then you will see this method in your string objects. This method return true if the given string is palindrome and false if not. An example how to use this extension method:

string testString = "asdrdsa";

    //String is palindrome - This will be executed
    //String is not palindrome

If you noticed, there is no argument when we call the IsPalindrome method. The argument in the static method is the object that calls the method, our string. The given method will fail with phrases that have commas and dots and it is case sensitive. You can use it as a base and change it to meet your needs.

Enjoy programmers, if you have any questions you can leave a comment.

C# – Extension Methods – IsPalindrome

Leave a Reply

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