[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Validate optional parameters in C#

[Validate optional parameters in C#]

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 Person 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.