Microsoft Developer Network >
Forenhomepage
>
Visual C# Language
>
Looking for Feedback About Extension Methods Article
Looking for Feedback About Extension Methods Article
- Hello,
I've been thinking about the best ways to use extension methods, and I've written an article based on what I know at
http://gen5.info/q/2008/07/03/extension-methods-nulls-namespaces-and-precedence-in-c/
There's some stuff that I think I understand pretty well, but there still are some things that I find murky in the C# 3.0 specification. I'm looking for general feedback about the article, but I'm particularly interested in finding more details about how precedence works, particularly when there are conflicting "using" directives. For instance, does the compiler give an error in that case, or does it just do something automatically?
Thanks for any information you can give me.
Alle Antworten
- Well, the easiest way too answer the precedence question is to do a little example:
Program#11 public class Program 2 { 3 static void Main(string[] args) 4 { 5 var program = new Program(); 6 Console.WriteLine(program.SomeNumber()); 7 } 8 9 public int SomeNumber() 10 { 11 return 5; 12 } 13 } 14 15 public static class Extension1 16 { 17 public static int SomeNumber(this Program program) 18 { 19 return 9; 20 } 21 }
In the Program#1 the output is 5. This means that the instance field takes precedence over the extension method.
Program#21 { 2 public class Program 3 { 4 static void Main(string[] args) 5 { 6 var program = new Program(); 7 Console.WriteLine(program.SomeNumber()); 8 } 9 10 public int SomeNumber() 11 { 12 return 5; 13 } 14 } 15 16 public static class Extension1 17 { 18 public static int SomeNumber(this Program program) 19 { 20 return 9; 21 } 22 } 23 24 public static class Extension2 25 { 26 public static int SomeNumber(this Program program) 27 { 28 return 17; 29 } 30 }
In program #2, I added a second Extension method by the same name. This doesn't error since the compiler can still resolve this un-ambiguously to the instance method since instance methods always take precedence.
Program#31 public class Program 2 { 3 static void Main(string[] args) 4 { 5 var program = new Program(); 6 Console.WriteLine(program.SomeNumber()); 7 } 8 } 9 10 public static class Extension1 11 { 12 public static int SomeNumber(this Program program) 13 { 14 return 9; 15 } 16 } 17 18 public static class Extension2 19 { 20 public static int SomeNumber(this Program program) 21 { 22 return 17; 23 } 24 }
In program#3, I removed the instance method and now the compiler throws this error:
Error The call is ambiguous between the following methods or properties: '
Extension1.SomeNumber(Program)' and 'Extension2.SomeNumber(Program)'
Since extension methods have the same precedence as other extension method, having two with the same name and no instance method causes the compiler to throw a fit since it can't decide.
I hope that helps.
-Matt - Very much so. Thanks!

