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
-
Imports System.Runtime.CompilerServices
-
-
Module StringExtensions
-
-
<Extension()>
-
Public Sub Print(ByVal aString As String)
-
Console.WriteLine(aString)
-
End Sub
-
-
<Extension()>
-
Public Sub PrintAndPunctuate(ByVal aString As String,
-
ByVal punc As String)
-
Console.WriteLine(aString & punc)
-
End Sub
-
-
End Module
To use that function
-
Sub Main()
-
-
Dim example As String = "Example string"
-
example.Print()
-
-
example = "Hello"
-
example.PrintAndPunctuate(".")
-
example.PrintAndPunctuate("!!!!")
-
-
End Sub
C#.NET
If you notice the parameter there is a this keyword, that is how it done.
-
namespace ExtensionMethods
-
{
-
public static class StringExtensions
-
{
-
public static int Print(<strong>this </strong>String str)
-
{
-
Console.WriteLine(String );
-
}
-
}
-
}
-
-
string s = "Hello Extension Method";
-
s.Print();