What is an extension method?

_config.yml

Let’s keep it simple - Extension Methods Explained

Suppose I have a dog. A dog is a “type” of animal. All dogs – all animals of type dog - do certain things:

  1. Eat
  2. WagsTail
  3. Cries “Woof!”
  4. Shakes Paw etc

The things that a dog can do are all called “methods”.

Now let’s suppose the Great Programmer in OO Heaven forgot to add a method to the dog class. Let’s suppose you want all the dogs in your household to do something additional: FetchNewspaper.

You want to be able to say:

    rex.FetchNewspaper(); // or
    wolfie.FetchNewspaper(); // or
    beethoven.FetchNewspaper(); 

……even though you don’t have access to the source code. Wolfie, Rex and Beethoven are dogs in your pet household btw.

How are you doing to get your dog to do that?

You would have to recompile. But you don’t have the source code! If you don’t have the source code, then you can’t add the method to the relevant place in the code.

Your only solution is to to create an “extension method”.

Creating an Extension Method

 // (Note the “this” keyword in front of the first parameter below):

    public static void FetchNewsPaper(this Dog familyDog)
    {
         ConsoleWriteline(Goes to get newspaper!)
    }

And if you want your dog to get the newspaper simply do this:

    Dog freddie_the_family_dog = new Dog();
    freddie_the_family_dog.FetchNewspaper();

If you didn’t have extension methods then you wouldn’t be able to ask Freddie_the_family_dog to fetch newspapers.

What did we just do?

We added an additional method so that all dogs have the ability to fetch newspapers.

How does it work?

You simply: (i) call your dog, and (ii) tell him to fetch the paper. What you cannot do is say “Fetch a newspaper” without specifying which dog, in your family, should do the fetching.

I hope that helps you. If you still have questions post a comment and i’ll do my best to explain.

Written on January 13, 2017