Extending Base Type Functionality with Extension Methods

This article comes from Scott Mitchell at 4guysfromrolla.com. Its good post which I liked and wanna share with you:

Extension methods allow a developer to tack on her own methods to an existing class in the .NET Framework. For example, imagine that our developer created a method named StripHtml, that strips HTML elements from a string using a regular expression. By associating this method with the System.String class, it could be called as if it was one of the System.String class’s built-in methods:

Creating the Extension Methods with Visual Basic
In order to create the extension methods in Visual Basic we need to first create a Module. For each extension method you want to create, add a method whose first input parameter is of the type that you want to add the extension method to. Moreover, prefix the method with the Extension() attribute.

The following Module named DateTimeHelpers contains two methods: ToRelativeToCurrentTimeString(DateTime) and ToRelativeToCurrentUtcTimeString(DateTime), both of which accept a DateTime instance as their first input parameter. The methods are also marked with the Extension() attribute (which is found in the System.Runtime.CompilerServices namespace). The two methods call the private ToRelativeString method, which returns the appropriate string message based on the difference in time between the two passed-in DateTime values.

We can now call these extension methods from a DateTime instance. In order to use an extension method, we first need to add an Imports directive to the code file, importing the namespace where the extension methods reside (Helpers). Upon doing that, the extension method is visible in the IntelliSense drop-down list, as the following screen shot illustrates.
ExtMethods1 Extending Base Type Functionality with Extension Methods
read source


Leave a Reply

Your email address will not be published. Required fields are marked *