Wednesday, December 30, 2015

Extension Methods in C#

If you've ever used Extension methods in C# but don't really understand what they are about this post will hopefully help you understand them a bit and even how to create your own. If you haven't used them this should serve as a good foray into expanding your toolset.



Here's what I've learned:

Make a static class and add a static method (this is the extension method).

The extension method takes in the object it is extending as the first argument in the following format:

public static class BakerExtensions
{
    public static Cake MakeCake(this Baker baker)
    {
        //make that cake
    }
}

If we have a baker instance we would call the extension method as if it belonged to the Baker class.

Baker baker = new Baker();
Cake mmmCake = baker.MakeCake();

I recommend keeping your extension classes at a 1:1 ratio to the classes they are extending. If you have a Baker and a CandleStickMaker you should have a BakerExtensions and a CandleStickMakerExtensions class. This is not required, but it will help with organization.

You may also want to namespace your extension classes the same as the classes they extend, but if you do remember that the extensions will automatically be brought in with the class if it is in the same namespace. You could go with <original namespace>.Extensions if you want more control over when to bring them in and when not to, but it may end up adding confusion in the end.

So why on earth would you want to use extension methods? Why not create subclasses and just add the methods to those?

Ok, so let's say you have some existing code with the Baker class all over the place. You might have some subclasses already and you don't want to change the base class OR you want to add functionality to built-in types like string or int.

public static class StringExtensions
{
    public static string Shuffle(this string inputString)
    {
         //shuffle that string
    }
}


var shuffled = "something".Shuffle();

//shuffled  == "emogsinht"

It's a pretty neat way to keep in line with the Open/Closed Principle if you don't need to access instance members.

Word of caution: be careful about side effects when it comes to extensions. Side effects are a code smell in any case. Thogh it may be tempting to have them in extension methods, you should treat them just like you would if they we a normal class method.

There are a couple of drawbacks - You wouldn't get access to internal members of the class; and your extension methods won't be called if they have the same name and signature of a class method.

Here's an msdn article on the topic for more detail: https://msdn.microsoft.com/en-us/library/bb383977.aspx

No comments:

Post a Comment