Looking at how the as
keyword works in C#, I can see that it allows for casting where explicit casting (i.e. using brackets) prevents compilation.
However In the code below I find that if I override a method in a derived class, and then safe cast as the base class, that the overridden method in the derived class still executes. Why is this? I was expecting the method as defined on the base class to execute instead.
class Base
{
public override string ToString()
{
return base.ToString();
}
public string OtherMethod()
{
return "Other method";
}
}
class Derived : Base
{
public override string ToString()
{
return "Derived class";
}
}
class Program
{
static void Main()
{
Derived d = new Derived();
Base b = new Base();
System.Console.WriteLine(b.ToString()); // Base
System.Console.WriteLine(d.ToString()); // Derived class
System.Console.WriteLine((d as Base).ToString()); // Derived class => WHY IS THIS?
System.Console.WriteLine((d as Base).OtherMethod()); // Other method
// System.Console.WriteLine((Base)d.OtherMethod()); // --- prevents compilation
// As noted in the comments, this works
System.Console.WriteLine(((Base)d).OtherMethod()); // Other method
System.Console.ReadLine();
}
}
OtherMethod
.((Base)d).OtherMethod()
should compile just fine. – Damien_The_Unbeliever