Wednesday, October 05, 2011

Extension Methods in .NET

Introduction

In this article, we will take a look at what extension methods are and how to use them in .NET. Personally, they are one of the best things that have been introduced into the .NET Framework in terms of readability. I will take you through what extension methods are, how to create them (in C# and VB), then I will show you some of the extension methods that I have created (in C# only, conversion is for you to try).
Contents

    What are extension methods?
    How do we create extension methods?
    Examples of extension methods
    Related Links

What are Extension Methods?

Extension methods allow you to easily extend a type, such as an integer or string, without re-compiling or modifying the type. In essence, they are a type of static (shared in VB) method, but they are called as if the method is native to the type. Extension methods are available from the 3.5 version of the .NET Framework and can be implemented on any type in the .NET Framework or any custom type that you define.

One downside to extension methods is if that you create an extension method with the same name as another method in that type, the compiler will bind the method call to the native method, not any extension. An extension method is only called when there is no native method found.
Warning
If you declare an extension method on the type Object, you will effectively create the extension method for every type in the framework including but not limited to String, Integer and Lists.
How Do We Create Extension Methods?

The basic outline of creating an extension methods goes something like this:

    Create a public static class (module in VB)
    Define functions that you wish to perform
    Make the functions an extension method

Following through a complete example, I will now demonstrate how to create an extension method that returns the first 3 characters of a string. Using the list above, I must first create a static class or module:

// C#
public static class Extensions
{

}


Read more: Codeproject
QR: ExtensionMethodsInDotnet.aspx

Posted via email from Jasper-Net