Click here to Skip to main content
Click here to Skip to main content

Extension Methods in VB.NET

, 26 Nov 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

db7uk
Architect ACPI Investments
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
QuestionHow to create dll PinmemberSumit Prakash Sharma9-Sep-09 0:18 
AnswerRe: How to create dll [modified] Pinmemberdb7uk9-Sep-09 1:10 
GeneralRe: How to create dll PinmemberSumit Prakash Sharma26-Oct-09 3:01 
GeneralBe aware of working with extensions and With / End With PinmemberHeikoDenny28-May-09 21:24 
GeneralRe: Be aware of working with extensions and With / End With Pinmembermdanh200213-Jun-10 6:46 
GeneralAdd an advisory about Object types PinmemberNIFOC2-Dec-08 5:46 
GeneralThe long awaited jscript prototype equivalent is there [modified] PinmemberMember 433228826-Nov-08 23:09 
GeneralRe: The long awaited jscript prototype equivalent is there Pinmemberdb7uk26-Nov-08 23:29 
GeneralIf only... PinmemberPIEBALDconsult26-Nov-08 5:07 
GeneralRe: If only... PinmemberJason Barrera18-Dec-08 7:31 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150224.1 | Last Updated 26 Nov 2008
Article Copyright 2008 by db7uk
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid