Extension Methods
Ξ February 26th, 2008 | → 5 Comments | ∇ .Net Framework, Tools and technologies |
The specification of C# 3.0 presents some interesting new features. Today I choose to speak of extension methods. This methods are a programming trick that allow the programmer to add new methods to existing classes without having access to the source file of the class. One of the questions that could rise is: Why would such a feature be useful? Well, first of all, it’s most important benefit would be the ability to keep the code cleaner and easier to read, but it also provides a powerful model for programmers to develop extensibility frameworks.
Now, let us see what’s all this buzz around extension methods. First of all, according to MSDN, extension methods are static methods that can be invoked using instance method syntax. In effect, extension methods make it possible to extend existing types and constructed types with additional methods.
An implementation example: suppose that we wish to extend the functionality of the class System.String… now we know that this class is a sealed one and therefore we cannot inherit it. A traditional method would have been to create a method that would take a string as a parameter and process it, then return the result. In the eyes of the compiler, this is exactly what happens. You will see why. Now, returning to our example, suppose that we wish to add some additional functionality to the string class that would allow us to convert a given string value to a nullable value for a database. In order to achieve this, we will create a namespace in which our extension methods will be grouped, and a static class that will provide the required functionality:
namespace ExtensionLibrary
{
public static class ExtString
{
public static object ToDBNullableString(this string s)
{
if (string.IsNullOrEmpty(s))
return DBNull.Value;
else
return s;
}
}
}
In order to access this newly created method all we need to do is import the namespace in our code file where we wish to use the newly created function. Here is how we call it:
using System;
using ExtensionLibrary;
namespace ExtensionMethods
{
class Program
{
static void Main(string[] args)
{
string emptyString = “”;
string valueString = “John”;
AddToDB(emptyString.ToDBNullableString());
AddToDB(valueString.ToDBNullableString());
}
}
}
I am sure that one can find more complex examples for more complicated scenarios in which to use extension methods, but this example should suffice for a small demo purpose. There are some constraints in declaring extension methods. They can be declared by specifying the keyword this as a modifier on the first parameter of the methods. Extension methods can only be declared in non-generic, non-nested static classes.
Extension methods can be accessed in the namespace in which they are declared or if they are imported with the using directive. If there is any collision between an extension method with an existing non extension method at any given time (collisions occur if the signatures of the methods is identical, excluding the first parameter in the extension methods), the non extension method is invoked. Bellow is a simple example to make things clear:
public static class Ext
{
public static void M(this object obj, string s) { }
}
class A { }
class B
{
public void M(string s) { }}class C
{
static void Call(A a, B b)
{
// call extension method from class Ext
a.M(“John”);
// call method from class M
b.M(“John”);
}
}
[Updated] Extension methods should be used only when the traditional techniques are not feasible. I would recommend the use of the inheritance technique where applicable due to a few reasons. One of them is the fact that extension methods are a bit less intuitive since the code is in a separate static class and not grouped with all the members of a given subclass. Still, they provide an excellent way to extend existing libraries and create Frameworks. More information on extension methods and other new features in C# 3.0 can be found on MSDN and on ScottGu’s blog.
on June 29th, 2008 at 10:19 am
> Extension methods should be used only when the traditional techniques are not feasible, because extension methods introduce some performance overhead.
Uh, not really. An extension method, once compiled, is just another static method. And static methods, not having v-tables, are about as fast as you can get. If they are short they will probably even be inlined.
on June 29th, 2008 at 10:54 am
Thanks for the observation Jonathan. You are right. Still, I would recommend the use of the inheritance technique where applicable due to a few reasons. One of them is the fact that extension methods are a bit less intuitive since the code that needs to be executed is in a separate static class and not grouped with all the members of a given class.
on June 29th, 2008 at 11:03 am
I’ve updated the post in order to remove my initial error, spotted by Jonathan. The initial block stated: “Extension methods should be used only when the traditional techniques are not feasible, because extension methods introduce some performance overhead”. I replaced it with: “Extension methods should be used only when the traditional techniques are not feasible. I would recommend the use of the inheritance technique where applicable due to a few reasons. One of them is the fact that extension methods are a bit less intuitive since the code is in a separate static class and not grouped with all the members of a given subclass”. Once again thank you Jonathan for your observation.
on February 12th, 2009 at 6:18 pm
[...] Extension Methods [...]
on March 6th, 2010 at 11:30 am
Este interesant acest blog, ai putea sa-l actualizezi mai des..:)