Extension method: Difference between revisions

Content deleted Content added
m Extension methods: fix lang name
Kyralessa (talk | contribs)
Restoring versioning problem section. If you disagree, let's discuss it on the talk page. I don't believe this problem with extension methods is well-known. I'm happy for you to revise wording etc.
Line 23:
</source>
 
===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:
<source lang="csharp">
Line 39:
The major difference between extension methods and normal, static helper methods is that static methods calls are [[Polish_notation|prefix notation]], whereas extension methods calls are in [[Infix_notation|infix notation]]. This leads to more readable code when the result of one operation is used for another operation.
 
;With static methods: <source lang="csharp">HelperClass.Operation2(HelperClass.Operation1(x, arg1), arg2)</source>"
 
;With extension methods: <source lang="csharp">x.Operation1(arg1).Operation2(arg2)</source>"
 
==The versioning problem==
In the current implementation, a member method with the same name as an extension method shadows the latter and makes it inaccessible. The IDE ([[Microsoft Visual Studio|Visual Studio]]) also does not warn about the naming conflict.
 
Instance methods are always preferred over extension methods, even when new instance methods replace previously-existing extension methods. However, Visual Studio gives no warning about naming conflicts. Consider this C# code:
 
<source lang="csharp">
class AlphabetMaker { }
 
static class ExtensionMethods
{
static public string GetAlphabet(this AlphabetMaker am)
{
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
}
</source>
 
The GetAlphabet extension method can be called in this way:
 
<source lang="csharp">
AlphabetMaker am = new AlphabetMaker();
Console.WriteLine(am.GetAlphabet()); // output: ABCDEFGHIJKLMNOPQRSTUVWXYZ
</source>
 
An instance method is then added to the AlphabetMaker class:
<source lang="csharp">
class AlphabetMaker
{
public string GetAlphabet()
{
return "abc";
}
}
</source>
 
The same code using AlphabetMaker now returns a different result:
 
<source lang="csharp">
AlphabetMaker am = new AlphabetMaker();
Console.WriteLine(am.GetAlphabet()); // output: abc
</source>
 
The new instance method has replaced the extension method, but the Visual Studio compiler gives no indication that a naming conflict exists.
 
==See also==