C# : overloading constructors with optional parameters & named arguments?

user1229895 picture user1229895 · Feb 24, 2012 · Viewed 23.4k times · Source

This isn't a question on proper coding practice, I'm just working through the semantics. lets 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 thusly...?

FooClass foo1 = new FooClass(num:1);  

// where I'm only passing one named argument, relying on the optionals to take care of the rest

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

FooClass foo2 = new FooClass();

Answer

Robert Harvey picture Robert Harvey · Feb 24, 2012

Use of 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 either is optional or corresponds, by name or by position, to a single argument in the calling statement, and that argument can be converted to the type of the parameter.

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

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

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