Validate optional parameters in C#

[optional parameters]

The example Use named and optional parameters in C# explains how to use named and optional parameters to let the calling code omit any combination of parameters. In many applications, you may not want to allow the user to omit every possible combination, just most of them. In that case, you can add some code to the method to verify that the combination provided by the calling code is allowed.

In this example, the Parson class requires a name and at least one contact method. The following code shows the constructor, which ensures that there is at least one contact method.

public Person(string name, string address = "", string email = "",
    string sms_phone = "", string voice_phone = "", string fax = "")
{
    // Make sure at least one contact method is present.
    if (address == "" && email == "" && sms_phone == "" &&
        voice_phone == "" && fax == "")
            throw new ArgumentException(
                "You must provide at least one contact method.");

    Name = name;
    Address = address;
    Email = email;
    SmsPhone = sms_phone;
    VoicePhone = voice_phone;
    Fax = fax;
}

When the program creates a Person object, the constructor checks the contact method parameters and throws an exception if they are all blank. If any contact method is non-blank, then the constructor uses the parameters to initialize the object.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in methods, syntax, variables and tagged , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Validate optional parameters in C#

Leave a Reply

Your email address will not be published. Required fields are marked *