Extension method
   HOME

TheInfoList



OR:

In
object-oriented computer programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pr ...
, an extension method is a
method Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
added to an object after the original object was
compiled In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
. The modified object is often a class, a prototype or a type. Extension methods are features of some object-oriented programming languages. There is no syntactic difference between calling an extension method and calling a method declared in the type definition. Not all languages implement extension methods in an equally safe manner, however. For instance, languages such as C#, Java (vi
Manifold
o
Lombok
, and Kotlin don't alter the extended class in any way, because doing so may break class hierarchies and interfere with virtual method dispatching. This is why these languages strictly implement extension methods statically and use
static dispatch In computing, static dispatch is a form of polymorphism fully resolved during compile time. It is a form of ''method dispatch,'' which describes how a language or environment will select which implementation of a method or function to use. Ex ...
ing to invoke them.


Support in programming languages

Extension methods are features of numerous languages including C#,
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
vi
Manifold
o
Lombok
Gosu Gosu (고수) is a Korean term used to refer to a highly skilled person. In computer gaming the term is usually used to refer to a person who dominated games like ''StarCraft'', ''Counter-Strike'', Tekken, ''Warcraft III'', ''Diablo II ''D ...
,
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
, Oxygene,
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
,
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
, Kotlin,
Dart Dart or DART may refer to: * Dart, the equipment in the game of darts Arts, entertainment and media * Dart (comics), an Image Comics superhero * Dart, a character from ''G.I. Joe'' * Dart, a ''Thomas & Friends'' railway engine character * Dar ...
,
Visual Basic.NET Visual Basic, originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Vis ...
and
Xojo The Xojo programming environment and programming language is developed and commercially marketed by Xojo, Inc. of Austin, Texas for software development targeting macOS, Microsoft Windows, Linux, iOS, the Web and Raspberry Pi. Xojo uses a propri ...
. In dynamic languages like
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
, the concept of an extension method is unnecessary because classes can be extended without any special syntax (an approach known as " monkey-patching", employed in libraries such as gevent). In VB.NET and Oxygene, they are recognized by the presence of the "extension" keyword or attribute. In Xojo the "Extends" keyword is used with global methods. In C# they're implemented as static methods in static classes, with the first argument being of extended class and preceded by "this" keyword. In Java you add extension methods vi
Manifold
a jar file you add to your project's classpath. Similar to C# a Java extension method is declared static in a

class where the first argument has the same type as the extended class and is annotated with @This. In Smalltalk, any code can add a method to any class at any time, by sending a method creation message (such as methodsFor:) to the class the user wants to extend. The Smalltalk method category is conventionally named after the package that provides the extension, surrounded by asterisks. For example, when Etoys application code extends classes in the core library, the added methods are put in the *etoys* category. In Ruby, like Smalltalk, there is no special language feature for extension, as Ruby allows classes to be re-opened at any time with the class keyword, in this case, to add new methods. The Ruby community often describes an extension method as a kind of
monkey patch Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. A monkey patch (also spelled monkey-patch, MonkeyPatch) is a way to extend or modify the runtime code of dynamic languages (e.g. Smalltalk, JavaSc ...
. There is also a newer feature for adding safe/local extensions to the objects, calle
Refinements
but it is known to be less used. In Swift, the extension keyword marks a class-like construct that allows the addition of methods, constructors, and fields to an existing class, including the ability to implement a new interface/protocol to the existing class.


Extension methods as enabling feature

Next to extension methods allowing code written by others to be extended as described below, extension methods enable patterns that are useful in their own right as well. The predominant reason why extension methods were introduced was
Language Integrated Query Language Integrated Query (LINQ, pronounced "link") is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages, originally released as a major part of .NET Framework 3.5 in 2007. LINQ extends the langua ...
(LINQ). Compiler support for extension methods allows deep integration of LINQ with old code just the same as with new code, as well as support for query syntax which for the moment is unique to the primary
Microsoft .NET The Microsoft .NET strategy is a marketing plan that Microsoft followed in the early 2000s. Steve Ballmer described it as the company's "most ambitious undertaking since Internet Strategy Day in 1995". In support of this strategy, between 2000 and ...
languages. Console.WriteLine(new[] .Where(d => d > 3).Select(d => Math.Sin(d / 2)).Sum()); // Output: // 1


Centralize common behavior

However, extension methods allow features to be implemented once in ways that enable reuse without the need for
inheritance Inheritance is the practice of receiving private property, Title (property), titles, debts, entitlements, Privilege (law), privileges, rights, and Law of obligations, obligations upon the death of an individual. The rules of inheritance differ ...
or the overhead of
virtual method In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part o ...
invocations, or to require implementors of an
interface Interface or interfacing may refer to: Academic journals * ''Interface'' (journal), by the Electrochemical Society * ''Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics'' * '' Inte ...
to implement either trivial or woefully complex functionality. A particularly useful scenario is if the feature operates on an interface for which there is no concrete implementation or a useful implementation is not provided by the class library author, e.g. such as is often the case in libraries that provide developers a plugin architecture or similar functionality. Consider the following code and suppose it is the only code contained in a class library. Nevertheless, every implementor of the ILogger interface will gain the ability to write a formatted string, just by including a ''using MyCoolLogger'' statement, without having to implement it once and without being required to subclass a class library provided implementation of ILogger. namespace MyCoolLogger; public interface ILogger public static class LoggerExtensions * use as :var logger = new MyLoggerImplementation(); logger.Write(": ", "kiddo sais", "Mam mam mam mam ..."); logger.Write(": ", "kiddo sais", "Ma ma ma ma... "); logger.Write(": ", "kiddo sais", "Mama mama mama mama "); logger.Write(": ", "kiddo sais", "Mamma mamma mamma ... "); logger.Write(": ", "kiddo sais", "Elisabeth Lizzy Liz..."); logger.Write(": ", "mamma sais", "WHAT?!?!!!"); logger.Write(": ", "kiddo sais", "hi.");


Better loose coupling

Extension methods allow users of class libraries to refrain from ever declaring an argument, variable, or anything else with a type that comes from that library. Construction and conversion of the types used in the class library can be implemented as extension methods. After carefully implementing the conversions and factories, switching from one class library to another can be made as easy as changing the using statement that makes the extension methods available for the compiler to bind to.


Fluent application programmer's interfaces

Extension methods have special use in implementing so called fluent interfaces. An example is Microsoft's Entity Framework configuration API, which allows for example to write code that resembles regular English as closely as practical. One could argue this is just as well possible without extension methods, but one will find that in practice, extension methods provide a superior experience because less constraints are placed on the class hierarchy to make it work - and read - as desired. The following example uses Entity Framework and configures the TodoList class to be stored in the database table Lists and defines a primary and a foreign key. The code should be understood more or less as: "A TodoList has key TodoListID, its entity set name is Lists and it has many TodoItem's each of which has a required TodoList". public class TodoItemContext : DbContext


Productivity

Consider for exampl
IEnumerable
and note its simplicity - there is just one method, yet it is the basis of LINQ more or less. There are many implementions of this interface in Microsoft .NET. Nevertheless, obviously, it would have been burdensome to require each of these implementations to implement the whole series of methods that are defined in th
System.Linq namespace
to operate on IEnumerables, even though Microsoft has all the source code. Even worse, this would have required everybody besides Microsoft considering to use IEnumerable themselves to also implement all those methods, which would have been very anti-productive seeing the widespread use of this very common interface. Instead, by implementing the one method of this interface, LINQ can be used more or less immediately. Especially seeing in practically most cases IEnumerable's GetEnumerator method is delegated to a private collection, list or array's GetEnumerator implementation. public class BankAccount : IEnumerable // given an instance of BankAccount called ba and a using System.Linq on top of the current file, // one could now write ba.Sum() to get the account balance, ba.Reverse() to see most recent transactions first, // ba.Average() to get the average amount per transaction, etcetera - without ever writing down an arithmetic operator


Performance

That said, additional implementations of a feature provided by an extension method can be added to improve performance, or to deal with differently implemented interface implementations, such as providing the compiler an implementation of IEnumerable specifically for arrays (in System.SZArrayHelper), which it will automatically choose for extension method calls on array typed references, since their argument will be more specific (this T[] value) than the extension method with the same name that operates on instances of the IEnumerable interface (this IEnumerable value).


Alleviating the need for a common base class

With generic classes, extension methods allow implementation of behavior that is available for all instantiations of the generic type without requiring them to derive from a common base class, and without restricting the type parameters to a specific inheritance branch. This is a big win, since the situations where this argument holds require a non-generic base class just to implement the shared feature - which then requires the generic subclass to perform
boxing Boxing (also known as "Western boxing" or "pugilism") is a combat sport in which two people, usually wearing protective gloves and other protective equipment such as hand wraps and mouthguards, throw punches at each other for a predetermined ...
and/or casts whenever the type used is one of the type arguments.


Conservative use

A note should be placed on preferring extension methods over other means of achieving reuse and proper object oriented design. Extension methods might 'clutter' the automatic completion features of code editors, such as Visual Studio's IntelliSense, hence they should either be in their own namespace to allow the developer to selectively import them or they should be defined on a type that is specific enough for the method to appear in IntelliSense only when really relevant and given the above, consider that they might be hard to find should the developer expect them, but miss them from IntelliSense due to a missing using statement, since the developer may not have associated the method with the class that defines it, or even the namespace in which it lives - but rather with the type that it extends and the namespace that type lives in.


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 code In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the wo ...
, but this forces the programmer to
recompile In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
all
binaries A binary file is a computer file that is not a text file. The term "binary file" is often used as a term meaning "non-text file". Many binary file formats contain parts that can be interpreted as text; for example, some computer document fil ...
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 Assembly may refer to: Organisations and meetings * Deliberative assembly, a gathering of members who use parliamentary procedure for making decisions * General assembly, an official meeting of the members of an organization or of their representa ...
. 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
inheritance Inheritance is the practice of receiving private property, Title (property), titles, debts, entitlements, Privilege (law), privileges, rights, and Law of obligations, obligations upon the death of an individual. The rules of inheritance differ ...
.


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 int,
float Float may refer to: Arts and entertainment Music Albums * ''Float'' (Aesop Rock album), 2000 * ''Float'' (Flogging Molly album), 2008 * ''Float'' (Styles P album), 2013 Songs * "Float" (Tim and the Glory Boys song), 2022 * "Float", by Bush ...
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 As a topic of economics, utility is used to model worth or value. Its usage has evolved significantly over time. The term was introduced initially as a measure of pleasure or happiness as part of the theory of utilitarianism by moral philosophe ...
in a manner similar to the following: string x = "some string value"; string y = Utility.Reverse(x); 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: string x = "some string value"; string y = x.Reverse();


Current VB.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; Dim x As String = "some string value" x.Reverse() Because Visual Basic allows the source object to be passed in by reference it is possible to make changes to the source object directly, without need to create another variable. It is 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. public static class Utility 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 is 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 (PN), also known as normal Polish notation (NPN), Łukasiewicz notation, Warsaw notation, Polish prefix notation or simply prefix notation, is a mathematical notation in which operators ''precede'' their operands, in contrast t ...
, whereas extension methods are called in
infix notation Infix notation is the notation commonly used in arithmetical and logical formulae and statements. It is characterized by the placement of operators between operands—" infixed operators"—such as the plus sign in . Usage Binary relations a ...
. The latter leads to more readable code when the result of one operation is used for another operation. ;With static methods: HelperClass.Operation2(HelperClass.Operation1(x, arg1), arg2) ;With extension methods: x.Operation1(arg1).Operation2(arg2)


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 Studio Visual Studio is an integrated development environment (IDE) from Microsoft. It is used to develop computer programs including websites, web apps, web services and mobile apps. Visual Studio uses Microsoft software development platforms such a ...
IDE warns about the naming conflict. Consider this C# class, where the GetAlphabet() method is invoked on an instance of this class: class AlphabetMaker static class ExtensionMethods 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

*
UFCS Uniform Function Call Syntax (UFCS) or Uniform Calling Syntax (UCS) or sometimes Universal Function Call Syntax is a programming language feature in D and Nim that allows any function to be called using the syntax for method calls (as in object-o ...
, a way to use free functions as extension methods provided in the
D programming language D, also known as dlang, is a multi-paradigm system programming language created by Walter Bright at Digital Mars and released in 2001. Andrei Alexandrescu joined the design and development effort in 2007. Though it originated as a re-engineeri ...
*
type class In computer science, a type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T and ...
es *
Anonymous type Anonymous types are a feature of C# 3.0, Visual Basic .NET 9.0, Oxygene, Scala and Go 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 ...
s *
Lambda expressions Lambda expression may refer to: *Lambda expression in computer programming, also called an anonymous function, is a defined function not bound to an identifier. * Lambda expression in lambda calculus, a formal system in mathematical logic and ...
*
Expression tree A binary expression tree is a specific kind of a binary tree used to represent expressions. Two common types of expressions that a binary expression tree can represent are algebraic and boolean. These trees can represent expressions that contain ...
s * Runtime alteration *
Duck typing Duck typing in computer programming is an application of the duck test—"If it walks like a duck and it quacks like a duck, then it must be a duck"—to determine whether an object can be used for a particular purpose. With nominative t ...


References

{{reflist


External links


Open source collection of C# extension methods libraries
Now archive
at CodeplexExtension method in C#C# Extension Methods
A collection.
extensionmethod.net Large database with C#, Visual Basic, F# and Javascript extension methodsExplanation and code exampleDefining your own functions in jQueryUniform function call syntax
* ttps://projectlombok.org/features/experimental/ExtensionMethod Extension Methods in Java with Lombokbr>Extension functions in Kotlin
Method (computer programming) Articles with example C Sharp code