Introduction To Extension Methods in C#

Extension methods allow you to extend the functionality of an existing class without using inheritance.

For example, suppose you were implementing a system which allowed users to post comments on a web site but you wanted to disallow swear words or other offensive content.

You could write a SwearChecker class (static or otherwise) or you could enable the same functionality by adding an extension method to the String class.

An extension method is defined a static method within a static class. The keyword this is used before the first method parameter and signifies the type that is being extended.

The following defines an extension method for String.


public static class OffensiveStringExtensions
{

    public static bool IsOffensive(this string stringToCheck)
    {
        // define list of offensive words (real swear words omitted...)
        List<string> offensiveWords = new List<string> {"darn", "damn", "blast"};

        foreach (var offesiveWord in offensiveWords)
        {
            // A real implementation may need to handle uppercase, localisation, etc.
            if (stringToCheck.Contains(offesiveWord))
                return true;
        }

        // no offensive words found
        return false;
    }

}


The extension method is called just as if it were a member of the type itself:

string wordsToCheck = "This is darn offensive!";
if (wordsToCheck.IsOffensive())

    //.... perform some logic ....


MSDN states: "In general, we recommend that you implement extension methods sparingly and only when you have to. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type."

We cannot inherit from String because it is sealed, so an extension method is one way of adding this functionality to all strings.

Some things to note when using extension methods:

  • If an extension method has the same signature as an instance method, the instance method will be used and the extension method will never be called;
  • The extension method can't access private members of the type it is extending;

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Add comment

Loading