Click here to Skip to main content
13,860,964 members
Click here to Skip to main content
Add your own
alternative version


32 bookmarked
Posted 26 Nov 2008
Licenced CPOL

Extension Methods in VB.NET

, 26 Nov 2008
Rate this:
Please Sign up or sign in to vote.
A brief overview of Extension Methods.


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:

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()>.

<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:

<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:

Dim msg As New Mail.MailMessage
Dim msgBody As New StringBuilder
Dim smtpClient As New Mail.SmtpClient
smtpClient.Port = 25
smtpClient.Host = ""
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

Finally, the output for this email is:

<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.

<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.


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


About the Author

Architect ACPI Investments
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionHow to create dll Pin
Sumit Prakash Sharma9-Sep-09 0:18
memberSumit Prakash Sharma9-Sep-09 0:18 
AnswerRe: How to create dll [modified] Pin
db7uk9-Sep-09 1:10
memberdb7uk9-Sep-09 1:10 
GeneralRe: How to create dll Pin
Sumit Prakash Sharma26-Oct-09 3:01
memberSumit Prakash Sharma26-Oct-09 3:01 
GeneralBe aware of working with extensions and With / End With Pin
HeikoDenny28-May-09 21:24
memberHeikoDenny28-May-09 21:24 
GeneralRe: Be aware of working with extensions and With / End With Pin
mdanh200213-Jun-10 6:46
membermdanh200213-Jun-10 6:46 
GeneralAdd an advisory about Object types Pin
NIFOC2-Dec-08 5:46
memberNIFOC2-Dec-08 5:46 
GeneralThe long awaited jscript prototype equivalent is there [modified] Pin
Member 433228826-Nov-08 23:09
memberMember 433228826-Nov-08 23:09 
GeneralRe: The long awaited jscript prototype equivalent is there Pin
db7uk26-Nov-08 23:29
memberdb7uk26-Nov-08 23:29 
GeneralIf only... Pin
PIEBALDconsult26-Nov-08 5:07
protectorPIEBALDconsult26-Nov-08 5:07 
GeneralRe: If only... Pin
Jason Barrera18-Dec-08 7:31
memberJason Barrera18-Dec-08 7: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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190214.1 | Last Updated 26 Nov 2008
Article Copyright 2008 by db7uk
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid