I’m wondering about the behavior of extension methods in C#. Please see the examples below:
static string ExtendedToString( this object oObj )
{
return "Object";
}
static string ExtendedToString( this Array oArray )
{
return "Array";
}
// Example 1: int array - working as expected.
int[] o = new int[] { 1, 2, 3 };
o.ExtendedToString( ); // returns "Array"
// Example 2: array as object - did not expect the result.
object o = new int[] { 1, 2, 3 };
o.ExtendedToString( ); // returns "Object"
Why is (in the last case) the object’s extension method called and not the one for int[]?
Overload resolution is performed at compile time. The compiler sees that
ois declared asobject, so it calls the overload that takes anobject. The fact thatoactually contains an array at runtime is irrelevant, because the compiler doesn’t know it.That’s actually not specific to extension methods, you would get the same result by calling it as a normal static method (
ExtensionsClass.ExtendedToString(o))