If I have something like this:
class Base
{
public void Write()
{
if (this is Derived)
{
this.Name();//calls Name Method of Base class i.e. prints Base
((Derived)this).Name();//calls Derived Method i.e prints Derived
}
else
{
this.Name();
}
}
public void Name()
{
return "Base";
}
}
class Derived : Base
{
public new void Name()
{
return "Derived";
}
}
and use the following code to call it,
Derived v= new Derived();
v.Write(); // prints Base
then the Name
method of base class gets called. but what would be the actual type of this
keyword in the Write
method? if that is of Derived
type(as the Program control enters the first if block in Write
method) then it is calling the base Name
method, and why does the explicit casting,(Derived)this
, change the call to the Name
method of derived class?
Name()
by introducing anew
methodName()
with the same signature. – Endoenzyme