Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / Visual Basic
Article

Extension Methods in VB.NET

Rate me:
Please Sign up or sign in to vote.
4.36/5 (7 votes)
26 Nov 2008CPOL2 min read 81.7K   32   10
A brief overview of Extension Methods.

Introduction

Extension Methods are a wonderful thing. They provide great ways to control the output of say Strings, DateTimes etc., or to specifically convert DateTimes to a nullable object. They provide a way of adding new methods to already available public methods such as String.<public method> or DateTime.Now.<public method>, so you don't have to write helper functions or sub-classes etc.

In this article, I will explain some simple ways in which you could use this in a real world scenario. This article is for VB.NET, but could be converted to C# easily. Note, points are added if there are language differences.

Using the code

Let us begin. Firstly, in your project, under the App_Code folder, add a new module (with ASP.NET, you can only add a class; add this, but change the statement “Public Class” to “Public Module”) and call it HTMLExtensionMethods, and then open it. Now, add the following import: Imports System.Runtime.CompilerServices.

Note: With C#, you only need to add the class and do not need to reference the compiler service.

Your new module should look like this:

VB
Imports Microsoft.VisualBasic
Imports System.Runtime.CompilerServices

Public Module HTMLExtensionMethods

End Module

To add an Extension Method, all you need to do is write a new function that returns an object. You must add a parameter that is identical to the method you are extending, i.e., if you were extending the System.String method, the InputValue must also be a String. In order for it to be visible to the compiler and thus show in the Intellisense, you must add the attribute: <Extension()>.

VB
<Extension()> _
Public Function MethodName(ByVal InputValue As String) As String

End Function

The above shows the complete function. This function is an extension of the public System.String method. This is because the input value is also a String.

So now, all we need to do is add some functionality to this module (or class) and use it in our project. I will now add some functions below, as an example:

VB
<Extension()> _
Public Function ToHTMLBoldString(ByVal InputValue As String) As String
Return String.Concat("<strong>", HttpUtility.HtmlEncode(InputValue), "</strong>")
End Function
<Extension()> _
Public Function ToHTMLItalicString(ByVal InputValue As String) As String
Return String.Concat("<em>", HttpUtility.HtmlEncode(InputValue), "</em>")
End Function
<Extension()> _
Public Function ToHTMLUnderlineString(ByVal InputValue As String) As String
Return String.Concat("<u>", HttpUtility.HtmlEncode(InputValue), "</u>")
End Function
<Extension()> _
Public Function ToHTMLParagraphString(ByVal InputValue As String) As String
Return String.Concat("<p>", HttpUtility.HtmlEncode(InputValue), "</p>")
End Function
<Extension()> _
Public Function ToHTMLBlockQuoteString(ByVal InputValue As String) As String
Return String.Concat("<blockquote>", _
       HttpUtility.HtmlEncode(InputValue), "</blockquote>")
End Function

Notice that I am using HttpUtility.HtmlEncode. This is important because the input may contain invalid HTML tags such as <>.

Once we have added our functions, we can then use this in our main project code. The code below shows how to write an HTML email using some of the functions above:

VB
Dim msg As New Mail.MailMessage
Dim msgBody As New StringBuilder
Dim smtpClient As New Mail.SmtpClient
smtpClient.Port = 25
smtpClient.Host = "127.0.0.1"
msg.To.Add("someone@somewhere.com")
msg.IsBodyHtml = True
msg.Subject = "Test Email"
With msgBody
.Append("Dear Someone".ToHTMLParagraphString)
.Append("Thank you for showing me this. It was really" & _ 
        " handy.".ToHTMLParagraphString)
.Append("See you soon !!!".ToHTMLParagraphString)
End With
msg.Body = msgBody.ToString
smtpClient.Send(msg)

Finally, the output for this email is:

HTML
<p>Dear Someone</p>
<p>Thank you for showing me this. It was really handy.</p>
<p> See you soon !!!</p>

The functions can be improved by adding parameters. The following will convert a string to parameter to an embedded mailto link.

VB
<Extension()> _
Public Function ToHTMLMailtoString(ByVal InputValue As String, _ 
ByVal Subject As String) As String
Return String.Concat("<a href='mailto:", HttpUtility.HtmlEncode(InputValue), _
"?subject=", Subject, "'>", HttpUtility.HtmlEncode(InputValue), "</a>")
End Function

Use this function in the same way, and it will convert your email address (as InputValue) to an HTML mailto anchor. This could save quite a few lines of code.

Points of interest

I have only scratched the surface of Extension Methods. There is a myriad of stuff you could do. But, some really useful thing might be checking to see if the string you have typed is correctly formatted using a Regular Expression. For DateTime, you could return DBNulls when a date is less than 01/01/1900 etc.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect ACPI Investments
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow to create dll Pin
Sumit Prakash Sharma8-Sep-09 23:18
professionalSumit Prakash Sharma8-Sep-09 23:18 
AnswerRe: How to create dll [modified] Pin
db7uk9-Sep-09 0:10
db7uk9-Sep-09 0:10 
GeneralRe: How to create dll Pin
Sumit Prakash Sharma26-Oct-09 2:01
professionalSumit Prakash Sharma26-Oct-09 2:01 
GeneralBe aware of working with extensions and With / End With Pin
HeikoDenny28-May-09 20:24
HeikoDenny28-May-09 20:24 
GeneralRe: Be aware of working with extensions and With / End With Pin
Minh Danh Nguyen (ToughDev)13-Jun-10 5:46
Minh Danh Nguyen (ToughDev)13-Jun-10 5:46 
GeneralAdd an advisory about Object types Pin
NIFOC2-Dec-08 4:46
NIFOC2-Dec-08 4:46 
GeneralThe long awaited jscript prototype equivalent is there [modified] Pin
Member 433228826-Nov-08 22:09
Member 433228826-Nov-08 22:09 
GeneralRe: The long awaited jscript prototype equivalent is there Pin
db7uk26-Nov-08 22:29
db7uk26-Nov-08 22:29 
GeneralIf only... Pin
PIEBALDconsult26-Nov-08 4:07
mvePIEBALDconsult26-Nov-08 4:07 
GeneralRe: If only... Pin
Jason Barrera18-Dec-08 6:31
Jason Barrera18-Dec-08 6:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.