The emergence of extension methods is related to the need to add new functions to existing data types (especially library and external types) without changing the source code of those types. This is particularly relevant in modern .NET applications where additional conveniences are required but there is no access to modify the source classes.
The problem was the inability to extend types without creating subclasses or wrappers, which led to complicated architecture and "false" inheritance.
The solution is extension methods. In Visual Basic, they are declared as modules with static methods marked with the <Extension> attribute. The first parameter of the method always indicates the type being extended, allowing the method to be called like a regular member of the object.
Code example:
Imports System.Runtime.CompilerServices Module StringExtensions <Extension> Public Function ToTitleCase(ByVal str As String) As String If String.IsNullOrEmpty(str) Then Return str Return Char.ToUpper(str(0)) & str.Substring(1).ToLower() End Function End Module ' Usage: Dim s As String = "visual basic" Console.WriteLine(s.ToTitleCase()) ' Visual basic
Key features:
Can you call an extension method through the class name rather than an instance?
Yes, the extension method can also be invoked through the extension class name as a static method, simply specifying the first (this/Me) parameter explicitly.
Code example:
StringExtensions.ToTitleCase("test string")
Can you override the behavior of system methods through Extension Methods?
No, extension methods do not override existing instance methods. In case of name conflicts, the original method of the type will be called.
Can extension methods accept a variable number of arguments (ParamArray), for example, for strings?
Yes, ParamArray can be used in extension methods just like in regular static methods.
In a large project, custom extension methods are created for each type with overlapping names and different logic, without a consistent style.
Pros:
Cons:
The module collects only universal and well-documented extensions for standard operations on types. The name of each method clearly indicates its purpose.
Pros:
Cons: