Click here to Skip to main content
15,867,568 members
Articles / .NET

Understanding Extension Methods in .NET

Rate me:
Please Sign up or sign in to vote.
3.61/5 (11 votes)
25 Jan 2018CPOL4 min read 14K   18   7
Extension methods is a great feature in .NET that allows developers to add or extend methods of existing types or classes and call them naturally, as if they are part of these types or classes.

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 to 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 extensibility 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#:

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:

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

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

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:

C#
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:

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

    ICollection<T> collection = Source as ICollection<T>;

    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:

C#
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 to 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 hundreds 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?

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Jordan Jordan
A passionate software developer with 13+ years of overall experience in various development languages including C#/vb.net, java. The technologies I mostly focus on are: ASP.NET Core, Android, Angular

I currently work as a Corporate Technical Manager in the Digital Solutions Team at Aramex International in Amman, Jordan.

Comments and Discussions

 
Questionmuch easier to check for IEnumerable null or empty Pin
BillWoodruff27-Jan-18 23:53
professionalBillWoodruff27-Jan-18 23:53 
AnswerRe: much easier to check for IEnumerable null or empty Pin
irneb28-Jan-18 23:46
irneb28-Jan-18 23:46 
GeneralRe: much easier to check for IEnumerable null or empty Pin
BillWoodruff30-Jan-18 6:50
professionalBillWoodruff30-Jan-18 6:50 
AnswerRe: much easier to check for IEnumerable null or empty Pin
Paulo Zemek29-Jan-18 10:10
mvaPaulo Zemek29-Jan-18 10:10 
GeneralRe: much easier to check for IEnumerable null or empty Pin
BillWoodruff30-Jan-18 6:54
professionalBillWoodruff30-Jan-18 6:54 
QuestionCode error Pin
Paulo Zemek24-Jan-18 11:06
mvaPaulo Zemek24-Jan-18 11:06 
In your code:
C#
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();
}

I think you actually wanted to use the "as" cast. By using the cast the way you did it, your code will throw an exception if the IEnumerable it not an ICollection too, and the if that comes later will always be true (considering there was no exception).
AnswerRe: Code error Pin
Aram Tchekrekjian26-Jan-18 1:47
Aram Tchekrekjian26-Jan-18 1:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.