Extension methods dispatch based on static type
suggest changeThe static (compile-time) type is used rather than the dynamic (run-time type) to match parameters.
public class Base
{
public virtual string GetName()
{
return "Base";
}
}
public class Derived : Base
{
public override string GetName()
{
return "Derived";
}
}
public static class Extensions
{
public static string GetNameByExtension(this Base item)
{
return "Base";
}
public static string GetNameByExtension(this Derived item)
{
return "Derived";
}
}
public static class Program
{
public static void Main()
{
Derived derived = new Derived();
Base @base = derived;
// Use the instance method "GetName"
Console.WriteLine(derived.GetName()); // Prints "Derived"
Console.WriteLine(@base.GetName()); // Prints "Derived"
// Use the static extension method "GetNameByExtension"
Console.WriteLine(derived.GetNameByExtension()); // Prints "Derived"
Console.WriteLine(@base.GetNameByExtension()); // Prints "Base"
}
}
Also the dispatch based on static type does not allow an extension method to be called on a dynamic
object:
public class Person
{
public string Name { get; set; }
}
public static class ExtenionPerson
{
public static string GetPersonName(this Person person)
{
return person.Name;
}
}
dynamic person = new Person { Name = "Jon" };
var name = person.GetPersonName(); // RuntimeBinderException is thrown
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents