Click here to Skip to main content
13,145,068 members (55,539 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

3.1K views
9 bookmarked
Posted 5 Jul 2017

Understanding Extension Methods in .NET

, 5 Jul 2017
Rate this:
Please Sign up or sign in to vote.
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#:

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

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 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)

Share

About the Author

Aram Tchekrekjian
Technical Lead
Jordan Jordan
My name is Aram Tchekrekjian, I’m a passionate software developer with 7+ years of overall experience in various development languages including vb.net, c#, java and some php, during which I gained abundant of knowledge in Asp.net Web Forms, Asp.net Web Api, javascript, bootstrap, entity framework, WCF, windows forms, SQL server, MySQL as well as Android.

Currently I am an android developer and a scrum master within a cross-location teams working on multi-platform project, managing a Jenkins CI for multiple projects on an ubuntu server. My main interests are: git, docker, SEO, digital marketing.

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


You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170915.1 | Last Updated 5 Jul 2017
Article Copyright 2017 by Aram Tchekrekjian
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid