Search code examples
c#optional-arguments

Using optional arguments


I have a method with 2 optional parameters.

public IList<Computer> GetComputers(Brand? brand = null, int? ramSizeInGB = null)
{
    return new IList<Computer>();
}

I'm now trying to use this method elsewhere where I do not want to specify the Brand argument and just the int but I'm getting errors using this code:

_order.GetComputers(ram);

Errors I am receiving:

Error   1   The best overloaded method match for 'ComputerWarehouse.Order.GetComputers(ComputerWarehouse.Brand?, int?)' has some invalid arguments  C:\Users\avmin!\Documents\InnerWorkings Content\630dd6cf-c1a2-430a-ae2d-2bfd995881e7\content\T0062A2-CS\task\ComputerWarehouse\ComputerStore.cs 108 59  ComputerWarehouse
Error   2   Argument 1: cannot convert from 'int?' to 'ComputerWarehouse.Brand?'    C:\Users\avmin!\Documents\InnerWorkings Content\630dd6cf-c1a2-430a-ae2d-2bfd995881e7\content\T0062A2-CS\task\ComputerWarehouse\ComputerStore.cs 108 79  ComputerWarehouse

Solution

  • You have to specify the name of the optional argument if you are going to skip other optional arguments.

    _order.GetComputers(ramSizeInGB: ram);