www.itgalary.com Homepage
Forum Home Forum Home > Programming > VB & VB.net
  Active Topics Active Topics
  FAQ FAQ  Forum Search   Register Register  Login Login

What are Extension Method? Orcas / VB 2008 / VB9.0

 Post Reply Post Reply
Author
Message
  Topic Search Topic Search  Topic Options Topic Options
Jijo View Drop Down
Admin Group
Admin Group
Avatar

Joined: 31 Dec 05
Location: United Kingdom
Posts: 495
  Quote Jijo Quote  Post ReplyReply Direct Link To This Post Topic: What are Extension Method? Orcas / VB 2008 / VB9.0
    Posted: 03 Sep 07 at 3:58am
What are Extension Methods?

Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type.

Simple Extension Method Example:

Ever wanted to check to see whether a string variable is a valid email address? Today you'd probably implement this by calling a separate class (probably with a static method) to check to see whether the string is valid. For example, something like:


Dim email As String = "itgalary@yahoo.com"

If EmailValidator.IsValid(email) Then

End If


Using the new "extension method" language feature in C# and VB, I can instead add a useful "IsValidEmailAddress()" method onto the string class itself, which returns whether the string instance is a valid string or not. I can then re-write my code to be cleaner and more descriptive like so:


Dim email As String = "itgalary@yahoo.com"

If email.IsValidEmailAddress() Then

End If

How did we add this new IsValidEmailAddress() method to the existing string type? We did it by defining a static class with a static method containing our "IsValidEmailAddress" extension method like below:

<System.Runtime.CompilerServices.Extension()> _
Public Function IsValidEmailAddress(ByVal s As String) as Boolean
Dim pattern As String = "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
Dim emailAddressMatch As Match = Regex.Match(s, pattern)

If emailAddressMatch.Success Then
     IsValidEmailAddress = True
Else
     IsValidEmailAddress = False
End If
End Function

Note the first parameter argument of type string. This tells the compiler that this particular Extension Method should be added to objects of type "String".
 
What is new in VB 2008
 
Partial Methods in C# 3.0 and VB.net 9.0
 
Nullable Types in VB 2008 & VB 2005
 
IIf in VB2005 vs IF in VB2008 - Whats new in VB9.0
 
Relaxed Delegates. VB 2008 / VB 9.0
 


Back to Top
 Post Reply Post Reply

Forum Jump Forum Permissions View Drop Down

.