Welcome to weblogs.com.pk Sign in | Join | Help

ASP.NET Applications

Discuss and share about ASP.NET Development
Extension Methods in VB.NET

Extension methods allow developers to add functionality to the existing .NET types without recompiling the source, or extending (deriving from the type) the type. For certain types, such as String, these cannot be extended because they are declared as Notinheritable (Sealed). For such scenarios, create an extension method to add custom functionality. Here's an example:

Imports Microsoft.VisualBasic
Imports System.Runtime.CompilerServices
Public Module Module1 <Extension()> _
Public Function ValidateEmailAddress(ByVal emailAddress As String) As Boolean
Dim emailRegEx As New Regex("\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")
If emailRegEx.IsMatch(emailAddress) Then
Return True
Return False
End If
End Function
End Module
The requirements to create an extension method in VB.NET are as follows
i) Import System.Runtime.CompilerServices namespace
ii) Create a Module
  • Extension methods may only be created in a module
iii) Use the Extension attribute with the method
  • Each extension method must have the Extension() attribute

To use the function defined above, use code like this:

Dim s As String = "rafayali@gmail.com"
If s.ValidateEmailAddress() Then
Response.Write("check the format of email")
End If
Posted: Tuesday, January 6, 2009 3:48 PM by aspnet


No Comments

Anonymous comments are disabled