The Power of Extension Methods in C#

So one of the most underrated and unknown features of C# is what is know as Extension Methods.  “Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type,” straight from MSDN.  The following post will describe what these extension methods are, how to implement them, and when is the proper time to use these methods.

First off, Extension Methods are just as the name describes them: methods that are extension points off of existing classes.  The power of this is shown by the following example.  Say your team/company is using a physics engine API where all the classes are sealed (no inheritance is allowed).  Now as newer and faster algorithms come out, there is no need to throw away the whole API for the few changes.  Instead you can use Extension Methods to add these algorithms to their appropriate classes without having to modify the original code or subclass.

The actual syntax of Extension Methods can look scary and awkward at first.  Take the following example:

public static String ReverseSentence(this String str){
    String retval = "";
    String[] words = str.Split(' ');
    foreach (String word in words)
        retval = word + " " + retval;
    return retval;

The following shows how you can call this method on a String:

    String sentence = "This is an example of Extension Methods in C#";
    String reverseSentence = sentence.ReverseSentence();

This quick example just reverses the sentence. The first thing you may notice is that the method is static, however this method can be called on a String object itself. Also, there is a parameter in the method declaration (this String str), but nothing gets passed in when using the method. Even though you call this method on the instance variable, the compiler will generate it as a static call to ensure these extension methods do not have access to private variables in the extended class (which would be a huge security issue).

Frederik Kalseth shows a couple examples of extending DateTime class here.

I hope this was an informative tutorial and shows how powerful Extension Methods can be.  Feel free to leave comments and/or questions.


Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">