Posts Tagged ‘extension method’

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();

, , ,

No Comments



SetPageWidth