What are extension methods in .NET?
EDIT: I have posted a follow up question at Usage of Extension Methods
What are extension methods in .NET?
EDIT: I have posted a follow up question at Usage of Extension Methods
Extension methods are ways for developers to "add on" methods to objects they can't control.
For instance, if you wanted to add a "DoSomething()" method to the System.Windows.Forms object, since you don't have access to that code, you would simply create an extension method for the form with the following syntax.
Public Module MyExtensions
<System.Runtime.CompilerServices.Extension()> _
Public Sub DoSomething(ByVal source As System.Windows.Forms.Form)
'Do Something
End Sub
End Module
Now within a form you can call "Me.DoSomething()".
In summary, it is a way to add functionality to existing objects without inheritance.
An extension method is a "compiler trick" that allows you to simulate the addition of methods to another class, even if you do not have the source code for it.
For example:
using System.Collections;
public static class TypeExtensions
{
/// <summary>
/// Gets a value that indicates whether or not the collection is empty.
/// </summary>
public static bool IsEmpty(this CollectionBase item)
{
return item.Count == 0;
}
}
In theory, all collection classes now include an IsEmpty
method that returns true if the method has no items (provided that you've included the namespace that defines the class above).
If I've missed anything important, I'm sure someone will point it out. (Please!)
Naturally, there are rules about the declaration of extension methods (they must be static, the first parameter must be preceeded by the this
keyword, and so on).
Extension methods do not actually modify the classes they appear to be extending; instead, the compiler mangles the function call to properly invoke the method at run-time. However, the extension methods properly appear in intellisense dropdowns with a distinctive icon, and you can document them just like you would a normal method (as shown above).
Note: An extension method never replaces a method if a method already exists with the same signature.
Here's the example in VB.Net; notice the Extension() attribute. Place this in a Module in your project.
Imports System.Runtime.CompilerServices
<Extension()> _
Public Function IsValidEmailAddress(ByVal s As String) As Boolean
If String.IsNullOrEmpty(s) Then Return False
Return Regex.IsMatch(email, _
"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")
End Function
Here is concise article on Extension Methods in c# with enough information to get you started: