Playing with LINQ and <Extension()>

I'm just sitting peacefully this evening playing with some LINQ stuff in ASP.NET and trying out extensions.

I was trying to think of a scenario where an extension would save repetitive drudgery. I thought of how many times I want to Response.Write something to the page and add line breaks.

I put together a little extension function to do it and used it in a LINQ query. (It's so much fun to see your extension show up in IntelliSense. It's like playing with the pros. <grin>)

Trouble is, I used the query results in a For Each loop. I could have just added the <br /> once in the loop so the extension was more effort, not less!

Anyway, it's instructive to play with .NET 3.5 stuff, so I inserted the code below. It's annoying that there doesn't seem to be a way to declare these extension thingys in a single-file ASP.NET page. You must use a separate module.


 Protected Sub Page_Load _
(ByVal sender As Object, ByVal e As System.EventArgs)
Dim names As String() = _
{"Elaine", "Brenda", "Julie", "Jaclyn"}
Dim q = _
   From s In names _
  Where s.StartsWith("J") _
  Order By s Descending _
  Select s.AddBR

Dim sb As New StringBuilder
For Each s As String In q
  sb.Append(s)
Next
Literal1.Text = sb.ToString
End Sub

' Create a separate module file called
' Module1.vb and put the stuff below in it

Imports Microsoft.VisualBasic
Imports System.Runtime.CompilerServices

Public Module Extns

 <Extension()> _
 Function AddBR(ByVal s As String) As String
   Return s & "<br />"
 End Function

End Module

1 Comment

  • >You must use a separate module.

    Ken,
    From the c# 3.0 specification,

    "Extension methods can only be declared in non-generic, non-nested static classes."

    I am sure the same applies to VB.net

    Raj

Comments have been disabled for this content.