I encountered a bug in my code today, highlighting the fact that apparently I don't understand polymorphism as well as I thought. Here's some sample code that illustrates my error:
internal class Startup{
interface IInterface{
bool SomeProp{get;}
}
class ClassA:IInterface{
public virtual bool SomeProp{get{return true;}}
}
class ClassB:ClassA{
public override bool SomeProp{get{return false;}}
}
public static void Main(String[] args){
IInterface test=new ClassB();
bool prop=test.SomeProp;
Console.WriteLine("result="+prop);
}
}
This shows a result of false, exactly as I'd expect. But consider this code:
internal class Startup{
interface IInterface{
bool SomeProp{get;}
}
class ClassA:IInterface{
public virtual bool SomeProp{get{return true;}}
}
class ClassB:ClassA{
public virtual bool SomeProp{get{return false;}}
}
public static void Main(String[] args){
IInterface test=new ClassB();
bool prop=test.SomeProp;
Console.WriteLine("result="+prop);
}
}
In this code, I accidentally typed the word "virtual" instead of "override" in ClassB. This was a typeo, but still, I would've expected one of the following things to happen:
(1) Compiler error, telling me that if I really wanted to create a new virtual property called SomeProp at the level of ClassB, I should've used the 'new' keyword.
or
(2) Complete passthrough of functionality: false would be returned by way of ClassB.
... the one thing I would NOT have expected is for true to be returned. Could someone explain what's happening in the second example with the typeo? Should I be using the virtual keyword at all in Class A? I would've though I had to, if I wanted its descendent ClassB to be able to override it.