Extension method: Difference between revisions

Content deleted Content added
m Extension methods: still needs cleanup, looks like some non-native english idioms in there
Line 1:
{{Cleanup|January 2007}}
One'''Extension method''' is a [[programming language]] feature of the features of [[C-Sharp|C# 3.0]] and [[VB.NET|VB.NET 9.0]]
=Extension methods=
 
One of the features of [[C-Sharp|C# 3.0]] and [[VB.NET|VB.NET 9.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 buildbuilt-in into the .NET-framework or reside in third-party [[.NET assembly|assemblies]], the programmer does not have access to the source code and is thus unable to change the behavior of the class directly. Heretofore, 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 returnreturns a new object with the modification of choice.
 
==Current solutions==
The first option is in principle easier, but it is unfortunately limited by the fact that many classes restrictsrestrict inheritance of certain members or forbids it completely. This includes sealed class and the different primitive data types in C# such as [[Integer (computer science)|int]], [[Floating point|float]] and [[String (computer science)|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, lets 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 primitive 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);