Using Additional Arguments

I have a method with 2 optional parameters.

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

Now I'm trying to use this method in another place where I don’t want to specify the Brand argument and only int , but I get errors with this code:

 _order.GetComputers(ram); 

Errors I get:

 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 
+4
source share
3 answers

You must provide the name of an optional argument if you intend to skip other optional arguments.

 _order.GetComputers(ramSizeInGB: ram); 
+9
source

To allow earlier arguments to be populated by the compiler, you need to specify the names of later ones:

 _order.GetComputers(ramSizeInGB: ram); 

Basically, the C # compiler assumes that if you do not specify argument names, the arguments you provide are in extra order. If you do not specify values ​​for all parameters, and the remaining parameters have default values, these default values ​​will be used.

So, they are all valid (subject to the appropriate brand and ram values):

 _order.GetComputers(brand, ram); // No defaulting _order.GetComputers(brand); // ramSizeInGB is defaulted _order.GetComputers(brand: brand); // ramSizeInGB is defaulted _order.GetComputers(ramSizeInGB: ram); // brand is defaulted _order.GetComputers(); // Both arguments are defaulted 
+5
source

The correct syntax is to use named arguments in combination with optional parameters, for example:

 _order.GetComputers(ramSizeInGB: ram); 

Optional parameters can be skipped (without using named arguments) only when they are located after the specified arguments, so this will be fine:

 _order.GetComputers(new Brand()); 

like this

 _order.GetComputers(); 

To understand why this should be done this way, consider a method with this signature:

 public void Method(double firstParam = 0, long secondParam = 1) Method(3); 

Here, the compiler cannot deduce if the developer should have called the method with the first parameter or with the second parameter, so the only way to distinguish yourself is to explicitly indicate which arguments are mapped to which parameters.

+2
source

Source: https://habr.com/ru/post/1445061/


All Articles