An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example.
In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-oriented programming languages.
In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.
This code won't compile:
using System;
using System.Runtime.CompilerServices;
static class Extensions {
public static void Foo(this A a, Exception e = null, string memberName = "") {
}
public static void Foo<T>(this A a, T t, Exception e = null, string memberName = "")
where T : class, IB {
}
}
interface IB { }
class A { }
class Program {
public static void Main() {
var a = new A();
var e = new Exception();
a.Foo(e); //<- Compile error "ambiguous call"
}
}
But if I delete last string
arguments everything is fine:
public static void Foo(this A a, Exception e = null) {
}
public static void Foo<T>(this A a, T t, Exception e = null)
where T : class, IB {
}
Question is - why these optional string
arguments break compiler's choice of method call?
Added: Clarified question: I dont get why compiler can't choose right overload in the first case but could do it in second one?
Edited:
[CallerMemberName]
attribute is not a cause of a problem here so I've deleted it from question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With