BLOG.CSHARPHELPER.COM: Validate optional arguments in C#
Validate optional arguments in C#
The example Use named and optional arguments in C# explains how to use named and optional arguments to let the calling code omit any combination of optional arguments. 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 arguments and throws an exception if they are all blank. If any contact method is non-blank, then the constructor uses the arguments to initialize the object.
good
Reply to this