Why in a child class, i can not call the extention method defined for the derived class by calling the base class directly ( i get a compile error that the base class does not contain a definition for the extention method). But instead, i can call the extention method without any compile errors when i call it directly from the child intance. Below is the code for my question :
using System;
using System.Reflection;
public class Program
{
public static void Main()
{
Child child = new Child();
child.TestMethod();
}
}
// Derived class
public class Mother
{
}
// Child class
public class Child : Mother
{
public Child() : base()
{
}
public void TestMethod()
{
this.ExtentionMethod(3);// Ok: no compile errors
base.ExtentionMethod(3);// Ko: Compilation error (line 27, col 8): 'Mother' does not contain a definition for 'ExtentionMethod'
}
}
public static class Extender
{
public static void ExtentionMethod(this Mother mother, int i)
{
Console.WriteLine($"Mother extention method {i}");
}
}
When you call an extension method, the compiler looks at the type of the reference on the left and finds the most appropriate method. So when you call this.ExtentionMethod
, the type of this
is used to find the best method.
So in your case, the compiler will look for an extension with a Child
first parameter. Since there is not one, it will then find the one with a Mother
first parameter (since a Child
"is-a" Mother
).
Using base
does not do a cast - it is used to access members of the base class. Since extension methods are not "members", base
does not do what you expect it to do.
An alternative might be to cast this
to the base class instead:
((Mother)this).ExtentionMethod(3);
Although I would note that you don't have a different extension method for the derived class, so with what you posted there would be no difference between this.ExtensionMethod
and ((Mother)this).ExtensionBethod
. The same method (with the same input values) are going to be called.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments