Content deleted Content added
m →Extension methods: fix lang name |
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>
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.
==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==
|