Tuesday, April 22, 2014

C# Extension Methods - When And How to Use Them

C# extension methods were added in .NET 3.0 as a way to extend a type without creating a new derived type.

From MSDN:

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

When would you want to use an extension method versus deriving from a class and using inheritance to create your own extension?

A popular reason to use an extension method is when you do not control the code for the type you want to extend. Examples would be extending a class provided by .NET or from a third party API.

Say, for example, you want to add functionality to the DateTime class. You could inherit from DateTime, creating a class MyDateTime. To call your methods, you would have to use MyDateTime and know when to use MyDateTime vs. DateTime. Another option is to extend the DateTime class, adding your methods. Now, every DateTime object used in your project will be able to use your extra functionality.

It is important to note, when using extension methods versus inheritance, you will not have access to protected or private members of the extended class. All extension methods are static.

Adding an extension method is very simple. First, determine where this should go in your project's organization. The extension methods should preferably live in a common area that all of your code can see, maybe in a helper file.

The silly example below shows how to set up the static extension method. Simply create a static method with a parameter of "this DateTime date". Any other parameters can follow.

    public static class DateTimeExtensions
        public static int GetMinutesPlusSeconds(this DateTime date)
            return date.Minute + date.Second;

Now I can call something like this anywhere in the code. Make sure to include the namespace of the helper method as Visual Studio might not pick up that you need an additional namespace.
    DateTime date = DateTime.Today;
    int sum = date.GetMinutesPlusSeconds();