Overview of Extension Methods in C#

Overview

Extension Methods allows an existing type to be extended by adding new functionality to it, without having to derive from or recompile the old type. Extension methods are available from the .NET Framework 3.5 and can be implemented on any type in the .NET Framework or any custom type.

Why is it Required

Extension Methods are required when we have a library containing a sealed class and no access to its source code. For example if there is a requirement to add a new method to the sealed class. Since source code access is not available and this class cannot be inherited, a mechanism is required to meet the requirements.

Here Extension Methods are useful.

How to Create: Steps

Step 1

Create a public static class (if using C#) or Module (if using VB.NET).

C#

public static class CustomExt
{

}

VB.NET

Module CustomExt

End Module

Step 2

Define and implement the new function.

Create the new function that must be added as extended functionality.

C#

public static class CustomExt

{

        public int FiveTimes(int iNum)

{

Return iNum*5;

}

}

VB.NET

Module CustomExt
Public Function FiveTimes(ByVal iNum As int) As int
Return iNum*5End Function
End


Step 3

Mark the function as an extension method.

C#

public static class CustomExt
{
public static int FiveTimes(this int iNum)
{
Return iNum*5;
}
}


The "this" keyword in the parameter section of the method is used to convert a static method to an extension method.

VB.NET
 

Module CustomExt

 

        <System.Runtime.CompilerServices.Extension()> _

        Public Function FiveTimes(ByVal iNum As int) As int

            Return iNum * 5

        End Function

 

End

<System.Runtime.CompilerServices.Extension> is added to convert a method in a module to extension method in VB.NET.

How to Call: Extension Method

In the above section the int type is extended and an additional functionality is defined which returns an integer value multiplied by 5. Let's call (use) this extended functionality:

C#

int iNumber = 4;

iNumber = iNumber.FiveTimes();

VB.NET

Dim iNumber As int = 4
iNumber = iNumber.FiveTimes()


Extension Method Binding at Compile Time

If an extension method with the same name as another method in that type is created, the compiler will bind the method call to the method from the original class and not to any extension. An extension method is only called when there is no instance method found with the same name.

Conclusion

It is always recommend extending the existing type by creating a type derived from the existing type and extension methods must be used only when required.
 


Similar Articles