Extension Methods with VB.NET

10/19/2009 7:30:52 PM

I wanted to make it easy for me to display a link to my blog posts from the results returned from queries here on the site.  It turns out that just extending the partial class created by LINQ-to-SQL data objects was just the ticket.

Here is an example of how easy it can be to extend an object to add functionality:

Partial Public Class Content

    Public Function ContentLink() As String
        Return String.Format("<a href='{0}{1}/{2}' title='{3}'>{3}</a>", _
                             New Web.UI.Control().ResolveUrl("~/"), _
                             Me.ContentType.Trim(), _
                             Me.URLAlias.Trim(), _
                             Me.Title.Trim())
    End Function

End Class

After that addition to my data layer, I can now call the ContentLink() method of the Content objects to display their relative links:

    Protected Sub DisplayRecentBlogPosts()
        Dim html As New StringBuilder
        html.Append("<ul>")
        Dim posts As List(Of Data.Content) = Business.ContentBO.GetContentByType("blog", True)
        posts = (From c As Data.Content In posts Order By c.CreateDate Descending Select c).Take(5).ToList()
        For Each c As Data.Content In posts
            html.Append(String.Format("<li>{0}</li>", c.ContentLink()))
        Next
        html.Append("</ul>")
        litRecentBlogPosts.Text = html.ToString()
    End Sub

 

Tags:.NET VB.NET
692b4387-6150-48e7-97ef-bb84c369ca97

Comments:

No comments yet
Name:
Email: (Your email will not be displayed or distributed in any way)
Comment:
  • © brentman.com 2009-2012 | This site licensed under a Creative Commons license
  • The opinions expressed on this site are my own and not those of my employer.
Log In
 
 
login