Extension method: Difference between revisions

Content deleted Content added
editing a link
Line 5:
In [[object-oriented computer programming]], an '''extension method ''' is a [[Method (computer programming)|method]] added to an object after the original object was [[Compiler|compiled]]. 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.<ref name="ms_ext">{{cite web|url=http://msdn.microsoft.com/en-us/library/bb383977.aspx|title=Extension Methods|publisher=Microsoft|accessdate=2008-11-23}}</ref>
 
Not all languages implement extension methods in an equally safe manner, however. For instance, languages such as C#, Java (via Manifold or [https://projectlombok.org/features/experimental/ExtensionMethod Lombok]), and Kotlin don't alter the extended class in any way, because doing so may break [[class hierarchy|class hierarchies]] and interfere with virtual method dispatching. This is why these languages strictly implement extension methods statically and use [[static dispatch]]ing to invoke them.
 
==Support in programming languages==
Line 71:
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".