Extension method: Difference between revisions

Content deleted Content added
Extension methods: syntax highlighting
rewrite
Line 43:
;With extension methods: <source lang="csharp">x.Operation1(arg1).Operation2(arg2)</source>
 
==Extension methods and Instance methods==
==The versioning problem==
In C# 3.0, both an instance method as well as an extension method with the same signature can exist for a class. In such a scenario, the instance method is preferred over the extension method. Neither the compiler nor the [[Microsoft Visual Studio]] IDE warns about the naming conflict. Consider this C# code:
 
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 stringvoid GetAlphabet() //When this AlphabetMakermethod am)is implemented,
{ //it will shadow the implementation
{
Console.WriteLine("abc"); //in the ExtensionMethods class.
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
}
</source>
 
static class ExtensionMethods
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
{
static public stringvoid GetAlphabet(this AlphabetMaker am) //This will only be called
{ //if there is no instance
{
Console.WriteLine("ABC"); //method with the same signature.
return "abc";
}
}
</source>
 
Result with the instance method not implemented:
The same code using AlphabetMaker now returns a different result:
ABC
 
<source lang="csharp">
AlphabetMaker am = new AlphabetMaker();
Console.WriteLine(am.GetAlphabet()); // output: abc
</source>
 
Result with the instance method implemented:
The new instance method has replaced the extension method, but the Visual Studio compiler gives no indication that a naming conflict exists.
abc
 
==See also==