Understanding Extension Methods in .Net

>>> Article has moved to codingsonata.com

Did you know that you can extend the functionality of any class or type from the .Net framework or any external library without having to obtain the source code?

Yes, this is doable. You can write methods that extend the existing functionality and call these methods as if they are part of the framework or the external library. The same also applies for your own classes.

This is the power of .Net extension methods.

Extension methods is a very useful feature that was added in .Net framework 3.0 that gives the developer the ability to add or extend methods to existing types without creating a new derived type, recompiling, or modifying the original type.

Once you write an extension method you can call it as if it was an instance method of the existing type.

extension3

In this article we will be discussing the extension methods with a sample C# code that illustrates the way to implement it in code and then we will blend the extension methods with generics to show the ultimate usage of such extensiblity feature in .Net, we will also take a look at the open source libraries of extension methods on the web.

Structure of an Extension Method

  • An extension method must be defined in a static class.
  • An extension method can be either void or have a return type.
  • An extension method must include at least one argument with which it must be identical to the type of the class that it will be extending. (I.e. if you are writing an extension method within the String type, then the first parameter in that extension method must be of type String), and must be prefixed with this keyword.
  • To use the extension method, you must import the namespace under which the extension method is defined.
  • You can use the extension method to overload existing methods.
  • Extension methods do accept generic types.

There are 2 important notes regarding the extension methods:

  • You cannot define an extension property, field, or event.
  • Extension methods cannot be used to override existing methods.

Extension Method Example in C#

To illustrate more about the usage of the extension methods in .net, an easy example for an extension method that can be used with String object, is a Reverse string extension method, this will return the string in reversed mode, check the below code in C#:

using System.Linq;

namespace Extensions
{
    public static class StringExtensions
    {
        public static string Reverse(this string input)
        {
            if (string.IsNullOrEmpty(input)) return "";
            return new string(input.ToCharArray().Reverse().ToArray());
        }
    }
}

And then you call this method as the below:

var input = "coding";
var inputReversed = input.Reverse();
MessageBox.Show(inputReversed);

Running the above code will output ‘gnidoc’ as the result of reversing the string ‘coding’.

Note: Always remember to import the namespace in which you have defined your extension methods, in our case it is called ‘Extensions’ , you can normally give it your preferred naming:

using Extensions;

Extension methods and Generics

As mentioned previously, an extension method can be defined to extend generic classes or data type (of type T), you can normally write an extension method that can apply for a generic type. Please see the below code:

public static bool IsNullOrEmpty<T>(this IEnumerable<T> Source)
{
    if (Source == null) return true;

    ICollection<T> collection = (ICollection<T>)Source;

    if (collection != null) return collection.Count < 1;

    return !Source.Any();
}

The above method will check if the provided generic collection, that implements the IEnumerable interface, is null or empty, this can be useful whenever you have many collections objects of the generic type (T) that you are not sure if they are null or empty (size = 0) , so in order to avoid doing the standard collection == null || collection.size == 0 check on each collection object, you can simply call this extension method and it will do the job for you. The below code shows how to call this method:

List<int> someList = null;
if (someList.IsNullOrEmpty())
{
    MessageBox.Show("Empty list");
}

At first sight, you might think that the above code will throw a null reference exception, because we are trying to access a method on a null reference object, however, .Net compiler will determine that this is an extension method and it will display “Empty List” as output in the message box.

Note that even though the Extension method has 1 parameter defined, we still call the method without passing any arguments.

This is due the fact that, as mentioned above, the first parameter defined in the extension method is the type that has to be identical to the class or datatype, that is being extended.

Open Source Libraries for .Net Extension methods

There is a wide variety of hundredth of ready-made useful .net extension methods provided by the community of .Net through CodePlex.

You can start using them today, just add a reference to the library from http://dnpextensions.codeplex.com/

Or even you can get this library from NuGet http://nuget.org/packages/PGK.Extensions/ and immediately start using it without any “import” statements

Conclusion

.Net extension methods is a powerful extensibility feature that .Net provides for the developers to extend the existing functionality of data types and classes and add more methods without having to obtain the source code and recompile it. This implies providing the developer with a seamless use of the new methods as if these methods are part of the original class or datatype.

I hope the above has provided you an adequate introduction to the amazing extension methods feature in .Net. So are you going to start using this amazing extension methods feature?

Enjoy this piece of music while writing your extension methods.

Advertisements

One thought on “Understanding Extension Methods in .Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s