I have noticed when using a virtual method that has an optional parameter. When you override this method and use a different default value for the optional parameter it uses the original. It seems a bit strange to me.
static void Main(string[] args)
{
List<Piece> Pieces = new List<Piece>();
Pieces.Add(new Piece());
Pieces.Add(new Pawn());
foreach(var v in Pieces)
{
Console.WriteLine(v.getPos());
}
Console.ReadKey();
}
class Piece
{
public virtual long getPos(bool enPassant = false)
{
if (enPassant)
return 2;
return 1;
}
}
class Pawn:Piece
{
public override long getPos(bool enPassant = true)
{
if (enPassant)
return 3;
return 4;
}
}
Initially I would expect the output to be
1
3
But it returns
1
4
Which means they are both False. I can even rename the parameter to a different name, and use the different name in the method body and it still behaves the same. Which tells me the default parameter value can't be overridden because that's part of the contract? Obviously if I cast the item to a Pawn object and then call GetPos() it returns a 3 instead of a 4.
I just thought this was interesting as I expected it to behave differently. I was just wondering if I am missing anything to make this work as I originally intended.