Extension method
Encyclopedia
An Extension method is a new language feature of C# starting with the 3.0 specification, as well as Visual Basic.NET starting with 9.0 and Oxygene with 2.0. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
, but this forces the programmer to recompile
all binaries
with these new changes and requires that the programmer be able to modify the class, which is not always possible, for example when using classes from a third-party assembly
. This is typically worked around in one of three ways, all of which are somewhat limited and unintuitive:
, float
and string
. The second option, on the other hand, does not share these restrictions, but it may be less intuitive as it requires a reference to a separate class instead of using the methods of the class in question directly.
As an example, consider a need of extending the string class with a new reverse method whose return value is a string with the characters in reversed order. Because the string class is a sealed type, the method would typically be added to a new utility class
in a manner similar to the following:
This may, however, become increasingly difficult to navigate as the library of utility methods and classes increases, particularly for newcomers. The location is also less intuitive because, unlike most string methods, it would not be a member of the string class, but in a completely different class altogether. A better syntax would therefore be the following:
Because VB allows the source object to be passed in by reference it's possible to make changes to the source object directly, without need to create another variable. It's also more intuitive as it works in a consistent fashion to existing methods of classes.
In the definition, the modifier 'this' before the first argument specifies that it's an extension method (in this case to the type 'string'). In a call, the first argument is not 'passed in' because it's already known as the 'calling' object (the object before the dot).
The major difference between calling extension methods and calling static helper methods is that static methods are called in prefix notation
, whereas extension methods are called in infix notation
. The latter leads to more readable code when the result of one operation is used for another operation.
With static methods:
With extension methods:
IDE warns about the naming conflict. Consider this C# class, where the
Result of invoking
ABC
Result if both the instance method and the extension method exist:
abc
The problem
In programming, situations arise where it is necessary to add functionality to an existing class—for instance by adding a new method. Normally the programmer would modify the existing class's source codeSource code
In computer science, source code is text written using the format and syntax of the programming language that it is being written in. Such a language is specially designed to facilitate the work of computer programmers, who specify the actions to be performed by a computer mostly by writing source...
, but this forces the programmer to recompile
Compiler
A compiler is a computer program that transforms source code written in a programming language into another computer language...
all binaries
Executable
In computing, an executable file causes a computer "to perform indicated tasks according to encoded instructions," as opposed to a data file that must be parsed by a program to be meaningful. These instructions are traditionally machine code instructions for a physical CPU...
with these new changes and requires that the programmer be able to modify the class, which is not always possible, for example when using classes from a third-party assembly
.NET assembly
In the .NET framework, an assembly is a compiled code library used for deployment, versioning, and security. There are two types: process assemblies and library assemblies . A process assembly represents a process that will use classes defined in library assemblies...
. This is typically worked around in one of three ways, all of which are somewhat limited and unintuitive:
- Inherit the class and then implement the functionality in an instance method in the derived class.
- Implement the functionality in a static method added to a helper class.
- Use aggregation instead of inheritanceInheritance (computer science)In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...
.
Current C# solutions
The first option is in principle easier, but it is unfortunately limited by the fact that many classes restrict inheritance of certain members or forbid it completely. This includes sealed class and the different primitive data types in C# such as intInteger (computer science)
In computer science, an integer is a datum of integral data type, a data type which represents some finite subset of the mathematical integers. Integral data types may be of different sizes and may or may not be allowed to contain negative values....
, float
Floating point
In computing, floating point describes a method of representing real numbers in a way that can support a wide range of values. Numbers are, in general, represented approximately to a fixed number of significant digits and scaled using an exponent. The base for the scaling is normally 2, 10 or 16...
and string
String (computer science)
In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet....
. The second option, on the other hand, does not share these restrictions, but it may be less intuitive as it requires a reference to a separate class instead of using the methods of the class in question directly.
As an example, consider a need of extending the string class with a new reverse method whose return value is a string with the characters in reversed order. Because the string class is a sealed type, the method would typically be added to a new utility class
Utility class
In computer programming, a utility class is a class that defines a set of methods that perform common, often re-used functions. Most utility classes define these common methods under static scope...
in a manner similar to the following:
This may, however, become increasingly difficult to navigate as the library of utility methods and classes increases, particularly for newcomers. The location is also less intuitive because, unlike most string methods, it would not be a member of the string class, but in a completely different class altogether. A better syntax would therefore be the following:
Current Visual Basic.Net solutions
In most ways the VB.net solution is similar to the C# solution above. However VB.net has a unique advantage in that it allows members to be passed in to the extension by reference (C# only allows by value). Allowing for the following;Because VB allows the source object to be passed in by reference it's possible to make changes to the source object directly, without need to create another variable. It's also more intuitive as it works in a consistent fashion to existing methods of classes.
Extension methods
The new language feature of extension methods in C# 3.0, however, makes the latter code possible. This approach requires a static class and a static method, as follows:In the definition, the modifier 'this' before the first argument specifies that it's an extension method (in this case to the type 'string'). In a call, the first argument is not 'passed in' because it's already known as the 'calling' object (the object before the dot).
The major difference between calling extension methods and calling static helper methods is that static methods are called in prefix notation
Polish notation
Polish notation, also known as prefix notation, is a form of notation for logic, arithmetic, and algebra. Its distinguishing feature is that it places operators to the left of their operands. If the arity of the operators is fixed, the result is a syntax lacking parentheses or other brackets that...
, whereas extension methods are called in infix notation
Infix notation
Infix notation is the common arithmetic and logical formula notation, in which operators are written infix-style between the operands they act on . It is not as simple to parse by computers as prefix notation or postfix notation Infix notation is the common arithmetic and logical formula notation,...
. The latter leads to more readable code when the result of one operation is used for another operation.
With static methods:
With extension methods:
Naming Conflicts in Extension methods and Instance methods
In C# 3.0, both an instance method and an extension method with the same signature can exist for a class. In such a scenario, the instance method is preferred over the extension method. Neither the compiler nor the Microsoft Visual StudioMicrosoft Visual Studio
Microsoft Visual Studio is an integrated development environment from Microsoft. It is used to develop console and graphical user interface applications along with Windows Forms applications, web sites, web applications, and web services in both native code together with managed code for all...
IDE warns about the naming conflict. Consider this C# class, where the
GetAlphabet
method is invoked on an instance of this class:Result of invoking
GetAlphabet
on an instance of AlphabetMaker
if only the extension method exists:ABC
Result if both the instance method and the extension method exist:
abc
See also
- Anonymous typeAnonymous typeAnonymous types are a feature of C# 3.0, Visual Basic .NET 9.0, and Oxygene that allows data types to encapsulate a set of properties into a single object without having to first explicitly define a type. This is an important feature for the SQL-like LINQ feature that is integrated into C# and VB.net...
s - Lambda expressionLambda expressionLambda expression may refer to:*Anonymous function*Lambda calculus#Definition...
s - Expression trees
- Runtime alteration