You can now add custom features to an existing type as if the type always had the custom features. In this way, you do not have to recompile a given object, nor do you have to create a second, derived object to add these features. Rather, you can add a method to an existing object by using a new compiler feature called extension methods.

Doing so is a bit different between VB and C#. In VB, you first import the
System.Runtime.CompilerServices namespace into your code file. Next, you mark a given Sub or Function with the <Extension()> directive. Lastly, you write a new Sub or Function with the first parameter of the new method being the type you want to extend. The following shows an example. In this example, we extend the Integer type with a new method called DoubleInSize:

VB

Imports System.Runtime.CompilerServices

Public Module IntegerExtensions
<Extension()> _
Public Function DoubleInSize(ByVal i As Integer) As Integer
Return i + i
End Function
End Module

The C# compiler does not require the same import or method attribute. Instead, you first create a static class. Next, you create a static method that you intend to use as your extension. The first parameter of your extension method should be the type you want to extend. Additionally, you apply the this modifier to the type. Notice the following example. In it, we extend the int data type with a new method called DoubleInSize.

C#

namespace IntegerExtensions {
public static class IntegerExtensions{
public static int DoubleInSize(this int i) {
return i+i;
}
}
}

To use an extension method, you must first import (using in C#) the new extension methods into a project. You can then call any new method as if it had always existed on the type. The following is an example in both VB and C#. In this case, a function called DoubleInSize that was added in the preceding example is being called from the Integer (int) class.

VB

Imports IntegerExtensions

Module Module1
Sub Main()
Dim i As Integer = 10
Console.WriteLine(i.DoubleInSize.ToString())
End Sub
End Module


C#
using IntegerExtensions;

namespace CsEnhancements {
class Program {
static void Main(string[] args) {
int i = 10;
Console.WriteLine(i.DoubleInSize().ToString());
}
}
}

Source of Information : Sams Microsoft Visual Studio 2008 Unleashed

0 comments


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner