Reputation: 1172
If we have a simple class like this one:
class MyClass
{
public void DoSomething(object anObj)
{
Console.WriteLine("I am an Object: {0}", anObj);
}
public void DoSomething(string aStr)
{
Console.WriteLine("I am a String: {0}", aStr);
}
}
And now we do this:
var myClass = new MyClass();
myClass.DoSomething("A message");
The output is "I am a String: some text"
Ok. That is fine. But if we have a "similar" overload with a extension method, for instance:
class MyClass
{
public void DoSomething(object anObj)
{
Console.WriteLine("I am an Object: {0}", anObj);
}
}
static class MyClassExtension
{
public static void DoSomething(this MyClass myClass, string aStr)
{
Console.WriteLine("I am a String: {0}", aStr);
}
}
And now we execute the same code than before:
var myClass = new MyClass();
myClass.DoSomething("some text");
The output is "I am an Object: some text"
Could someone explain this behaviour?.
I guess it is related with when the methods are assigned but I am missing something here. I will appreciate any clarification. Thanks
Upvotes: 2
Views: 336
Reputation: 1499860
Could someone explain this behaviour?
Sure - extension methods aren't considered until after the compiler has failed to find a normal instance method to call. They're not part of the normal candidate set. If you do something that would make it fail to compile with the normal instance method, then it will be taken into consideration. For example, you could add another parameter, or change the parameter type of the existing method:
public void DoSomething(int foo)
Or even call it using a named argument instead, to make it only match the extension method:
myClass.DoSomething(aStr: "some text");
Upvotes: 5