Extension method: Difference between revisions

Content deleted Content added
m Extension Methods: VB.NET will also be upgraded with this functionality.
Current Solution: Attempted to wikify the paragraph. May need more improving.
Line 6:
# The second option is to make a new, separate class and add a static method that takes an object of the class type and return a new object with the modification of choice.
 
==Current Solutionsolutions==
The first option is in principle easier, but it is unfortunately limited by the fact that many classes restricts inheritance of certain members or forbids it completely. This includes sealed class and the different primitive data types in C# such as [[int|Integer (computer science)]], [[float|Floating_point]] and [[string|String (computer science)]]. 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.
The first option sounds simpler, but actually it is harder, because sometimes you can't do this, because inheritance has some limitations, like you can't inherit a sealed class, or a primitive data type such as int, float, ... etc.
Ok, we still have the second option, which is writing a class anywhere, and add the function to it as static function. However, you can't do something like this
 
As an example, consider a need of extending the string class with a new reverse method whose return value was 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 not unlike the following:
string x = "some string value";
string y = xUtility.Reverse(x);
 
which you can't use the function as if it is part of the class itself, and you will end up with code similar to this
 
This may, however, become increasingly difficult to navigate as the library of utility methods and classes increases, especially for newcomers. The ___location is also less intuitive because, unlike most string methods, it would not be a member of the string class, but a completely different class altogether. A better syntax would therefore be the following:
string x = "some string value";
string y = Utilx.Reverse(x);
 
that's because you wrote the Reverse function the Util function.
 
==Extension Methods==