C# 4.0 enabled optional parameters, which greatly simplify the case where you want to pass arguments in variable order, or pass arguments where some of the arguments are omitted, and you wish to have the inner variables of the Class corresponding to the arguments omitted set to default values.
An important requirement of optional parameters is: if one optional variable has a value declared in the parameter list, then all other optional parameters must also have their values declared: that can be worked around by using the [Optional] Attribute as shown here:
using System.Runtime.InteropServices;
public class OptionalParameterClassDemo
{
public int requiredInt = 100;
public string requiredString = "default string required";
public int? optionalInt = 999;
public string optionalString = "default string optional";
public OptionalParameterClassDemo()
{
}
public OptionalParameterClassDemo(int reqInt, string reqString, [Optional] int? optInt, [Optional] string optString)
{
requiredInt = reqInt;
requiredString = reqString;
if (optInt != null) optionalInt = optInt;
if (optString != null) optionalString = optString;
}
}
I suggest you test the use of the Class like this:
OptionalParameterClassDemo optTest0 = new OptionalParameterClassDemo(11, "eleven");
OptionalParameterClassDemo optTest1 = new OptionalParameterClassDemo(100, "one hundred", optString: "777");
OptionalParameterClassDemo optTest2 = new OptionalParameterClassDemo(100, "one hundred", optInt: 888);
I suggest you try this code, set a breakpoint after the three calls to create an instance of OptionalParameterClassDemo, and examine the internal values in each instance.
Note that you can pass parameter arguments out-of-sequence using this syntax
OptionalParameterClassDemo optTest3 = new OptionalParameterClassDemo(optInt: 888, optString: "some string", reqInt: 1111, reqString: "some required string");
But, in this case, you must specify
all arguments.
Note the use of a nullable int in the above code which enables us to test whether the optional integer parameter is supplied in the same way we test if the optional string parameter is supplied.
If we didn't use a nullable int, then we couldn't tell if the parameter was omitted, since an int is automatically initialized to zero: how would we recognize the difference between the user supplying a zero, and the default initialization supplying the zero ?