Click here to Skip to main content
Licence CPOL
First Posted 26 Nov 2008
Views 19,188
Bookmarked 25 times

Extension Methods in VB.NET

By | 26 Nov 2008 | Article
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:

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

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

License

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

About the Author

db7uk

Software Developer (Senior)
Heartwood Group Ltd
United Kingdom United Kingdom

Member

I am very passionate about developing software and websites using modern technologies and techniques.
 
I enjoy spending time with my wife and two sons. I am currently learning to fly and hope to achieve my light aircraft pilot’s license by my 40th birthday!

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionHow to create dll PinmemberSumit Prakash Sharma23:18 8 Sep '09  
AnswerRe: How to create dll [modified] Pinmemberdb7uk0:10 9 Sep '09  
GeneralRe: How to create dll PinmemberSumit Prakash Sharma2:01 26 Oct '09  
GeneralBe aware of working with extensions and With / End With PinmemberHeikoDenny20:24 28 May '09  
GeneralRe: Be aware of working with extensions and With / End With Pinmembermdanh20025:46 13 Jun '10  
GeneralAdd an advisory about Object types PinmemberNIFOC4:46 2 Dec '08  
GeneralThe long awaited jscript prototype equivalent is there [modified] PinmemberMember 433228822:09 26 Nov '08  
GeneralRe: The long awaited jscript prototype equivalent is there Pinmemberdb7uk22:29 26 Nov '08  
GeneralIf only... PinmemberPIEBALDconsult4:07 26 Nov '08  
GeneralRe: If only... PinmemberJason Barrera6:31 18 Dec '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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 | Mobile
Web02 | 2.5.120528.1 | Last Updated 26 Nov 2008
Article Copyright 2008 by db7uk
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid