Introduction
Extension Methods are a wonderful thing. They provide great ways to control the output of say String
s, DateTime
s etc., or to specifically convert DateTime
s 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 DBNull
s when a date is less than 01/01/1900 etc.