Extension method in .net

Extension methods enable developers to add a method to an existing class without deriving or affecting the existing class. This extension methods only support a sub routine or a function.

Example if we want to extend the functionality of the String type

VB.NET


  1. Imports System.Runtime.CompilerServices
  2.  
  3. Module StringExtensions
  4.  
  5.     <Extension()>
  6.     Public Sub Print(ByVal aString As String)
  7.         Console.WriteLine(aString)
  8.     End Sub
  9.  
  10.     <Extension()>
  11.     Public Sub PrintAndPunctuate(ByVal aString As String,
  12.                                  ByVal punc As String)
  13.         Console.WriteLine(aString & punc)
  14.     End Sub
  15.  
  16. End Module

To use that function

  1.     Sub Main()
  2.  
  3.         Dim example As String = "Example string"
  4.         example.Print()
  5.  
  6.         example = "Hello"
  7.         example.PrintAndPunctuate(".")
  8.         example.PrintAndPunctuate("!!!!")
  9.  
  10.     End Sub

C#.NET
If you notice the parameter there is a this keyword, that is how it done.

  1. namespace ExtensionMethods
  2. {
  3.     public static class StringExtensions
  4.     {
  5.         public static int Print(<strong>this </strong>String str)
  6.         {
  7.             Console.WriteLine(String );
  8.         }
  9.     }  
  10. }
  11.  
  12. string s = "Hello Extension Method";
  13. s.Print();

, , ,

  1. No comments yet.
(will not be published)
Submit Comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Subscribe to comments feed
  1. No trackbacks yet.

SetPageWidth