![]() |
|
|
What are Extension Method? Orcas / VB 2008 / VB9.0 |
Post Reply
|
| Author | |
Jijo
Admin Group
Joined: 31 Dec 05 Location: United Kingdom Posts: 495 |
Quote Reply
Topic: What are Extension Method? Orcas / VB 2008 / VB9.0Posted: 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
|
|
![]() |
|
Post Reply
|
| Forum Jump | Forum Permissions ![]() You cannot post new topics in this forum You cannot reply to topics in this forum You cannot delete your posts in this forum You cannot edit your posts in this forum You cannot create polls in this forum You cannot vote in polls in this forum |