C #: overload constructors with optional parameters and other arguments?

This is not a question of good coding practice, I'm just working on semantics. let's say I have the following constructors ...

public FooClass(string name = "theFoo") { fooName = name; } public FooClass(string name, int num = 7, bool boo = true) : this(name) { fooNum = num; fooBool = boo; } 

is it possible to use named arguments ...?

 FooClass foo1 = new FooClass(num:1); 

// where I pass only one named argument, relying on options to take care of the rest

or call the constructor FooClass (string, int, bool) with no arguments? how in...

 FooClass foo2 = new FooClass(); 
+6
source share
2 answers

Using named and optional arguments affects overload resolution in the following ways:

  • A method, indexer, or constructor is a candidate for execution if each of its parameters is either optional or matches one name or position to one argument in the calling statement, and this argument can be converted to the type of the parameter.

  • If more than one candidate is found, overload resolution rules for preferred conversions apply to arguments that are explicitly specified. Missing arguments for optional parameters are ignored.

  • If two candidates are considered equally good, preference is given to a candidate who does not have optional parameters for which arguments were omitted in the call. This is a consequence of the general preference for overload resolution for candidates with fewer parameters.

http://msdn.microsoft.com/en-us/library/dd264739.aspx

+5
source

Additional parameters are defined at the end of the parameter list after any required parameters. If the caller provides an argument for any of several optional parameters, it must provide arguments for all previous optional parameters. Comma-separated spaces in the argument list are not supported.

Moreover,

A named argument can follow positional arguments, as shown here. CalculateBMI (123, height: 64); However, a positional argument cannot follow a named argument. The following statement causes a compiler error. // CalculateBMI (weight: 123, 64);

0
source

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


All Articles