C # Optional parameters in virtual method and overridden method

I noticed when using a virtual method that has an optional parameter. When you override this method and use a different default for an optional parameter, it uses the original. It seems a little 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;
    }
}

      

I originally expected the output to be

1
3

      

But it returns

1
4

      

This means they are both false. I can even rename the parameter to a different name and use a different name in the body of the method and it still behaves the same. What tells me that the default parameter value cannot be overridden due to that part of the contract? Obviously, if I pass the item to the Pawn object and then call GetPos (), it will return 3 instead of 4.

I just thought it was interesting as I expected it to behave differently. I'm just wondering if I'm missing anything to make this work as I originally planned.

+3


source to share


2 answers


Additional options are resolved at compile time at compile time.

This means that it is v.GetPos()

actually compiled to v.GetPos(false)

, because it is v

printed Piece

. The fact that the call is virtual and ends up being allowed for Pawn.GetPos(bool)

doesn't matter what happens after the optional parameter is already set.



This is why you get the result you see.

+4


source


I think this is because of the trigger. You did v.getPos (); no fool. because there is no insert bool I think its value is default false and returns 4 istead.



0


source







All Articles