Extension method

Extension method

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.

The problem

Normally, in a situation where it is necessary to add more functionality to a class - for instance a new method - it would simply be a matter of modifying the class' source code and recompiling the binaries with these new changes to make this effect. However, in some cases, especially when it comes to classes that are built-in into the .NET-framework or reside in third-party assemblies, the programmer does not have access to the source code and is thus unable to change the behavior of the class directly. Hence, the programmer has been left with two other more limited and less intuitive (respectively) options:
# The first option is to inherit the class and then add the functionality.
# The second option is to make a new, separate class and add a static method that takes an object of the class type and returns a new object with the modification of choice.

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 forbids it completely. This includes sealed class and the different primitive data types in C# such as int, 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: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();

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 Util{ public static string Reverse(this string input) { char [] chars = input.ToCharArray(); Array.Reverse(chars); return new String(chars);

The major difference between extension methods and normal, static helper methods is that static methods calls are prefix notation, whereas extension methods calls are in infix notation. This 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)

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 IDE warns about the naming conflict. Consider this C# class, where the GetAlphabet() method is invoked on an instance of this class:

class AlphabetMaker { public void GetAlphabet() { //When this method is implemented, Console.WriteLine("abc"); //it will shadow the implementation } //in the ExtensionMethods class.}

static class ExtensionMethods{ static public void GetAlphabet(this AlphabetMaker am) { //This will only be called Console.WriteLine("ABC"); //if there is no instance } //method with the same signature. }

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

ee also

* Anonymous types
* Lambda expressions
* Expression trees
* Runtime alteration

References

* [http://spellcoder.com/blogs/bashmohandes/archive/2006/12/08/4027.aspx C# 3.0 Language Enhancements Presentation]
* [http://www.interact-sw.co.uk/iangblog/2005/09/26/extensionmethods C# 3.0 Extension Methods]
* [http://blogs.msdn.com/abhinaba/archive/2005/09/15/467926.aspx C# 3.0 I Like Extension Methods]
* [http://community.bartdesmet.net/blogs/bart/archive/2006/12/06/C_2300_-3.0-Feature-Focus-_2D00_-Part-4-_2D00_-Extension-Methods.aspx C# 3.0 Feature Focus - Part 4 - Extension Methods]
* [http://dotnet.agilekiwi.com/blog/2007/11/making-extension-methods-safer.html A suggestion for making C# extension methods safer - i.e. allowing compiler warnings on like-named instance methods]

External links

* [http://www.extensionmethod.net/ ExtensionMethod.NET Repository]


Wikimedia Foundation. 2010.

Игры ⚽ Нужно решить контрольную?

Look at other dictionaries:

  • Extension und Intension — sind moderne semantische Ausdrücke, insbesondere der Logik, Sprachphilosophie und Linguistik, die den Umfang beziehungsweise Inhalt von Zeichen oder sprachlicher Ausdrücke bedeuten. Sie werden vornehmlich statt der traditionellen Ausdrücke… …   Deutsch Wikipedia

  • Method of image charges — The method of image charges (also known as the method of images and method of mirror charges) is a basic problem solving tool in electrostatics. The name originates from the replacement of certain elements in the original layout with imaginary… …   Wikipedia

  • Method of steepest descent — For the optimization algorithm, see Gradient descent. In mathematics, the method of steepest descent or stationary phase method or saddle point method is an extension of Laplace s method for approximating an integral, where one deforms a contour… …   Wikipedia

  • Extension (Mac OS) — On the Apple Macintosh operating system prior to Mac OS X, extensions were small pieces of code that extended the system s functionality. They were run initially at start up time, and operated by a variety of mechanisms, including trap patching… …   Wikipedia

  • method — The mode or manner or orderly sequence of events of a process or procedure. SEE ALSO: fixative, operation, procedure, stain, technique. [G. methodos; fr. meta, after, + hodos, way] Abell Kendall m. a …   Medical dictionary

  • Intension und Extension — Extension und Intension (auch Begriffsumfang und Begriffsinhalt) bezeichnen in der Logik und Sprachphilosophie verschiedene, nach Meinung mancher Autoren entgegengesetzte Eigenschaften von Begriffen. Inhaltsverzeichnis 1 Extension 2 Intension 3… …   Deutsch Wikipedia

  • LZH extension — extension of a file compressed by the LZH compression method …   English contemporary dictionary

  • Life extension — refers to an increase in maximum or average lifespan, especially in humans, by slowing down or reversing the processes of aging. Average lifespan is determined by vulnerability to accidents and age related afflictions such as cancer or… …   Wikipedia

  • Filename extension — A filename extension is a suffix (separated from the basefilename by a dot) to the name of a computer file applied to indicate the encoding (file format) of its contents or usage. Some filesystems limit the length of the extension (such as the… …   Wikipedia

  • Dynamic systems development method — Model of the DSDM Atern project management method …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”