Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 202
user1229895 Avatar asked Feb 24 '12 04:02

user1229895


1 Answers

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

like image 161
Robert Harvey Avatar answered Sep 19 '22 00:09

Robert Harvey