Extension method: Difference between revisions

Content deleted Content added
Kyralessa (talk | contribs)
New section on inherent versioning problem in extension methods
The versioning problem: the entire thing can be stated in one line which I am going to add. this thing was how-to-ish and uncited anyway
Line 43:
With extension methods: "x.Operation1(arg1).Operation2(arg2)"
 
==The versioning problem==
 
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==