Am I the only one who found “Shared” (aka Static) methods disturbing? Loving true Object Oriented programming, when reviewing .net 1.0 Beta 1 I was aghast (similar to being agog) in that I knew my less sophisticated software developing brethren would use this as a way of avoiding using OO. (also don’t get me started on the Module keyword in VB) I was not disappointed.
As much as I tried to encourage these simple souls to inherit, override and extend, they happily pointed out the cursed “NotInheritable” (sealed) classes. My dreams of adding my own methods to existing classes such as “String” were dashed. The “subroutine” brigade merrily created their “Utils” modules and using OO for “everything” appeared to be unattainable.
Fortunately the situation has been approved. I give you the new VB9 feature of “Extension Methods”. These are cool methods that can be effectively added to any class, whether “NotInheritable” or not.
A feature of the string class I really like is the “StartsWith” and “EndsWith” methods. They allow me to check if a string has certain characters at the beginning or end of a target string.
What if I wanted to check if there was a string anywhere within a target string? No easy boolean operator there. (There is “IndexOf” but returns a -1 if not found. Yuk!)
Now if I was one of the simple Shared method lovers I may create a module like this:
Module Utils End Module
To do the check, you’d have code that looked like this:
Public Function ContainsString(ByVal targ As String, ByVal toFind As String) As Boolean
Return tar.IndexOf(toFind) <> -1
End Function
Dim lsString = "The red sun set in the west"
If Utils.ContainsString(lsString, "red")
Then
MsgBox("Contains Red")To some this may be beautiful. To me it is not.
End If
I prefer this syntax:
Dim lsString = "The red sun set in the west"
If lsString.ContainsString("red") Then
To make this happen, simple add the *<Extension()> attribute:
MsgBox("Contains Red")
End If
Imports System.Runtime.CompilerServices End Module
Pretty cool eh? I’m quite excited at the possibilities. It honours the accessor keywords (Public,Friend,Private) so you can use it within assemblies safely without having to have debates.
Module Utils
<Extension()> Public Function ContainsString(ByVal targetString As String, ByVal stringToFind As String) As Boolean
Return targetString.IndexOf(stringToFind) <> -1
End Function
Extension methods even work for generic types, such as “List(Of T)”, so they really are without limits.
Note: Sadly this requires targeting .Net Framework 3.5 and doesn’t appear to work on the Compact Framework.
End Module