views:

606

answers:

7

What are extension methods in .NET?



EDIT: I have posted a follow up question at Usage of Extension Methods

A: 

Click here: Extension Methods

Ricardo Villamil
+2  A: 

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.

Tom Anderson
+29  A: 
Andreas Grech
100% correct, although I have a beef with adding extension methods to primitive types such as string that aren't Fundamental to the type. Thus, I wouldn't add 'IsValidEmailAddress' to string, but I have added Left(int) and Right(int).
Michael Bray
+2  A: 

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.

Mike Hofer
shouldn't be return item.Count == 0; instead return this.Count == 0; ?
balexandre
Nice catch. Fixed the code.
Mike Hofer
A: 

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
Sisiutl
+1  A: 

Here is concise article on Extension Methods in c# with enough information to get you started:

How and when to use Extension Methods in C# and .Net

Roboblob